Home > Mobile >  basic onclick button in a html form
basic onclick button in a html form

Time:05-30

When i put a basic onclick button in a form it doesn't work : (even with the type="button")

function action(div) {
  var x = document.querySelector(div);
  if (x.style.display == 'block') {
    x.style.display = 'none';
  } else {
    x.style.display = 'block';
  }
}
<form method="post">
  <button type="button"  onclick="action('.popup')">click</button>
  <div >
    <p>popup</p>
    <div>
</form>

But this same button out does work :

function action(div) {
  var x = document.querySelector(div);
  if (x.style.display == 'block') {
    x.style.display = 'none';
  } else {
    x.style.display = 'block';
  }
}
<form method="post">

</form>

<button type="button"  onclick="action('.popup')">click</button>
<div >
  <p>popup</p>
  <div>

Can i make it work into the form ?

CodePudding user response:

The default behavior of a button in a form is to submit the form to the server (or whatever the ACTION of the form is. In your case, it will post the form elements to the same url). The button is working, but then the page immediately reloads so you don't see it.

You need to prevent the default action in your button handler. You can usually do that by returning false, but preventDefault better. Here, I show doing both:

 <button type="button"  
    onclick="action(event, '.popup'); return false;">click</button>


js

function action(e, div) {
  e.preventDefault();
  var x = document.querySelector(div);
  if (x.style.display == 'block') {
    x.style.display = 'none';
  } else {
    x.style.display = 'block';
  }
}

CodePudding user response:

Here is a slightly different solution, also based upon the urge to prevent the default form submission.

I am using a custom attribute to make the code more readable.

document.querySelector('.trigger').addEventListener('click', action);


function action(e) {
  e.preventDefault();
  var x = document.querySelector(e.target.getAttribute('toggle-data'));
  if (x.style.display == 'block') {
    x.style.display = 'none';
  } else {
    x.style.display = 'block';
  }
}
<form method="post">
  <!-- toggle-data is read on click event and used to toggle a popup -->
  <button type="button" toggle-data=".popup" >click</button>
  <div >
    <p>popup</p>
    <div>
</form>

CodePudding user response:

action can not be a name for a function in any form.
use an other name for your function and it will work as you expect

function myAction(cssRef)
  {
  document.querySelector(cssRef).classList.toggle('noDisplay')
  }
.noDisplay {
  display : none;
  }
<form method="post">
  <button type="button" onclick="myAction('.popup')">click</button>
  <div >
    <p>popup</p>
    <div>
</form>

  • Related