【问题标题】:Changing value of text field with jQuery使用 jQuery 更改文本字段的值
【发布时间】:2012-09-19 21:49:14
【问题描述】:

我有一个表单输入文本字段,我想在用户单击按钮时更改文本字段内的文本。我可以使用 jQuery 获取特定的文本字段,但不能使用 .val() 更改文本。有没有其他方法可以做到这一点,或者我做错了什么。

这是文本字段:

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

然后我使用它来识别和更改文本字段。在这种情况下,stage = "Stage 1",而 dance 是我要放置在文本字段中的字符串。

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

【问题讨论】:

  • ID 不能有空格。 Stage 1text 是无效 ID
  • 谢谢,我不知道 id 不能有空格。

标签: javascript jquery forms textfield


【解决方案1】:

ID 不应包含空格。第 1 阶段文本是无效 ID

添加下划线而不是空格

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

并在下面尝试,

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

如果stage是从后端返回的..那么只需用_替换空格

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

【讨论】:

    【解决方案2】:

    id 属性不应包含空格。

    您可以像这样更改您的代码:

    <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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多