Reputation: 13
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.
<form class="add_form" id="add_list_form">
<input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />
<div class="mt-2">
<button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
<button class="btn btn-sm btn-danger" id="close_btn">close</button>
</div>
</form>
<script>
const add_list_form = document.querySelector('#add_list_form');
add_list_form.addEventListener('submit',(e)=>{ e.preventDefault();
console.log('form is submitted..') })
<script>
Upvotes: 1
Views: 556
Reputation: 21
You can use in js method preventDefault() to not to have a default submit or reload by default
Upvotes: 0
Reputation: 6857
You can add type="button"
to the button that you want to use to hide the form, which will remove the default behavior.
Here is an example,
const form = document.getElementById('form');
const otherBtn = document.getElementById('close-btn');
otherBtn.addEventListener('click', () => {console.log('Close button was clicked')});
form.addEventListener('submit', (e) => {e.preventDefault(); console.log("form got submitted")})
<form id="form">
<input type="email" placeholder="email"/>
<input type="password" placeholder="password"/>
<button type="submit">Submit</button>
<button type="button" id="close-btn">Close</button>
<form/>
Upvotes: 2
Reputation: 938
add type="button"
attribute in your close button tag, without specifying this type attribute, browser consider every button as submit button by default in the form element.
your close button element should look like this:
<button type="button">close</button>
Upvotes: 0
Reputation: 5444
See to it that you've added the right type
attribute for the 2 buttons
<button type="submit">Submit</button>
<button type="button">Close</button>
Upvotes: 1