Textbox refers to <input type="text"> in this question.
For each textbox with a given class i would like to check if the value equals '', and if it does I want to make the value '0'. I would like to do this as soon as the page is loaded.
This is the closest I’ve got now:
$(document).ready(function() {
if ($('.myclass').val() == '') $('.myclass').val('0');
})
The problem here is that this code will give all my textboxes (with class="myclass") the value '0' as soon as one of them is empty. I know this is the expected behaviour given the code I use now, but I’m pretty new to jQuery and I haven’t really got the hang of the selectors yet. How would I solve this? Do I need to create a separate function to do the check on one element and then call that for each of the elements that apply to the selector? If so, how would I do this?
In jQuery 1.4, a function can be passed to val() that will be executed on all elements in the collection:
Example
For versions older than jQuery 1.4, you need to use .each() on the collection:
Example