Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: put a default value in all empty textboxes

Tags:

jquery

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?

like image 932
Jules Colle Avatar asked Aug 17 '26 07:08

Jules Colle


2 Answers

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

like image 162
Andy E Avatar answered Aug 20 '26 02:08

Andy E


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.

like image 38
Georg Schölly Avatar answered Aug 20 '26 01:08

Georg Schölly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!