在更多输入字段中设置值

时间:2018-01-14 14:36:12

标签: javascript php jquery html input

如何通过JavaScript或jQuery在更多输入字段中设置值(默认值)?谢谢。

<form method="" action="">
Name: <input type="text" id="id1" value="<?php $value; ?>" placeholder="Your name"> <br><br>
Surname: <input type="text" id="id1" value="<?php $value; ?>" placeholder="Your surname"> <br><br>
Email: <input type="text" id="id1" value="<?php $value; ?>" placeholder="Your email"> <br><br>
</form>

4 个答案:

答案 0 :(得分:1)

迭代所有输入,然后使用element.value syntaxis设置默认值。

Array.from(document.getElementsByTagName("INPUT")).forEach(input => {
  input.value = "Default value has been assigned";
});
Input 1: <input type="text">
Input 2: <input type="text">
Input 3: <input type="text">

答案 1 :(得分:1)

您忘记了echo这些值。 下面是更新的代码。

<form method="" action="">
Name: <input type="text" id="id1" value="<?php echo $value; ?>" placeholder="Your name"> <br><br>
Surname: <input type="text" id="id1" value="<?php echo $value; ?>" placeholder="Your surname"> <br><br>
Email: <input type="text" id="id1" value="<?php echo $value; ?>" placeholder="Your email"> <br><br>
</form>

答案 2 :(得分:1)

诀窍是提出一个选择器,选择你想要改变的所有元素。

因为您想要更改文本框的所有值,所以以下选择器将执行:$("input['type=text']")。并改变或设置其价值:只需:$("input['type=text']").val('value');

查看正在运行的示例:https://jsfiddle.net/2od89uou/1/

答案 3 :(得分:0)

要在jQuery中设置输入字段的值,您可以使用.val()方法:

$('#id1').val("This is a value");// the selector #id1 selects all elements with id "id1"

如果你想将多个输入设置为相同的值,你需要使用另一个选择器,因为id的设计是唯一的:

$('.text-input').val("Some other value"); // this will set value of all elements with class text-input
相关问题