Reputation: 37
My if statement in jQuery seems to be breaking this code and I cannot figure out why:( here is a bit of the code:
$(document).ready(function wordCount() //init
{
$('#text_area').keyup(function () //when you type in the text area
{
$('#limit').html($(this).val().split(/\b[\s,\.-:;]*/).length - 1 + ' words'); //count the number of words
//and print it out in paragraph #limit
//if there are more than 250 words...
if ($(this).val().split(/\b[\s,\.-:;]*/).length - 1 > 250) {
//print it out
$('#limit').html($(this).val().split(/\b[\s,\.-:;]*/).length - 1 + ' out of 250 words');
//color it in red
$('#limit').css("color": "red");
//disable the submit button.
$('#submit_button').attr('disabled', 'disabled');
}
});
});
It works perfectly without an if statement. but as soon as I add some condition, it breaks and displays nothing in #limit.
Thanks
Upvotes: 0
Views: 200
Reputation: 17586
assign your $(this).val().split(/\b[\s,\.-:;]*/).length
to a variable and use that your if
var length = $(this).val().split(/\b[\s,\.-:;]*/).length ;
if ( (length- 1) > 250) {
}
@blargie-bla . if you say your $(this).val().split(/\b[\s,\.-:;]*/).length
is working .
UPDATE
also
$('#limit').css("color": "red");
should be
$('#limit').css("color","red");
this should work
Upvotes: 0
Reputation: 322562
It is breaking when the if
statement is present because this:
$('#limit').css("color": "red"); // semi-colon is wrong
should be:
$('#limit').css("color", "red"); // use a comma instead
Example: http://jsfiddle.net/H2JWy/
$(document).ready(function wordCount() //init
{
var limit = $('#limit');
var submit = $('#submit_button');
$('#text_area').keyup(function() //when you type in the text area
{
var len = $(this).val().split(/\b[\s,\.-:;]*/).length - 1;
limit.html(len + ' words');
if (len > 250) {
limit.html(len + ' out of 250 words').css("color", "red");
submit.attr('disabled', 'disabled');
}
});
});
Upvotes: 2