wxcoder
wxcoder

Reputation: 655

Why does function only work on second click?

I am trying to submit data through a form and when the submit button is click I want certain images to disappear with style.display = 'none';. Currently, I have to click the button twice before images disappear. Is there a way to do this on first click?

HTML:

<form action="/create_post/" method="POST" id="post-form">
    <div class="col-sm-4" id="toprow">
        <h4 style="font-family:verdana"> Models </h4>
        <img src='{% static 'images/USAcomplete2.png' %}' class="img-responsive thumbnail" id='gbimg' >
        <div class="btn-toolbar">
            <button type="submit" name="model" value="test" class="btn btn-default">test</button>
            <button type="submit" name="model" value="test2" class="btn btn-default">test2</button>
            <button type="submit" name="model" value="test3" class="btn btn-default">test3</button>
        </div>
    </div>
</form>

JS:

$('#post-form').on('submit', function(event) {
    event.preventDefault();
    console.log("form submitted!")
    create_post();
});

function create_post() {
    console.log("create post is working!");
    $("button").click(function() {
        var cbtn = $(this);
        var btnval = cbtn.val();
        console.log(btnval);
        document.getElementById('gbimg').style.display = 'none';
    });

    //$.ajax({
    //    url : "create_post/",
    //    type : "POST",
    //    data : { model : 
};

Upvotes: 2

Views: 2508

Answers (2)

taxicala
taxicala

Reputation: 21759

Move the button click handler outside your create_post function:

$(document).ready(function () {
    $('#post-form').on('submit', function(event) {
        event.preventDefault();
        console.log("form submitted!")
        create_post();
    });

    function create_post() {
        console.log("create post is working!");
        var cbtn = $("button");
        var btnval = cbtn.val();
        console.log(btnval);
        document.getElementById('gbimg').style.display = 'none';

        //$.ajax({
        //    url : "create_post/",
        //    type : "POST",
        //    data : { model : 
    };
});

Upvotes: 1

roscioli
roscioli

Reputation: 1230

If your <button> executes the submit function for the form, you should just disappear the button on submitting of the form instead of adding the click handler in the create_post() method. So:

$('#post-form').on('submit', function(event) {
    event.preventDefault();
    console.log("form submitted!");

    var cbtn = $("button");
    var btnval = cbtn.val();
    console.log(btnval);
    document.getElementById('gbimg').style.display = 'none';

    create_post();
});

function create_post() {
    console.log("create post is working!");

    //$.ajax({
    //    url : "create_post/",
    //    type : "POST",
    //    data : { model : 
};

Upvotes: 2

Related Questions