开发者

jQuery selector object does not update on the fly

开发者 https://www.devze.com 2023-02-10 05:00 出处:网络
I\'m trying to validate a form by checking the required fields with a jQuery selector. function validate() {

I'm trying to validate a form by checking the required fields with a jQuery selector.

function validate() {
  if ($('input[required][value=""]').length != 0) {
    console.log("required value missing");
  }
  return false; // to prevent firing default action
}

There are a couple input elements like so, with the value set in PHP (not shown):

<input id="id" name="name" type="text" required\>

The problem is that this validate function will read the DOM correctly the first time (i.e will correctly recognize all required, empty inputs), but once I fill in/delete values the fun开发者_开发知识库ction will keep returning the same set as before, not recognizing the newly empty fields or the newly filled fields. Once I refresh the page, however, the selector will correctly grab the right inputs.

I saw the .live() function, but that applies to events.

Does the $(selector) cache (only checks the DOM once instantiated) or is there some other arcane/simple rule for jQuery selectors I'm not paying attention to?


Don't use the value attribute; use .val().

function validate() {
    var $missing = $('input[required]').filter(function (){
        return $(this).val() === '';
    });

    if ($missing.length != 0) {
        console.log("required value missing");
    }
    return false; // to prevent firing default action
}
0

精彩评论

暂无评论...
验证码 换一张
取 消