开发者

Issue with $(this).val().length in chrome - wrong value

I use the following JQuery in chrome: $(this).val().length this represents an input field. Now in every other browser this works fine, but in Chrome it sometimes returns the wrong value. Say I have 3 characters in an input field, yet alert($(this).val().length); will say 4.

Does anyone know why this occurs and a possible sollution?

edit: some code

$("#fieldset1 input[type=text]").keyup(function(e){
    if($(this).val().length == $(this).attr('maxlength')){
                if($(this).parent().children().last().attr('id') == $(this).attr("id")){
                    $(this).parent().next().find(':input').focus();
                }else{
                    $(this).next("input").focus();
                }
            }
});

I added the alert after the first if when I noticed this behaviour.

edit2: put it on JSFiddle: http://jsfiddle.net/QyyBV/

HTML:

<fieldset id ="test">
  <input type="text" id="1" maxlength="5" size="5"/>
  <input type="text" id="2" maxlength="5" size="5"/>
  <input type="text" id="3" maxlength="5" size="5"/>
  <input type="text" id="4" maxlength="5" size="5"/>
  <in开发者_开发知识库put type="text" id="5" maxlength="5" size="5"/>
</fieldset>

JavaScript:

      $(document).ready(function() {

          $("#test input[type=text]").keydown(function(e){
            if(e.which == 8){
              if($(this).val().length == 0){
                $(this).prev().focus().val($(this).prev().val());
              }
            }
          });

          $("#test input[type=text]").keyup(function(e){


if($(this).val().length == $(this).attr('maxlength') ){
          if($(this).parent().children().last().attr('id') == $(this).attr("id")){
            $(this).parent().next().find(':input').focus();
          }else{
            $(this).next("input").focus();
          }
        }
      });

  });

Scenario: I enter 5 4 times and then 5 once more, I backspace untill the 4th field is also empty. Sometimes (but not always) when I enter 4 5's again I jump despite that it should jump at 5 5's. But this doesn't always happen. Sometimes I need to do it again to see this issue in Chrome.


Update 4:

I can't replicate the problem using Chrome (for Linux) with your fiddle.

But I noticed you're using keydown for one aspect of the masked edit, but keyup for another aspect of it. Barring a really good reason for using keyup instead of keydown, I'd use keydown for both — not least because then key repeat works properly with the masked edit you're creating (e.g., if I push down '5' and hold it, I switch from field to field as I expect, instead of stopping at the end of the first field).

Here's my slightly-edited version using keydown. Seems to work fine (but then, your original didn't show the problem for me either, could be OS-specific):

$(document).ready(function() {

    $("#test input[type=text]").keydown(function(e){
        var $this = $(this),
            val = $this.val(),
            $prev,
            $parent;

        if(e.which == 8){
            if(val.length == 0){
                $prev = $this.prev();
                $prev.focus().val($prev.val());
            }
        }
        else if(val.length == $this.attr('maxlength') ){
            $parent = $this.parent();
            if($parent.children().last().attr('id') == $this.attr("id")){
                $parent.next().find(':input').focus();
            }else{
                $this.next("input").focus();
            }
        }

    });

});

Who knows, perhaps that works around the weird issue you're seeing.

Off-topic 1:

I didn't do it above, but since next() will return an empty jQuery object if there is no match for the selector, you can replace

if($parent.children().last().attr('id') == $this.attr("id")){
    $parent.next().find(':input').focus();
}else{
    $this.next("input").focus();
}

with

$next = $this.next("input");
if($next.length == 0) {
    $next = $parent.next().find(':input:first');
}
$next.focus();

...(declaring $next with a var up top, of course). That avoids the need for $parent.children().last().attr('id') == $this.attr("id"), which is more work than necessary. And you can add equivalent functionality to the backspace:

if(val.length == 0){
    $prev = $this.prev();
    if($prev.length == 0) {
        $prev = $this.parent().prev().find(':input:last');
    }
    $prev.focus().val($prev.val());
}

Live example. FWIW.


Off-topic 2: The IDs you've given the fields in your example (1, 2, etc.), while valid HTML IDs, are invalid for use with CSS selectors. IDs in CSS cannot start with a digit (or a few other things, see the link for details). I mention this because we use CSS selectors so frequently in jQuery...


Off-topic 3: Repeatedly calling $(this) makes your browser work harder than it has to. Each time you do it, jQuery ends up doing two function calls and a memory allocation. That may not be an issue, but there's rarely a reason not to cache the result in a local variable, e.g. var $this = $(this);.



Previous updates of answer:


Update 3:

You mentioned it happening occasionally, and you mentioned backspace, but the quoted code doesn't do anything with backspaces. So really, a pared-down, self-contained, functional example will be key to finding this. Sounds like a browser difference in the order of events vs. focus (since you're modifying focus), but...

Update 2:

Re your comment that it's a keyup handler, I'm still not seeing that behavior:

$('#theField').keyup(function() {
  if ($(this).val().length == $(this).attr("maxlength")) {
    display("Field is at maximum, length = " +
            $(this).val().length);
  }
  else {
    display("Field is not at maximum, length = " +
            $(this).val().length);
  }
});

Live copy

Note that your latest posted code (as of this writing) has a syntax error (should end with });, not just };), but I'm guessing that's a side-effect of copy-and-paste.

Recommend paring your code down to the bare minimum, posting it to JSBin or jsFiddle or similar, and we can help you find the problem.


Update 1:

My guess (more context would help! what event handler is that in?) is you're doing this in a keypress handler. As of the keypress event, the character hasn't (yet) been added to the field. Live example:

$('#theField').keypress(function() {
  if ($(this).val().length == $(this).attr("maxlength")) {
    display("Field is at maximum, length = " +
            $(this).val().length);
  }
  else {
    display("Field is not at maximum, length = " +
            $(this).val().length);
  }
});

function display(msg) {
  $('<p/>').html(msg).appendTo(document.body);
}

As far as I know, this is reliable behavior across browsers, though, so if you're really seeing in only on Chrome, perhaps you're using another event I don't have much experience with. For instance, the above is fine in Firefox.

In any case, if the problem is that the event happens too early for what you're trying to do, you can easily defer it:

$('#theField').keypress(function() {
  var $this = $(this);
  setTimeout(function() {
    if ($this.val().length == $this.attr("maxlength")) {
      display("Field is at maximum, length = " +
              $this.val().length);
    }
    else {
      display("Field is not at maximum, length = " +
              $this.val().length);
    }
  }, 0);
});

Live example


Original answer:

I suspect that there really are four characters in the field. Certainly it works as expected, in Chrome, with this live example:

HTML:

<form>
    <input type='text' id='theField' value='123'>
</form>

JavaScript:

display('Length is ' + $('#theField').val().length);

function display(msg) {
  $('<p/>').html(msg).appendTo(document.body);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜