Home » Jquery » javascript – jQuery selector is selecting all input types of submit

javascript – jQuery selector is selecting all input types of submit

Posted by: admin February 22, 2020 Leave a comment

Questions:

I was working with the jquery-3.4.1 when I came across this strange behavior of the jquery selector.
The html section of the particular submit button is as follows:

<input type="submit" id="submit">

Initially, I used the following code to select the only submit button on my page. But, it didn’t work.

$('submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

Then, I tried to be more specific and used the following code to select that submit button on the basis of an id.

$('#submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

Once again, the results were the same. Then I selected all the submit buttons on the page and the code started working. The code is as follows:

$(':submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

Now, my question is that why this piece of code worked and the others were not working ? Is there anything wrong with the code ? Or was this because I used the same id as the input type ?

How to&Answer:
$('submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

in this one you should use # from id or . for class
but it’s best to use class for you select like this

$('.submit-form').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

<input type="submit" class="submit-form" id="submit">

and in your code just on tag should have id with name submit
because id name is unique