tags:

views:

120

answers:

4

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?

+1  A: 

Try

$(document).ready(function() {
  $('.myclass[type=checkbox]').each(function(){
      if($(this).val()=='')
          $(this).val('0');
    });
})
Bang Dao
This works only for the first element in the selection. You need to use each.
Yves M.
A: 
$(document).ready( function() {
  $('input:checkbox').each( function() {
    // check the val
    if( $(this).val()=='')
      // do something
  });
});
Haim Evgi
this doesn't work. Guess you made a typo: this.val() should be $(this).val()
Jules
thanks , you right
Haim Evgi
+6  A: 

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

Andy E
this just outputs "function (index, value) { return value || "0"; }" as if it where a string...
Jules
@user296430: Are you using an older version of jQuery? Like I said in the answer, this applies to 1.4 and later. For older versions of jQuery you have to use [ *.each()* ](http://api.jquery.com/each/) to iterate over the elements in the collection.
Andy E
oh sorry, i'm indeed using 1.3 :)
Jules
@user296430: no worries, I updated my answer with an alternative example :-)
Andy E
ok, thanks, didn't know that the ||-operator could be applied to strings also. That's pretty neat. I'll accept this as best answer
Jules
+1  A: 

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.

Georg
+1 from me for the blindingly obvious solution that the rest of us missed.
Andy E