如何使用 jQuery 设置输入框的默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7157896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:28:56  来源:igfitidea点击:

How do I set the default value of an input box using jQuery?

jquery

提问by Vimal Basdeo

I want to change the default value of an input box such that when I reset the form, the value remains.

我想更改输入框的默认值,以便在我重置表单时,该值保持不变。

I have the following code that sets a value using jQuery but as reset is pressed, the value becomes the initial one.

我有以下代码使用 jQuery 设置一个值,但当按下重置时,该值成为初始值。

<form>
Email: <input type="text" id="email" value="old value" />
<input type="reset" value="reset" />
</form>

$(function(){
    $("#email").val("New value");
});

采纳答案by Bas Slagter

Reset clears all values of the form (default behaviour). If you want the values to be visible again, you need to set them again. So you need to call a method onclick of the reset button and fill the form again.

重置清除表单的所有值(默认行为)。如果您希望这些值再次可见,则需要再次设置它们。因此,您需要调用重置按钮的 onclick 方法并再次填写表单。

回答by Sergey Larionov

You have to set attribute "value" of #email element, not the value itself.

您必须设置#email 元素的属性“值”,而不是值本身。

$("#email").attr("value", "New value");

回答by Henry

Reset by default clears a form but if you want to controll this behaviour yourself here is how you would do it. You need to use .val() Here are some examples of doing a single box reset and multiple box's using a wrapped set.

默认情况下重置会清除表单,但如果您想自己控制此行为,您将如何操作。您需要使用 .val() 以下是一些使用包装集进行单个框重置和多个框重置的示例。

Example:http://jsfiddle.net/HenryGarle/ZTprm/

示例:http : //jsfiddle.net/HenryGarle/ZTprm/

<b>Reset Single</b>

<input type="text" id="TextBox">
<button id="reset">Reset</button>

<hr>
<b>Reset Many</b>

<div id="Many">
<input type="text" value="1">
<input type="text" value="5">
<input type="text" value="2">
    <button id="ResetMany">Reset</button>
</div>


<script>
// Reset single
$("#reset").click(function (e) {
   $("#TextBox").val("Value"); 
});


// Resets many given a selector 
// Could be a form, containing div
$("#ResetMany").click(function (e) {
    var inputs = $("input", "#Many");

    for (var i = 0; i < inputs.length; i++) {
        $(inputs[i]).val("Value");
    }

});
</script>

回答by Pritam Banerjee

If you want to put the value then you can do as @Sergey Larionov mentioned. If you want to put a default placeholder you can do this:

如果你想输入这个值,那么你可以像@Sergey Larionov 提到的那样做。如果要放置默认占位符,可以执行以下操作:

$("#email").attr("placeholder", "Default value");

回答by Franquis

Try

尝试

$('input[type="reset"]').click(function(){
 $("#email").val("New value");
});