Fil
Fil

Reputation: 8863

Prevent form submit when I put any search keyword on the input text box then pressed enter. Using Jquery

Hi I have this code on laravel blade,

<h1 class="" id="module-users-h1">Search User</h1>

<form class="" id="module-user-search" action="" method="post">
    <div class="field has-addons">
        <div class="control is-expanded">
            <input class="input" type="text" name="user" id="module-user-search-input" placeholder="Find user">
        </div>
        <div class="control">
            <button type="button" class="button is-info" id="module-user-button" name="button">Seach</button>
        </div>
    </div>
</form>

for search functionality.

and I have this javascript code,

/**
 * Perform search user -------------------
 *
 * @return void
 */
$('#module-user-button').click(function(e) {
    let formData = $(this).parents('form').serialize();

    axios.get('/modules/getuser/' + formData.split('=')[1])
    .then((response) => {
        console.log(response.data);
    });
});

$('#module-user-search-input').keyup(function (e) {
    e.preventDefault();

    if (e.keyCode === 13) {
        $('#module-user-button').click();
    }
});

What I'm trying to do aside from button click, I would like to perform search when the enter key is pressed.

The problem is that, when I put any user name as search keyword on the input text box then pressed enter. The form will submit resulting this kind of error in laravel.

Any Ideas or solution for this?

enter image description here

Upvotes: 0

Views: 160

Answers (1)

You can disable the default behavior by returning false on pressing enter key at the Form this way:

$(document).on("keypress", "#module-user-search", function(event) 
{ 
    if (event.keyCode == 13)
        return false;
});

Upvotes: 1

Related Questions