Textbox refers to <input type="text">
in this question.
For each textbox with a given class i would li开发者_Python百科ke 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:
$(document).ready(function() {
$('.myclass').val(function (index, value) {
// If the element has a value, return it, else return "0"
return value || "0";
});
});
Example
For versions older than jQuery 1.4, you need to use .each() on the collection:
$(document).ready(function() {
$('.myclass').each(function() {
this.value = this.value || "0";
});
});
Example
This might be the simplest answer:
$("input.myclass[value=]").val("0");
Only elements with no value get selected. This works because the value attribute reflects the text the user put in.
Try
$(document).ready(function() {
$('.myclass[type=checkbox]').each(function(){
if($(this).val()=='')
$(this).val('0');
});
})
$(document).ready( function() {
$('input:checkbox').each( function() {
// check the val
if( $(this).val()=='')
// do something
});
});
精彩评论