Search code examples
jqueryhtmlformsclicksubmit-button

Click on submit button doesn't work always


I have a form with a text box and a submit button.

<div style="float:left; padding:20px;">
<form id="crate_input" method="get">
    Create new crate: <input type="text" id="create">
    <input id="subbutton" type="submit" value="Submit">
</form>
<select id="crates">
    <option id="choose" value="choose" selected>Choose a crate</option>
    <option id="default_crate" value="default_crate">default_crate</option>
</select>
</div>

User interactions are handled in a separate java script file.

$('#subbutton').click(function(event) {
    $.ajax({
        url: OC.linkTo('crate_it', 'ajax/bagit_handler.php'),
        type: 'get',
        dataType: 'text/html',
        data: {'action':'create', 'crate_name':$('#crate_input #create').val()},
        success: function(data){
            $('#crates option').filter(function(){
            return $(this).attr("id") == data.responseText;
        }).prop('selected', true);
    }
    });
});

But the problem is when I type a name for a crate and press submit button, it sometimes doesn't create the crate. It seemed to refresh the page, but new crate hasn't been created. Does anyone know what's wrong here?


Solution

  • What's wrong is you're not stopping the default form submission.

    $('#crate_input').submit(function(){ return false; });
    

    should resolve your issues.