Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding value to input field with jQuery

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/

like image 524
user966582 Avatar asked Sep 06 '13 10:09

user966582


People also ask

How do I set the value of a element in jQuery?

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.

How can get input tag value in jQuery?

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.


2 Answers

You can do it as below.

$(this).prev('input').val("hello world");

Live Demo

like image 140
Dipesh Parmar Avatar answered Sep 19 '22 11:09

Dipesh Parmar


You can simply use

 $(this).prev().val("hello world");

JSFiddle Demo

like image 40
Satpal Avatar answered Sep 19 '22 11:09

Satpal