0

I am building an error list. When click the submission button, the old errors will be removed and the new errors will be added. The following code is what I am using but it keeps adding new errors without removing the old ones: (my JS fiddle here: http://jsfiddle.net/shapeare/bc1bdq1b/)

<div id="error">
    Below is a list of errors:
</div>
<input id="submitBtn" type="submit" value="submit"/>

$(document).ready(function(){
    $index = 0;
    $(document).on('click', '#submitBtn', function(event) {
        $('#error').innerHTML = '';
        $('#error').append('<p>Error ' +  $index  +  '</p>');
        $index ++; 
    });
});

What I want to achieve is that every time the button is clicked, the old error disappears and a new error occurs. For example, the first time the submit button is clicked, "Error 0" will appear. The second time it is clicked, "Error 0" disappears and "Error 1" is shown.

3 Answers 3

1

You're setting innerHTML which is not a property of jQuery but native DOM. Instead use empty which empties the $('#error'). Other options are .text('') and .html('')

$(document).ready(function(){
    $index = 0;
    $(document).on('click', '#submitBtn', function(event) {
        $('#error').empty().append('<p>Error ' +  $index  +  '</p>');
        $index++; 
    }); 
});

DEMO You could also use indexer to get the native element and then setting innerHTML but why not use something which jQuery offers when it is used?

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

$(function(){
    $index = 0;
    $(document).on('click', '#submitBtn', function(event) {
        $('#error p').hide("slow");
        $('#error p').html("");
        $('#error p').html('<p>Error ' +  $index  +  '</p>');
        $('#error p').show("slow");
        $index ++; 
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="error">
    Below is a list of errors:
    <p></p>
</div>
<input id="submitBtn" type="submit" value="submit"/>

Comments

1

Instead of appending, you can just replace the html like so:

$(document).ready(function(){ 
    $index = 0;
    $(document).on('click', '#submitBtn', function(event) {
        $('#error').html('<p>Error ' +  $index  +  '</p>');
        $index ++; 
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.