At first, the value
attribute of the input is equal to its value, therefore
console.log(jQuery('#link').attr('value'));
It is consistent with the initial value. After changing it, this command continues to report the initial value.
If you do instead:
console.log(document.getElementById('link').value);
You get the new input value.
Why is this happening?
This happens because jQuery does a initial population of the attributes of the html element based on all its properties and attributes strong> indistinctly.
After changing the value, the property value of the item has changed, but the data that jQuery used to populate attr
does not change for certain properties , such as value
of an input of type text, or status checked
of a checkbox because, I repeat, they are properties and not attributes .
It happens that in the latest versions of jQuery (from 1.6 onwards, actually), there is a differentiation between properties and attributes:
console.log(jQuery('#link').attr('value')); // no habrá cambiado
console.log(jQuery('#link').prop('value')); // sí habrá cambiado
Do the test by changing the value of the input in the following snippet and using the buttons that send the attribute value and the property value to the console.
jQuery(document).ready(function() {
jQuery('#link').on('keypress change', function() {
jQuery('#prueba_attr').removeAttr('disabled');
jQuery('#prueba_prop').removeAttr('disabled');
});
jQuery('#prueba_attr').on('click', function() {
console.log("attr('value') sigue siendo ", '"' + $('#link').attr('value') + '"');
console.log("input value ahora es ", '"' + document.getElementById('link').value + '"');
});
jQuery('#prueba_prop').on('click', function() {
console.log("prop('value') ahora es ", '"' + $('#link').prop('value') + '"');
console.log("input value ahora es ", '"' + document.getElementById('link').value + '"');
});
});
#link {
width: 300px;
}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
<input type='text' value='cambia mi valor para habilitar los botones' id='link' />
<input type="button" id="prueba_attr" value="prueba attr" disabled/>
<input type="button" id="prueba_prop" value="prueba prop" disabled/>
Side note : jQuery('#link').val()
deletes the value property of an input, not the value attribute. That's why it works for you.
Side note 2 : Use of jQuery('#link').attr(x)
changed in jQuery 1.6, but in 1.6.1 they tried to revert it to how it was before . This has been evolving in later versions, but although it works in some cases , it is still recommended to use jQuery('#link').prop(x)
when it comes to an input.