How do I change the value of an input element?
Is it possible to "override / overwrite" the fixed value of an input element 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 create a jquery object of that element and then change its value to something else and then overwrite the jquery object in the dom ?? I'm trying, but obviously I don't have good results!
I've tried something like this:
$('input').val("someOtherDynamicValue");
var x = $('input');
$("#myDiv").html(x);
a source to share
You can directly access the value using the method $.val()
:
$("[name='inputs']").val("Foo"); // sets value to foo
No need to re-insert it into the DOM. Pay attention to the specifics of my selector [name='inputs']
, which is only needed to change one input element per page. If you use a selector input
, it will change all the input elements on the page.
Demo version online: http://jsbin.com/imuzo3/edit
a source to share
If you just want to manipulate the value of an input element, use the first line of your code. However, it will change the meaning of every input element on the page, so be more specific using the element name or id.
$('input[name=inputs]').val("someOtherDynamicValue");
Or if the element had an id
$('#someId').val('some Value');
Check out the jQuery selectors ( http://api.jquery.com/category/selectors/ ) for how to get any element you need to manipulate with jQuery.
a source to share