简体   繁体   中英

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 : 
};

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 : 
};

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 : 
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM