Get text in input field and check if it's equal to it's value attribute?
I have this when the page loads
<input class="input" id="accountNameUsernameForm_name" name="profile[real_name]" size="30" type="text" value="George">
When a submit trigger is pressed I want to check if the current text in the input field is the same as it's value attribute?
if ( $('.input').val() != $('.input').attr('value') ) {
$(this).addClass('formLoading');
}
However the problem is, val() and the attr('value') are always the same. What function retr开发者_Go百科ieves the current text that is in the input right now without looking at its value attribute?
thank you
btw. it doesn't work with text()
!
// save the default value on page load
var defaultUsername = $('.input').val();
// on submit, compare
if ( $('.input').val() != defaultUsername ) {
$(this).addClass('formLoading');
}
use id of input instead input
and then try this..
inputValue = $("#accountNameUsernameForm_name").val()
and then in your form handler try this..
inputText = $("#accountNameUsernameForm_name").attr('value')
if(inputValue ! = inputText ){
$(this).addClass('formLoading');
}
$('.input').val() is equal to $('.input').attr('value') always.
I suggest you include a hiddenfield or save the value in a variable
See example: http://jsfiddle.net/r3KZu/6/
The problem is that the value attribute is also updated as the text is changed. On page load, you should store the initial value as a variable, and then check against that in the callback.
Have a crack at this:
$('.input').each(function() {
if($(this).val() != this.defaultValue) {
$(this).addClass('formLoading');
}
});
Use the defaultValue
property.
$('.input')[0].defaultValue
The defaultValue property sets or returns the default value of a text field, specified in the value attribute.
Sometimes people forget jQuery is just JavaScript, simple things should be done the easy way.
精彩评论