GG.
GG.

Reputation: 21854

Display a message in jQuery only once when I submit

When I submit my form, I display a message in jQuery.

I want it appears only once when I submit more than once

$('form').submit(function(){
    if ($('#title').val() != '' && $('#comment').val() != '')
        $('form').append($('<span>').text('Bug sent').delay(4000).fadeOut(600));
    else
        $('form').append($('<span>').text('Fields are empty').delay(4000).fadeOut(600));

return false;
});

Example : http://jsfiddle.net/bUS8e/

Upvotes: 1

Views: 1100

Answers (6)

dwalldorf
dwalldorf

Reputation: 1379

You should clear the parent element before:

$('form').submit(function(){
    if ($('#title').val() != '' && $('#comment').val() != '')
        $('form').empty().append($('<span>').text('Bug sent').delay(4000).fadeOut(600));
    else
        $('form').empty().append($('<span>').text('Fields are empty').delay(4000).fadeOut(600));

    return false;
});

Upvotes: 0

freakish
freakish

Reputation: 56477

Add a div (or any other element) to your form and use $('div').html([YOUR STUFF]) instead of $('form').append([YOUR STUFF]).

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272136

Remove all spans when the user submits the form. Then add them again (if necessary):

Like this

Upvotes: 2

Till Helge
Till Helge

Reputation: 9311

You could add the span to the HTML code and give it an ID. And instead of appending a new span everytime, you just reuse the existing one by addressing it via its ID.

Upvotes: 1

Matt Fellows
Matt Fellows

Reputation: 6522

Check if $('form').text() contains "Bug sent"? i.e.

$('form').submit(function(){
    if ($('#title').val() != '' && $('#comment').val() != '')
        if (!/Bug sent/.test($('form').text()) {
            $('form').append($('<span>').text('Bug sent').delay(4000).fadeOut(600));
        }
    else
        $('form').append($('<span>').text('Fields are empty').delay(4000).fadeOut(600));

return false;
});

Upvotes: 2

pimvdb
pimvdb

Reputation: 154848

Simply remove any existing spans in the form: http://jsfiddle.net/pimvdb/bUS8e/1/.

$('form span').remove();

Note that this would also remove any other, irrelevant spans which you might not want to have removed. In that case, you can add a class to the message spans you add, and use $('form span.message').remove(); so that only those message spans get removed.

Upvotes: 3

Related Questions