Chuck
Chuck

Reputation: 15

jQuery on submit doesn't work

I know the kind of question is already been asked but I can't find a solution to my problem. In my HTML file I have this code:

<div>
        <form id="chart-input">
            <input type="text" name="country" placeholder="Country" autocomplete="off">
            <input type="number" name="visits" placeholder="Visits" autocomplete="off"> 
            <button>Send</button>
        </form>
</div>

I tried to handle the submit for this form with jQuery, but it seems it doesn't work.

Here is my js file:

jQuery('#chart-input').on('submit', function (e) {
  e.preventDefault();

  let countryTextbox = jQuery('[name=country]');
  let visitsTextbox = jQuery('[name=visits]');


    socket.emit('addData', {
      "country": countryTextbox,
      "visits": visitsTextbox
    }); 
});

What's the problem? When I click the button preventDefault() and the other code is not executed. Hope anyone knows a solution. Thx

Upvotes: 0

Views: 987

Answers (2)

Sergo Kupreishvili
Sergo Kupreishvili

Reputation: 462

change <button>Send</button> to <button type="submit">Send</button> and it will work

Upvotes: 1

Majid Parvin
Majid Parvin

Reputation: 4992

Make sure you have registered jQuery and act as follow:

Put your javaScript code after the HTML or change it to:

jQuery(document).ready(function(){
    jQuery('#chart-input').on('submit', function (e) {
          e.preventDefault();

          let countryTextbox = jQuery('[name=country]');
          let visitsTextbox = jQuery('[name=visits]');

          socket.emit('addData', {
            "country": countryTextbox,
            "visits": visitsTextbox
          }); 
    });
});

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<form id="chart-input">
    <input type="text" name="country" placeholder="Country" autocomplete="off">
    <input type="number" name="visits" placeholder="Visits" autocomplete="off">
    <button>Send</button>
</form>
<script>
    jQuery(document).ready(function() {
        jQuery('#chart-input').on('submit', function(e) {
            e.preventDefault();

            let countryTextbox = jQuery('[name=country]');
            let visitsTextbox = jQuery('[name=visits]');

            //socket.emit('addData', {
             //   "country": countryTextbox,
             //   "visits": visitsTextbox
            //});
            alert('it works!!!');
        });
    });
</script>

Upvotes: 0

Related Questions