Adding a value to an input field using jQuery

I want to add some value to the input field using jQuery. The problem is with the input field identifier. I use id, for example options[input2] . In this case, my code does not work. If I use an 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/

+4
source share
3 answers

You can do this as shown below.

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

Live demo

+16
source

You can just use

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

JSFiddle Demo

+2
source

You need to exit [ and ] . Try the following:

 $('.button').click(function(){ var fieldID = $(this).prev().attr("id"); fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1"); $('#' + fieldID).val("hello world"); }); 

Demo: http://jsfiddle.net/7RJtf/1/

+1
source

Source: https://habr.com/ru/post/1500892/


All Articles