Frage

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?

War es hilfreich?

Lösung

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(...

Andere Tipps

Use preventDefault();

 $('#plus').click(function (evt) {
        evt.preventDefault();
          var value = $('#number').val();
          value++;
          $('#number').val(value);
           });

      $('#minus').click( function (evt) {
          evt.preventDefault();
             var value = $('#number').val();
             value--;
            $('#number').val(value);
        });

The difference between ‘return false;’ and ‘e.preventDefault();

Vadim is correct, but the proper method to do this is use e.preventDefault() as such:

$('button').on("click", function(e) {
    e.preventDefault();
    // Your code
});

Also make sure you don't have any errors in your code.

Enjoy!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top