Ben
Ben

Reputation: 257

Jquery if else condition breaks in specific situation

I have a textarea input and i'm checking: if the user entered at least 65 letters.

If not: there's a message saying how many letters left.

If he did: i'm checking if there is a specific word inside the text he entered.

If not: there's a message saying you have to use this word.

If he did: there's a message saying "great".

This is the code:

<?php $maname = get_theme_mod( 'cz_pros_names_man' ); ?>
$("body").on("keyup", "#field_newpro_aboutme", function(event){
    var maname = '<?php echo $maname; ?>';
    if ($(this).val().replace(/ |\n/g,'').length < 65 ) {
            $('.one_enoughText').text("* more "+parseInt(65 - $(this).val().replace(/ |\n/g,'').length, 10)+" to go");
    } else if ($(this).val().indexOf(maname) <= 0) {
            $('.one_enoughText').text('* you have to use the word at least once');
    } else {
        $('.one_enoughText').text('great');
    }

});

It works great but there's one problem: if the specific word is used before he enters 65 letters, then after he entered 65 letters it's showing the message saying you have to use the word once.

Don't know why... Any ideas?

Upvotes: 1

Views: 88

Answers (1)

Utkarsh Pandey
Utkarsh Pandey

Reputation: 1716

// call this function on key up and you will get your result 
function validate(search = '') {
		var message = '';
		if ($('#textarea').val().length >= 65) {
			if ($('#textarea').val().search(search) != -1) {
				message = 'Great';
			}else {
				message = 'You have to use '+search+' word.';
			}
		}
		else {
			message = (65 - $('#textarea').val().length) + ' letters left.';
		}
		return message;
	}

	$(function() {
		$('#textarea').on("keyup", function(e){
            // replace the search_word with the word you want to search      
            var message = validate('search_word');
          // I'm showing your message in a span 
			$("#message").text(message);
          
		});
	})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="textarea" id="textarea" cols="30" rows="10"></textarea>
<span id="message"></span>

Upvotes: 1

Related Questions