- Как отключить action у формы?
- Решение
- Example of jQuery code to disable form submission action in HTML
- How to disable the action of the form via jquery?
- ASP.NET JQuery, disabled a button on form submit not call httpPost action
- How to disable <input type=»submit» . > when button is clicked
- Запрет одной из кнопок на выполнение form action. Как?
- HTML Атрибут disabled
- Синтаксис
- Значения
- Значение по умолчанию
Как отключить action у формы?
Ситуация такая. Есть модальное окно, в нём выводится форма с чекбоксами, инпут-датами и текстовыми инпутами и одна кнопка, нажатие на которую обрабатывается в JS. В JS клик по ней я слушаю так:
document.body.addEventListener('click', function(e) { if (e.target.className === 'btn-findtsk') { . } }
Так вот, когда происходит клик по кнопке, из элементов в окне в переменные считываются данные, они отправляются аяксом в скрипт php для обработки, закрывается модальное окно и на страницу выводится результат. У меня возникла проблема, что всё отрабатывает как нужно, но данные не выводятся, а в результате, словно запускается совершенно другой скрипт, который отвечает за регистрацию пользователя и появляется окно алерт «Пользователь не найден» и страница отображает ошибку. Искал в чём же ошибка, в общем наткнулся на подобное, где один человек посоветовал в подобной ситуации указать event.preventDefault(); вот так:
document.body.addEventListener('click', function(e) { event.preventDefault(); if (e.target.className === 'btn-findtsk') { . } }
Да, действительно, когда я это прописал, то всё стало работать, результат запроса аяксом выводится на страницу как нужно, но теперь возникла другая проблема, элементы checkbox и data-input на форме изменить невозможно, т. е. они не меняются и установлены по умолчанию.
Пробовал другой метод и в самой форме прописывать action=’javascript :void(0);’, но это тоже не помогло.
Как же вырулить из данной ситуации, отключить экшен формы, но чтобы всё остальное работало?
Как правильно задать action формы?
здравствуйте. есть форма для админки wordpress по ссылке.
Как запретить переход на страницу обработчика формы в action
Как запретить переход на новую вкладку при отправке данных с формы? То есть что бы код обработчика.
Как передать django переменную в атрибут формы action?
Доброго времени суток, есть форма, в ней атрибут action На данный момент запись следующая: action.
Отправка формы методом GET, используя атрибут action формы
Язык HTML. Задача состоит в том чтобы при выставленном методе отправки данных с формы "post".
Сообщение было отмечено VKont как решение
Решение
document.body.addEventListener('click', function(e) { if (e.target.className === 'btn-findtsk') { e.preventDefault(); } }
Так, конечно, работает, но тоже какая-то ошибка возникает в Jquery.
Uncaught TypeError: Cannot read properties of null (reading 'childNodes') at Function.buildFragment (jquery-2.1.4.min.js:3:14086) at n.fn.init.domManip (jquery-2.1.4.min.js:3:16823) at n.fn.init.append (jquery-2.1.4.min.js:3:14908) at n.fn.init. (jquery-2.1.4.min.js:3:16268) at n.access (jquery-2.1.4.min.js:2:30138) at n.fn.init.html (jquery-2.1.4.min.js:3:15939) at Object.success (script.js:202:15) at j (jquery-2.1.4.min.js:2:26925) at Object.fireWith [as resolveWith] (jquery-2.1.4.min.js:2:27738) at x (jquery-2.1.4.min.js:4:11253) buildFragment @ jquery-2.1.4.min.js:3 domManip @ jquery-2.1.4.min.js:3 append @ jquery-2.1.4.min.js:3 (анонимная) @ jquery-2.1.4.min.js:3 n.access @ jquery-2.1.4.min.js:2 html @ jquery-2.1.4.min.js:3 success @ script.js:202 j @ jquery-2.1.4.min.js:2 fireWith @ jquery-2.1.4.min.js:2 x @ jquery-2.1.4.min.js:4 (анонимная) @ jquery-2.1.4.min.js:4 Объект load (асинхронный) send @ jquery-2.1.4.min.js:4 ajax @ jquery-2.1.4.min.js:4 (анонимная) @ script.js:185
Пока проверил все переменные, включая чекбоксы передаются правильно, возможно эта ошибка не связана с event.preventDefault() ; пробую разобраться.
Example of jQuery code to disable form submission action in HTML
In HTML, please note the inclusion of «s» to both the form and submit button to enable JavaScript selection. In JavaScript, if there are two submit buttons, you have the option to assign a distinct value to the action page based on which button is pressed. This can be done by setting the value of the hidden element accordingly. In HTML, the implementation of this process is as follows: JavaScript is then utilized to achieve the desired functionality.
How to disable the action of the form via jquery?
onsubmit=»return false» or $(‘form’).submit(function());
Simply modify the HTML output based on the state of $_SESSION[‘cart’].
connect_error) < die("Connection failed: " . $conn->connect_error); > $name=$_POST['name']; $pass=$_POST['password']; $sql=mysqli_query($conn, "INSERT INTO insert_tbl(name,pass) VALUES('".$name."','".$pass."')") ?>
Javascript — How to disable submit action, use prevent defaults to avoid form action.please refer the code below it might help you.
. just remove action param from form and add onsubmit=»return false». It will return false everytime you click on any button in …
ASP.NET JQuery, disabled a button on form submit not call httpPost action
@Html.BeginForm("FormSubmit", "My", FormMethod.Post) < >
Eliminate the attribute [HttpPost,ActionName(«MyController»)] from the action as it is an unusual attribute.
This method provides a quick and dependable solution to disable the button and prevent any instances of «Double click».
You can see the source here
Another approach to accomplish this during the submission process is to utilize an overlay and then employ a redirection function (if desired). This optional function can be used to halt the overlay and simply notify the user that the function has been completed.
function showOverlay(buttonElement) < $(buttonElement.parentNode).css('position', 'relative'); $bgColor = $(buttonElement).attr('data-overlay-color'); if ($bgColor === undefined) < $bgColor = '#fff'; >$(buttonElement.parentNode).append(' '); //.css('background-color', $bgColor) >
You have the option to utilize this feature to generate a personalized overlay GIF. Afterwards, in the controller where you invoke the Method, you can conclude it.
Create a cshtml file named ButtonClicked.cshtml on your homepage.
Simply generate a landing page where you have the ability to input various texts, such as an example.
An alternative is to implement an overlay that includes a timeout feature.
$('form').submit(function () < var button = $('#button'); var oldValue = button.value; var isDisabled = true; button.attr('disabled', isDisabled); setTimeout(function () < button.value = oldValue; button.attr('disabled', !isDisabled); >, 3000) >);
Thank you for your response! I have successfully discovered the solution.
The issue with the code arises when I utilize the «disabled» attribute, as it modifies the request metadata during the form submit event, rendering it impossible to disable the button.
I discovered a solution that involves removing pointer events from the button, effectively preventing the issue of double submission.
$('input[type="submit"]').css("pointer-events","none")
Javascript — jQuery disable/enable submit button, In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button. If you need to disable submit button until all required input fields …
How to disable <input type=»submit» . > when button is clicked
You can disable when form submit :-
Manipulating events can be achieved by utilizing jQuery. To do so, ensure that the jQuery script is included and develop your own code.
The issue with the previous answers is that disabling the submit button prevents the name — value data pair from being posted. This happens because the button is disabled before the data is posted. However, submit buttons are typically not used for data passing. To solve this problem, one solution is to associate the data with a separate, hidden input element.
Observe that I included id elements to the form and submit button to enable selection using JavaScript.
// Get the form and the submit button. var form = document.getElementById('form'); var submitButton = document.getElementById('submit-button'); // Disables the submit button. function disableSubmitButton() < submitButton.setAttribute('disabled', '') >// Disable the submit button when the form is submitted, with fallback for IE 5-8. if (form.addEventListener) < form.addEventListener('submit', disableSubmitButton, false); >else
By having two distinct submit buttons, it is possible to send a different value to the action page. This can be achieved by dynamically assigning a value to the hidden element input based on the button that was pressed.
// Get the form and the hidden input. var form = document.getElementById('form'); var hiddenInput = document.getElementById('hidden-input'); // Set the value of the hidden input depending on which button was pressed. function setHiddenInputValue(event) < // Get the id of the button that was pressed. pressedButtonId = event.target.id; // Set the value of the hidden input element to be the same as the id of the pressed button. hiddenInput.setAttribute('value', pressedButtonId); // Disables the submit button that was pressed. function disableSubmitButton(event) < event.target.setAttribute('disabled', '') >// Disable the submit button when the form is submitted, with fallback for IE 5-8. if (form.addEventListener) < form.addEventListener('submit', function(event) < // Event object fallback for IE 5-8. if (!event) < event = window.event; >setHiddenInputValue(event); disableSubmitButton(event); >, false); > else < form.attachEvent('onsubmit', function(event) < // Event object fallback for IE 5-8. if (!event) < event = window.event; >setHiddenInputValue(event); disableSubmitButton(event); >); >
How to disable the action of the form via jquery?, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more
Запрет одной из кнопок на выполнение form action. Как?
Нужно чтобы при нажатии на кнопку «Сгенерировать» выполнялся JS скрипт, но не выполнялся запрос к php файлу. Что делать?
return false; отменяет все переходы (которые делает не JS конечно). Это относится и тегам a.
В данном случае тег form осуществляет переход (не JS), следовательно его можно отменить
или так:
document.getElementById("Gen").addEventListener("click", function()< return false; >)
Для решения вашей задачи следует, прежде всего, однозначно определять тип кнопок. Для отправки формы submit, для выполнения кода button. Не нужно кнопке, не связанной с отправкой формы, задавать тип submit.
Отдельно обрабатывать отправку формы (которая может случиться и не при клике на кнопку), отдельно click на кнопке с типом button.
Пример
HTML Атрибут disabled
Атрибут disabled (от англ. «disabled» ‒ «неработающий, отключённый») блокирует элемент формы, то есть делает его неактивным.
Заблокированный элемент по умолчанию имеет серый фон. Кроме того, такое поле не может получить фокус путем нажатия на клавишу Tab , мышью или другим способом. Заблокированное в поле значение не передаётся на сервер.
В случае кнопки ( или с атрибутом type в значениях button , reset или submit ) блокировка означает, что на кнопку нельзя будет нажать.
В случае с текстовым полем ввода ( или ) в нем нельзя будет поменять или скопировать текст.
В случае с чекбоксами и радио кнопками их состояние (отмечено или нет) нельзя будет сменить.
В случае с выпадающими списками нельзя будет сменить выбранный пункт списка.
Блокировка элементов обычно нужна для того, чтобы запретить пользователю менять некоторые значения (которые, тем не менее, должны быть показаны пользователю в виде элементов формы). Иногда элементы блокируют (и снимают блокировку) с помощью скриптов (например JavaSctipt).
Для визуального отличия заблокированных элементов формы от активных, большинство современных браузеров не существенно изменяют внешний вид заблокированных элементов. Тем не менее, с помощью CSS, используя псевдоклассы disabled и enabled, можно установить свои стили заблокированным и незаблокированным элементам.
Синтаксис
Значения
Данный атрибут является логическим атрибутом. В HTML данный атрибут может указываться либо без значения, либо с пустым значением, либо со значением disabled .
Значение по умолчанию
По умолчанию этот атрибут выключен.