如何在javascript中设置函数的多输入字段的值

时间:2017-09-05 01:22:05

标签: javascript html forms input field

我可以在某些功能之后设置或发送值到输入字段。我可以根据需要在执行某些操作后显示我的值而不是占位符。 它仅适用于单个输入字段,因此我如何为两个或更多输入字段(输入类型是文本)执行此操作? 工作代码如下,

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("input:text").val("Glenn Quagmire");

    });
});
</script>
</head>
<body>

<p>Name: <input type="text" name="user" placeholder="entername"></p>


<button>Set the value of the input field</button>

</body>
</html>

这样我想在点击按钮后设置两个输入字段的值。我怎样才能使它发挥作用?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("input:text").val("Glenn Quagmire");
        $("input.text").val("Kathmandu");
    });
});
</script>
</head>
<body>

<p>Name: <input type="text" name="user" placeholder="entername"></p>
<p>Add : <input type="text" name="add" placeholder="address"></p>

<button>Set the value of the input field</button>

</body>
</html>

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用名称属性为不同的输入字段设置值。

$(document).ready(function(){
    $("button").click(function(){
        $('input[name="user"]').val("Glenn Quagmire");
        $('input[name="add"]').val("Kathmandu");
    });
});