开发者

How do I change the value of an input element?

is it possible to "override/overwrite" an input element fixed value using javascript and/or jquery?

i.e. if i have an input element like this:

<div id="myDiv">
    <input type="text" name="inputs" value="someValue" />
</div>

is it possible to make a jquery object of that element and then change its value to something else then rewrite the jquery object to the dom?? I'm trying but obviously I haven't got good results!

I've been trying something like this:

开发者_StackOverflow社区
$('input').val("someOtherDynamicValue");
var x = $('input');
$("#myDiv").html(x);


If you just want to manipulate the value of the input element, use the first line of your code. However it will change the value of every input element on the page, so be more specific using the name or the id of the element.

$('input[name=inputs]').val("someOtherDynamicValue");

Or if the element had an id

$('#someId').val('some Value');

Check out jQuery's selectors (http://api.jquery.com/category/selectors/) to see how to get whatever element you need to manipulate with jQuery.


You can directly access the value via the $.val() method:

$("[name='inputs']").val("Foo"); // sets value to foo

Without needing to re-insert it into the DOM. Note the specificity of my selector [name='inputs'] which is necessary to modify only one input element on the page. If you use your selector input, it will modify all input elements on the page.

Online Demo: http://jsbin.com/imuzo3/edit


//Changes on the load of form

$(document).ready(function(){
    $('#yourTxtBoxID').val('newvalue');
});

//Changes on clicking a button

$(document).ready(function(){
    $('#somebuttonID').click(function(){
    $('#yourTxtBoxID').val('newvalue');
});
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜