in this question. For each text field with th...">

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?

+3
source share
4 answers

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";
  });
});

Example

jQuery 1.4 . each() :

$(document).ready(function() {
    $('.myclass').each(function() {
        this.value = this.value || "0";
    });
});

+8

:

$("input.myclass[value=]").val("0");

. , value , .

+3

Try

$(document).ready(function() {
  $('.myclass[type=checkbox]').each(function(){
      if($(this).val()=='')
          $(this).val('0');
    });
})
+1
source
$(document).ready( function() {
  $('input:checkbox').each( function() {
    // check the val
    if( $(this).val()=='')
      // do something
  });
});
0
source

Source: https://habr.com/ru/post/1759090/


All Articles