简体   繁体   中英

My website refreshes everytime I run my code

$(document).ready(function() {
  $("#btn").click(function() {
    $("#form").toggle();
  });
  $("#submit").click(function() {
    if ($(".product").checked = true) {
      alert("Thank You!")
    } else {
      alert('Please Choose A Product');
    }
  var name = $("input:text").val();
  var nLi = $("<li>").appendTo("ul");
  nLi.text(name);
  });
});

Everytime I put text in the text input, the <li> will display for only a moment, but the page will refresh and it will disappear. Sorry if this is obvious, I'm still learning.

Don't allow the page to refresh. Return false at the end.

$(document).ready(function() {

  $("#btn").click(function() {
    $("#form").toggle();
  });
  $("#submit").click(function() {
        if ($(".product").checked) {
          alert("Thank You!")
        } else {
          alert('Please Choose A Product');
        }
      var name = $("input:text").val();

      var nLi = $("<li>").appendTo("ul");
      nLi.text(name);

      return false;

  });
});

And please change if ($(".product").checked = true) {

to if ($(".product").checked == true) {

Try to use event.preventDefault() in your click event, for example:

$("#submit").click(function(e) {
    e.preventDefault();
}

for more info about this jquery method event.preventDefault()

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