There is a button to submit the form button. By clicking on it, a modal window should appear at the end. Instead, a window appears, immediately the page reloads and the window disappears. I understand that this is precisely because it is a button. What is the way out?

The problem is exactly when the button is in the form tag. And it does not matter where our modal window is, in the form or not. Anyway, the window opens and closes immediately.

$("#sub_toggle").click(function() { $('#sub_modal').show(); }); <div id="sub_modal"></div> <button id="sub_toggle"></button> 
  • show html code - artem55555p
  • corrected the first post - Denis Denis
  • the form is not even connected yet - Denis Denis

2 answers 2

You can do this:

 $("#sub_toggle").click(function() { $('#sub_modal').slideToggle(); }); 
 #sub_modal { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="sub_modal">модалка</div> <button id="sub_toggle">кнопка</button> 

But:

The page reloads due to the form being sent. If the form is on ajax, then do a form submission check via jquery ajax success, and if not, then you can send the parameter to the url via php index.php?response="openmodal" and then do a type check if $_GET['respons'] == 'openmodal'

  • how does this differ from my script?) at least toggle, at least slideToggle effect is the same - Denis Denis
  • <button id = "sub_toggle" "> you have an extra quote here - artem55555p
  • I was wrong here, everything is fine in the markup ( - Denis Denis
  • one
    @ Daniel agrees with you. - artem55555p
  • one
    @Devergence is true, but the author most likely needs to make a conclusion with the answer, add the event into the brackets - Daniel

The <button> has a type attribute.

By default, it is set to type="submit"

To prevent the form from being sent, it is enough to set type="button" , which will make the browser aware that this is a stub button - details about the <button>

  • Same as event.preventDefault (); - Daniel
  • It is logical to assume that if button submit is there, then I need the form to be sent. Otherwise I could use any tag - Denis Denis
  • @DenisDenis, so you had to leave the default value on the button that sends the form. On all the others -> it was necessary to put type="button" - Vlad Volkov
  • @Daniel, it's not the same as if ... it's one thing to use native html5 and do everything semantically correctly, another is to use JS where it is not needed. With such success, you can not use the form at all, and even input, and write everything through ' <div editable="true"> '. Kochylno, uncomfortable, useless. - Vlad Volkov
  • If there is js possible without it - Daniel