Muhammad Hashir Anwaar
Muhammad Hashir Anwaar

Reputation: 614

stop redirecting page if alert appears

I see many questions here but no one solve my issue.

i have a form and a save button, when click on save button it run a script first to check if bad words are used. If text contain bad words, it shows an alert.when i click ok of alert, it perform pending action of save button and then redirect to main page.

My code

<script type="text/javascript">
$(document).delegate('.btn-save-template', 'click', function() {
    var text = $('#input-message').val().toLocaleLowerCase(); 
    var bad_words = ['bad', 'sex', 'fuck you', 'fuckyou', 'murder', 'rap']; // Bad Words

    if((new RegExp( '\\b' + bad_words.join('\\b|\\b') + '\\b') ).test(text)){
        alert('Sorry, you are not allowed to use bad words');
    }
});
</script>

But, I want to stay at the same page after alert, so user can remove bad word and click save button again.

Upvotes: 0

Views: 1716

Answers (3)

Muhammad Hashir Anwaar
Muhammad Hashir Anwaar

Reputation: 614

I used keydown function of jquery to check bad words and disable button if bad word is used.

My Code

<script type="text/javascript">
$('#input-message').keydown(function() {
    var text = $('#input-message').val().toLocaleLowerCase(); 
    var bad_words = ['bad', 'fuck you', 'fuckyou', 'kill you', 'murder', 'rap']; // Bad Words

    if((new RegExp( '\\b' + bad_words.join('\\b|\\b') + '\\b') ).test(text)){
        alert('Sorry, you are not allowed to use bad words');
        $('.btn-save-template').attr('disabled',true);
        $('input-messgae').css('border','1px solid red');
    }else{
        $('.btn-save-template').attr('disabled',false);
    }
});
</script>

Now it works fine for me... :)

Upvotes: 1

Oleksandr Blyzniuk
Oleksandr Blyzniuk

Reputation: 556

You can prevent the default behavior of the browser

function(event) {
   ...
   if((new RegExp( '\\b' + bad_words.join('\\b|\\b') + '\\b') ).test(text)){
       alert('Sorry, you are not allowed to use bad words');
       event.preventDefault();
   }
});

Upvotes: 0

Alex S.
Alex S.

Reputation: 632

Replace submit type of button with button type to disable form processing by browser.

<input type="button" class="btn-save-template" value=...>

When user clicks on the button, submit the form from the script, if all tests passed successfuly.

<script type="text/javascript">
$(document).delegate('.btn-save-template', 'click', function() {
    var text = $('#input-message').val().toLocaleLowerCase(); 
    var bad_words = ['bad', 'sex', 'fuck you', 'fuckyou', 'murder', 'rap']; // Bad Words

    if((new RegExp( '\\b' + bad_words.join('\\b|\\b') + '\\b') ).test(text)){
        alert('Sorry, you are not allowed to use bad words');
    } else {
        this.form.submit();
    }
});
</script>

Upvotes: 1

Related Questions