Prevent form action html

Запретить HTML от отправки с помощью JavaScript/jQuery

В этом посте мы обсудим, как предотвратить отправку формы HTML в JavaScript и jQuery.

Самое простое решение для предотвращения отправки формы — вернуть false в обработчик события отправки, определенный с помощью onsubmit свойство в HTML элемент.

HTML

Choose your preferred contact method:

В качестве альтернативы вы можете позвонить в Event.preventDefault() чтобы предотвратить выполнение действия по умолчанию при отправке формы.

HTML

Choose your preferred contact method:

Обратите внимание, что всегда рекомендуется отделить JavaScript от разметки HTML, но приведенное выше решение не может этого сделать. Лучшее решение — привязать обработчик события к событию “отправить” JavaScript. Событие отправки срабатывает всякий раз, когда пользователь отправляет форму.

JS

HTML

Choose your preferred contact method:

Это все о предотвращении HTML

от отправки в JavaScript и jQuery.

Средний рейтинг 4.27 /5. Подсчет голосов: 37

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Prevent form action html

Last updated: May 24, 2023
Reading time · 4 min

banner

# Table of Contents

# Prevent a button from submitting the form using JavaScript

To prevent a button from submitting the form in JavaScript:

  1. Use the addEventListener() method to add a click event listener to the button.
  2. Use the event.preventDefault() method to prevent the button from submitting the form.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> form> input id="first" name="first" /> input id="last" name="last" /> button id="btn">Clickbutton> form> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); const firstNameInput = document.getElementById('first'); const lastNameInput = document.getElementById('last'); btn.addEventListener('click', event => event.preventDefault(); console.log(firstNameInput.value); console.log(lastNameInput.value); >);

We used the document.getElementById method to select the button and the two input elements.

The next step is to add a click event listener to the button element.

When the button is clicked, the callback function is invoked where we call the event.preventDefault() method.

Copied!
btn.addEventListener('click', event => event.preventDefault(); console.log(firstNameInput.value); console.log(lastNameInput.value); >);

The preventDefault method tells the browser to not take the default action of the event.

In case of a button click, the default action is to submit the form.

This means that the form won’t be submitted and the page won’t get refreshed.

# Prevent a button from submitting the form by setting its type to button

You can also prevent a button from submitting the from by setting its type attribute to button .

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> form> input id="first" name="first" /> input id="last" name="last" /> button type="button" id="btn">Clickbutton> form> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); const firstNameInput = document.getElementById('first'); const lastNameInput = document.getElementById('last'); btn.addEventListener('click', event => console.log(firstNameInput.value); console.log(lastNameInput.value); >);

Notice that we set the button’s type attribute to button .

Copied!
button type="button" id="btn">Clickbutton>

By default, the button’s type attribute is set to submit .

The default behavior is for the button to submit the form, however, this can be changed by setting the button’s type attribute.

Notice that we didn’t have to call the event.preventDefault() method in the example.

# Prevent a button from submitting the form by returning false

You can also prevent a button from submitting the form by returning false from the form’s onsubmit attribute.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> form onsubmit="return false;"> input id="first" name="first" /> input id="last" name="last" /> button id="btn">Clickbutton> form> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); const firstNameInput = document.getElementById('first'); const lastNameInput = document.getElementById('last'); btn.addEventListener('click', event => console.log(firstNameInput.value); console.log(lastNameInput.value); >);

This time, we set the onsubmit attribute on the form element.

Copied!
form onsubmit="return false;"> form>

The submit event is triggered when the form is submitted.

When the form is submitted, we return false straight away which prevents the browser from taking the default action.

# Prevent a button from submitting the form by disabling the button

You can also prevent the user from submitting the form by disabling the button.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> form onsubmit="return false;"> input id="first" name="first" /> input id="last" name="last" /> button id="btn" disabled>Clickbutton> form> body> html>

prevent button from submitting form by disabling button

We set the disabled attribute on the button element so it cannot be clicked.

In some cases, you might only want to disable the button when the input fields are empty.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> form> input id="first" name="first" /> input id="last" name="last" /> button id="btn" disabled>Clickbutton> form> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); const firstNameInput = document.getElementById('first'); const lastNameInput = document.getElementById('last'); firstNameInput.addEventListener('input', event => disableOrEnableButton(); >); lastNameInput.addEventListener('input', event => disableOrEnableButton(); >); function disableOrEnableButton() if ( firstNameInput.value.trim() && lastNameInput.value.trim() ) btn.removeAttribute('disabled'); > else btn.setAttribute('disabled', ''); > > btn.addEventListener('click', event => console.log(firstNameInput.value); console.log(lastNameInput.value); >);

The button starts as disabled and then when the values of the input fields change:

  • If at least one input field is empty, the button remains disabled
  • If both input fields have values, the button is no longer disabled

The input event is triggered when the value of an input , select or textarea element has been changed.

Copied!
firstNameInput.addEventListener('input', event => disableOrEnableButton(); >); lastNameInput.addEventListener('input', event => disableOrEnableButton(); >);

When the value of the input field changes, we call the disableOrEnableButton function.

Copied!
function disableOrEnableButton() if ( firstNameInput.value.trim() && lastNameInput.value.trim() ) btn.removeAttribute('disabled'); > else btn.setAttribute('disabled', ''); > >

The function disables the button if at least one input field is empty, otherwise, it removes the disabled attribute.

The String.trim method is used to prevent the user from only entering spaces in the input field.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Prevent form submit event from reloading the page

In this article, we are going to discuss 2 options that how you can prevent your HTML form submit event from reloading the page. Normally, when you submit the form, it redirects to the action attribute link. But you can stop that reload and call an AJAX or any other Javascript function.

1. preventDefault

You can call the preventDefault function on the event target and it will stop the form from redirecting to the page specified in the action attribute of the tag.

Then you can create the following Javascript function to prevent the page reload:

In this method, the form is first prevented from submission and then your Javascript code will be run. So it prevents the form submit event first, then it will run our Javascript code which is a good approach.

You can learn more about preventDefault from here.

2. return false

The second approach is to use the return false statement in your Javascript code. For this, you also need to return the value from the onsubmit event function. Let’s check this out.

Then create your Javascript function as like that:

In this method, your Javascript code runs first before preventing the form submission.

Recommendation

We would recommend the 1st method i.e. preventDefault because it is the very first line of the Javascript function. So if there is an error in your Javascript code, your browser will not get reloaded and thus you will be able to view the error in the browser console.

Now that you have learned to prevent the form submit event. You can also display a pop-up for confirmation in case of the delete function. You can follow this tutorial to display a pop-up confirmation before submitting the form.

Источник

Stop form submission using JavaScript preventDefault() Event Method

In projects, it is often necessary to prevent form submission after clicking the submit button of an HTML form. So in this tutorial, we are going to see how to prevent or stop an HTML form from submitting even after clicking the form submit button.

To better understand let’s create an HTML form. Below is the code of our HTML form:

 First name:  
Last name:
Phone number:

We have a submit button in the form which has the id “submit-btn”. Now if we click the button, the form will be submitted.

But suppose for some purpose we don’t want to let our form submitted. How can we do it? Is there any way to prevent the form from submission.

Well, JavaScript has a method that can prevent the default action that belongs to the event. That means the default action will not occur. This is JavaScript preventDefault() event method which can stop the form submission.

Now we are going to prevent our form submission that we have just build using the preventDefault() event method of JavaScript. Below is our JavaScript code which can do this job:

document.getElementById("submit-btn").addEventListener("click", function(event)< event.preventDefault() >);

In the above code, we have first applied the click event listener to the HTML form submission button. Inside the click event listener, we have applied the preventDefault() JavaScript method.

How to get value from input box in JavaScript?

That’s it. Now if we test our form on the browser, we will see that after clicking the form nothing has happened. Our form has not submitted. Now we can clearly say that we have prevented our form from submission using JavaScript preventDefault() method.

The supported browser of the preventDefault method is Chrome, Internet Explorer 9.0, Safari, Mozilla and opera.

So from this tutorial, we have learned how to prevent an HTML form submission using javaScript.

Источник

Читайте также:  Negative numbers java random
Оцените статью