简体   繁体   中英

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

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.

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

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

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

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

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.

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.

Example: 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>

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:

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

Try

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

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