开发者

Jquery - why isn't this working?

Can someone tell me why the code below doesn't work. I think my theory is sound, I am just missing some vital component.

'#tweet' is the id assigned to the form submit button. I开发者_JS百科 want it to check whether the input has less than 141 characters, if it doesn't, alert the user and do not submit the form.

Currently it does nothing.

    $('#tweet').click(function() {
   if ($('.message').val().length > 140) {
    alert('Your message much be less than or exactly 140 characters');
    return false;
   }
  });


it may be possible, that your .message hits more elements!

$(document).ready(function() {
    $('#tweet').click(function(e) {
        var success = true;
        $('.message').each(function() {
            if ($(this).val().length > 140) {
                alert('Your message much be less than or exactly 140 characters');
                success = false;
            }
        });
        if (!succeess) {
            e.preventDefault();
        }
        return success;
    });
});


Put the above code like this

<script type="text/javascript">
$(function(){
  $('#tweet').click(function() {
    if ($('.message').val().length > 140) {
     alert('Your message much be less than or exactly 140 characters');
     return false;
    }
  });
});
</script>

in the section of your html after including jQuery library file. As event handlers are attached after the dom is ready.


you should attach your behaviour to the form submit event:

 $('form').bind('submit',function() {
   if ($('.message').val().length > 140) {
    alert('Your message much be less than or exactly 140 characters');
    return false;
   }
  });


you probably want to prevent the default action instead of returning false

$('#tweet').click(function( e ) {
    if ($('.message').val().length > 140) {
        alert('Your message much be less than or exactly 140 characters');
        e.preventDefault();
    }
});


For completeness, if your preventing default, you should probably go the following extra distance:

function stopEvent(event) {
    event.preventDefault();
    event.stopPropagation();
    if ($.browser.msie) {
        event.originalEvent.keyCode = 0;
        event.originalEvent.cancelBubble = true;
        event.originalEvent.returnValue = false;
    }
}

There's mroe info on this in my answer to the following question: jQuery form submission. Stopping page refresh only works in newest browsers


The ID should be tweet not #tweet

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜