I want to add some value in an input field with jQuery. The problem is with the ID of the input field. I am using the id such as options[input2]
. In that case my code does not work. If I use ID like input2
, then it works fine. I need to use options[input2]
, how can I fix the code?
HTML:
<div>
<h3>Working</h3>
<input id="input1" type="text" value="" />
<input class="button" type="button" value="Add value" />
</div>
<div>
<h3>Not working</h3>
<input id="options[input2]" type="text" value="" />
<input class="button" type="button" value="Add value" />
</div>
jQuery:
$('.button').click(function(){
var fieldID = $(this).prev().attr("id");
$('#' + fieldID).val("hello world");
});
Demo:
http://jsfiddle.net/4XR8M/
The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element.
You can do it as below.
$(this).prev('input').val("hello world");
Live Demo
You can simply use
$(this).prev().val("hello world");
JSFiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With