ComputerUser
ComputerUser

Reputation: 4878

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

Upvotes: 0

Views: 131

Answers (6)

Dested
Dested

Reputation: 6433

The ID should be tweet not #tweet

Upvotes: -3

Mutation Person
Mutation Person

Reputation: 30498

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

Upvotes: 0

user57508
user57508

Reputation:

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

Upvotes: 2

meouw
meouw

Reputation: 42140

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

Upvotes: 0

GeekTantra
GeekTantra

Reputation: 12081

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.

Upvotes: 2

pixeline
pixeline

Reputation: 17974

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

Upvotes: 1

Related Questions