0

This is simple question regarding javascript .value and .defaultValue

Here is my First html

<input id="txt" value="Hello">
</input>
<input type="button" id="btn" />

And corresponding js

$('#btn').click(function(){
    alert('Old Value '+ document.getElementById('txt').defaultValue);
    alert('New value ' + document.getElementById('txt').value);
});

So the above html by default has Hello, now if i remove a few characters and make it Hel and press the button, the output that i'm getting is Old Value Hello and New value Hel

Here is the demo

Now here is my second html

<input id="txt" ></input>
<input type="button" id="btn" />

And the corresponding js

$('#txt').val('Hello');
$('#btn').click(function(){
    alert('Old Value '+ document.getElementById('txt').defaultValue);
    alert('New value ' + document.getElementById('txt').value);
});

Here if i remove a few characters and make it Hel and press the button, the output that i'm getting is Old Value and New value Hel

Here is the demo

Can any one explain why the difference in defaultValue in both examples

1
  • 1
    * Oh the first demo You have default value in html where in second you don't! :) LOL! <input id="txt" > vs <input id="txt" value="Hello"> I reckon! :) Commented Oct 21, 2013 at 8:31

1 Answer 1

2

Because the default value is set by the intial value of the input field... which is an empty string in the second case... you are changing the value using a script which will not update the defaultValue

defaultValue:

The default value as originally specified in HTML that created this object.

You can use .prop() to update the value of defaultValue after updating value

$('#txt').val('Hello').prop('defaultValue', 'Hello');

or

$('#txt').val('Hello').prop('defaultValue', function(){
    return this.value
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

ok..dat works...is there a way to call the above code i.e prop('defaultValue', function(){ return this.value }); where ever i have called the .val('Hello') since i have a number of input types of text on a page
@iJay that is a tricky situation since you may not want to change the value of defaultValue on all call to val(...), a proper solution will be is to trigger an event whenever you want to update the defaultValue
is there any default value for html select

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.