Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
});
like image 225
Manish Basdeo Avatar asked Aug 23 '11 08:08

Manish Basdeo


People also ask

How do I change the default value of a textbox?

Setting a Default Value for the Textbox If you want to set the default value to a textbox, you can use the value attribute. Whenever the form is loaded, the default value is shown inside the textbox.

Which jQuery function can we use to get value from an input box?

jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element.

How do I set the value of a element in jQuery?

The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.


3 Answers

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

$("#email").attr("value", "New value");
like image 183
Sergey Larionov Avatar answered Oct 11 '22 21:10

Sergey Larionov


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.

like image 24
Bas Slagter Avatar answered Oct 11 '22 20:10

Bas Slagter


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>
like image 21
Henry Avatar answered Oct 11 '22 20:10

Henry