简体   繁体   中英

How to stop button inside form tags from submitting data

Hi I'm trying to make a form taking input of numbers, inside the form I have on input field but with some button for styling the said field, and an anchor tag to send the form to a php file. Clicking one of the buttons send the current value immediately, how to stop that?

<form name="destination" action="../a.php" method="post">
    Quantity : 
    <button onclick="dec('amount')">-</button>
    <input name="amount" type="text" value="0" size = 1>
    <button onclick="inc('amount')">+</button><br><br>
    </form>
<a href="javascript:submitForm()">Details</a> 

Buttons JS:

function inc(element) {
    let el = document.querySelector(`[name="${element}"]`);
    el.value = parseInt(el.value) + 1;
  }
  
  function dec(element) {
    let el = document.querySelector(`[name="${element}"]`);
      if (parseInt(el.value) > 0) {
        el.value = parseInt(el.value) - 1;
    }
  }

Anchor tag JS function:


function submitForm() {
document.destination.submit();
}
</script>```

You can do easily, just include event.preventDefault() in your js code.

event.preventDefault() actually used to prevent(stop) any default event.

function inc(element) {
  event.preventDefault();
  let el = document.querySelector(`[name="${element}"]`);
  el.value = parseInt(el.value) + 1;
}

function dec(element) {
 event.preventDefault();
 let el = document.querySelector(`[name="${element}"]`);
  if (parseInt(el.value) > 0) {
    el.value = parseInt(el.value) - 1;
  }
}

But in case you don't want to use js, you can change buttons default type. Button's default type is submit which will submit the form. You can use type="button"

In html the button's default type id "submit" which will submit forms. To avoid this behavior simply assign a different type

<button type="button">...</button>

https://www.w3schools.com/TAGs/att_button_type.asp

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