简体   繁体   中英

Jquery on click button reloads page

I have the following script:

HTML

<form class="trial_form" id="trial_form" >
   <input type="text" value="TRIAL DATA PLEASE ALERT" id="trial_data" name="trial_data" class="trial_data"/>
   <input type="submit" name="trial_submit" id="trial_submit" class="trial_submit" value="Validate Data"/>
</form>

jQuery

$('#trial_submit').click(function () {
  alert('CLICKED!!!!');
  alert('Alert!!');
  var bla = $('#trial_data').val();
  alert(bla);
});

When I click on the Validate Data button, the page responds with an alert and then reloads the page passing the information from the test field with it in the following format:

http://enunua.com/emarps/main.php?trial_data=TRIAL+DATA+PLEASE+ALERT&trial_submit=Validate+Data

How can I prevent the reload of the page?

Use event.preventDefault() or return false in event handler to stop form submission.

If this method is called, the default action of the event will not be triggered.

$('#trial_submit').click(function(e) {
    e.preventDefault(); // Stop form submission

    alert('CLICKED!!!!');
    alert('Alert!!');
    var bla = $('#trial_data').val();
    alert(bla);
});

Using return false :

$('#trial_submit').click(function(e) {
    alert('CLICKED!!!!');
    alert('Alert!!');
    var bla = $('#trial_data').val();
    alert(bla);

    return false; // Stop form submission
});

Use event.preventDefault() . It is used to prevents the default action and trigger your event

$('#trial_submit').click(function (event) {
    event.preventDefault();
    alert('CLICKED!!!!');
    alert('Alert!!');
    var bla = $('#trial_data').val();
    alert(bla);
 });
$('#trial_submit').click(function (e) {
    e.preventDefault();
            alert('CLICKED!!!!');
            alert('Alert!!');
            var bla = $('#trial_data').val();
            alert(bla);
        });

Fiddle

在表单标签中使用attr onsubmit

<form class="trial_form" id="trial_form" onsubmit="return false"> <input type="text" value="TRIAL DATA PLEASE ALERT" id="trial_data" name="trial_data" class="trial_data"/> <input type="submit" name="trial_submit" id="trial_submit" class="trial_submit" value="Validate Data"/> </form>

using return false

$('#trial_submit').click(function () {
  alert('CLICKED!!!!');
  alert('Alert!!');
  var bla = $('#trial_data').val();
  alert(bla);

  return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM