简体   繁体   中英

Changing value of text field with jQuery

I have a form input text field, and I want to change the text inside of the text field when the user clicks a button. I can get the specific textfield with jQuery, but cannot change the text with .val(). Is there another way this can be done, or am I doing something wrong.

Here is the text field:

<input type="text" name="textBox" id="Stage 1text" size="20" value="Enter Current Comp." align="center">

Then I use this to identify and change the text field. where in this case stage = "Stage 1" and dance is the string I want to place in the text field.

str = "#" + stage + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);

id attributes should not contain spaces.

You could change your code like so:

<input type="text" name="textBox" id="Stage_1text" size="20" value="Enter Current Comp." align="center">

str = "#" + stage.replace(' ','_') + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);

An ID should not have spaces. Stage 1text is an invalid ID

Add an underscore instead of space

<input type="text" name="textBox" id="Stage_1text" size="20" value="Enter Current Comp." align="center">

and try below,

//           v--- assuming this will be Stage_1
str = "#" + stage + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);

incase if stage is returned from backend.. then simply replace space with _

 str = "#" + stage.replace(/ /g,"_") + 'text';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM