1
$(document).ready(function(){
    $('#playerForm .add-box').click(function(){
        addplayerList();
    });
});

function addplayerList(){
    $('.list-box').append('<p>second</p>');
}

I am trying to make a function which will create a new line of HTML after I press the add button. I have no idea what I did wrong. I checked the code and I believe it should work but some how after I click on add the content <p>second</p> shows and disappears right away.

Demo - it has an error after I click add

1
  • Any specific reason for using post method? If none, then you can change method="post" to method="get" Commented Oct 28, 2015 at 10:19

2 Answers 2

1

The issue is because the button click is submitting the form. You need to call preventDefault() in the click() handler to stop this.

$('#playerForm .add-box').click(function (e) {
    e.preventDefault();
    addplayerList();
});

Example fiddle

Alternatively you can just amend your HTML to change the type of the button from a submit (which is the default) just to a plain button:

<button class="add-box" type="button">add</button>
Sign up to request clarification or add additional context in comments.

1 Comment

thank i didt know it somehow make the button to submit that form , thank friend.
1

The fiddle seems to work fine for me apart from the default behaviour of clicking the link causing the error you describe to show.

To avoid the error after click, you can do this:

$(document).ready(function(){
    $('#playerForm .add-box').click(function(){
        addplayerList();
        return false;
    });
});

The return false; prevents the default behaviour of the click, which is to redirect to the href attribute.

https://jsfiddle.net/wmzoroag/4/

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.