JQuery: put a default value in all empty text fields
The text box refers to <input type="text">in this question.
For each text field with this class, I would like to check if the value is equal '', and if necessary, I want to make a value '0'. I would like to do this as soon as the page is loaded.
This is the closest I have now:
$(document).ready(function() {
if ($('.myclass').val() == '') $('.myclass').val('0');
})
The problem is that this code will give all my text fields (c class="myclass") a value '0'as soon as one of them is empty. I know this is the expected behavior, given the code I'm using now, but I'm pretty new to jQuery, and so far I have no difference in selectors yet. How can i solve this? Do I need to create a separate function to test a single element, and then call this for each of the elements that apply to the selector? If so, how would I do it?
In jQuery 1.4, a function can be passed to val (), which will be executed on all elements of the collection:
$(document).ready(function() {
$('.myclass').val(function (index, value) {
// If the element has a value, return it, else return "0"
return value || "0";
});
});
jQuery 1.4 . each() :
$(document).ready(function() {
$('.myclass').each(function() {
this.value = this.value || "0";
});
});