Search code examples
jqueryajaxwordpressshortcodecontact-form-7

How to prevent form submitting in jQuery


I have created a shortcode that generate a custom input:

function input_plus_moins() {
    $output = "
            <div data-role='controlgroup' data-type='horizontal' data-mini='true'>
             <button id='plus' data-inline='true'>+</button>
                <input type='text' name='number' id='number' value='0' />
             <button id='minus' data-inline='true'>-</button>
            </div>
        ";
    return $output;
}

I can then increments or decrements the input value by clicking on the plus or minus buttons with jQuery

$('#plus').unbind('click').bind('click', function () {
    var value = $('#number').val();
    value++;
    $('#number').val(value);
});

$('#minus').unbind('click').bind('click', function () {
    var value = $('#number').val();
    value--;
    $('#number').val(value);
});

Every time I click on any button, it submits the form.

How can I modify the JavaScript file so that the form is submitted only when clicking specifically on submit button?


Solution

  • The default type for a button element is "submit". Change the button type to "button" as:

    function input_plus_moins() {
        $output = "<div data-role='controlgroup' data-type='horizontal' data-mini='true'>" +
            "<button id='plus' type='button' data-inline='true'>+</button>" +
            "<input type='text' name='number' id='number' value='0' />" +
            "<button id='minus' type='button' data-inline='true'>-</button>" +
            "</div>";
        return $output;
    }
    

    You can also avoid the bind/unbind by using the .on() as in:

    $(document).on('click', '#plus', function () {
        var value = $('#number').val();
        value++;
        $('#number').val(value);
    });
    
    $(document).on('click', '#minus', function () {
        var value = $('#number').val();
        value--;
        $('#number').val(value);
    });
    

    OR alternately combine them both to:

    $(document).on('click', '#plus,#minus', function (event) {
        var value = $('#number').val();
        if (event.target.id == "plus") value++
        else value--;
        $('#number').val(value);
    });
    

    Better in both cases to replace $(document) with the selector for the container they are appended to: $('#mycontainerid').on(...