Disable form submission if a field has invalid values - javascript

I have a html form with multiple textboxes. Each textbox can accept only integers.
I am using dojo NumberTextBox to validate this.
But the problem is, even if a textbox is in error, only an error tooltip is displayed but the user can still press the submit button.
Is there a way to disable the submit button if any textbox is in error?

You need to have a custom submit button.
<button onClick='submitForm("NAME OF FORM")' value='Submit'>
<Script>
function submitForm(name) {
var bad = 0;
for(Loop through values) {
if(isNaN(num)) {
bad = 1;
}
}
if(bad==0) {
document.forms[name].submit();
}
}
</script>

Related

Preventing form submission with invalid fields

I have been trying to make a simple HTML form that takes a phone number, password, and confirmed password. I tried using the HTML5 required attribute to ensure all fields were filled out upon submission, but since finding out Safari doesn't support that, I moved on to using the following code from a different stack overflow topic to validate the form:
var form = document.getElementById('text'); // form has to have ID: <form id="formID">
form.noValidate = true;
form.addEventListener('submit', function (event) { // listen for form submitting
if (!event.target.checkValidity()) {
event.preventDefault(); // dismiss the default functionality
if (document.getElementById('password_confirm').value != document.getElementById('password').value) {
alert('Passwords must match');
//document.getElementById("alert_pw_match").style.color = rgba(37, 33, 90, 0.64);
} else {
// input is valid -- reset the error message
alert('All fields are required');
}
}
}, false);
The issue I'm having is that I want to move away from using the standard alert boxes and just highlight the relevant fields or display some text indicating why the form is invalid, but whenever I add a line other than the alert the form submits without anything happening.

JavaScript method not working in HTML

So I have a button that calls the AllEntered() javascript method when it is clicked and as you can see in the final if/else, it should either got to submission.html or admin.html but instead of going to either of those it just reloads the current page that I am on. This is all inside a form by the way and its purpose is to check if all checkbox inputs are checked. Also the alert doesn't i put for loop-number doesn't generate either.
zbutton onclick="AllEntered()" class="myButton">Submit</button>
<script>
function AllEntered()
{
var ids = {"freshSoph", "participate", "respect", "leave", "illegal", "alcohol", "typeName"};
var loopNumber = 0;
for(var i = 0; i < ids.length - 1; i++)
{
if(document.getElementById(ids[i]).checked)
{
loopNumber++;
alert(loopNumber.value);
}
}
if(loopNumber = ids.length)
{
window.open("submission.html");
}
else
{
window.open("admin.html");
}
}
</script>
Open your browser developer tools. Read the error message.
You have a typo. An array is created with [], not {}.
(And of course it reloads the page, that is what clicking a submit button inside a form does).
In your form, below this button, add one more button as a hidden input of type submit like so:
<button hidden type="Submit">
Your problem could be caused by the fact that you are missing a submit type button.
When a form has no button of type Submit ( which on click will submit the form to its target or TO ITS SELF if no target is specified. This is what we call postback, as in posting back to your self ) it will use any buttons click as a submit event raiser.
By adding an actual submit button you remove this default behaviour, while also ensuring the user cant click on it, as the control is not active when its hidden.

JavaScript Form Validation Query

I've just wrote some validation code so as to check if either of my radio buttons from my web form have been selected before they are submitted. I've just starting learning php as I want to be able to store the value of each radio button in a .csv file.
Because I have my action attribute set to trigger a php script, I get my alert box, but as soon as I click OK after pressing submit the browser goes straight to the php script (inevitably).
Is there a way I can return to my initial index.html after the alert message?
I have not actually written any php as yet, so would this go in the php script or the javascript?
Heres my code so far:
$("#submit").on("click", function() {
var radio = $("input[type=radio][name=emotion]")[0].checked;
var radio2 = $("input[type=radio][name=emotion]")[1].checked;
var radio3 = $("input[type=radio][name=emotion]")[2].checked;
if(!radio && !radio2 && !radio3) {
alert("You must select at least one word!");
}
else {
alert("Please rate the next item!")
}
});
In Jquery you should use .submit() function to validate a form.
Then to avoid to submit the form you can use the function event.preventDefault()
And if you want to go to the index you can use window.location = "yourURL"
You must use form.onsubmit().
For example, if your form's name is myForm:
document.forms['myForm'].onsubmit = function()
{
if (this.elements['emotion'].value)
{
alert("Please rate the next item!");
}
else
{
alert("You must enter at least one word!");
return false;
}
}
And after alert "Please rate the next item!" form will be send.
Actually you can use jquery $.post() , an easy solution is just to post your php page without leaving index page.
http://api.jquery.com/jquery.post/
$.post( "yourpage.php" );
You probably have the input type of the submit button as submit? Set this to button, so the action doesn't take place and only jQuery is executed.
But then you have to submit the form by jQuery when validation was successful:
document.myFormId.submit();

jquery dialog submit button cannot control enable/disable

I've been battling with this issue all day. I am hoping someone has an answer for me. I did a bunch of searching and can't seem to find an answer.
I have a page that has 3 forms on it. I am working within the 2nd form. None of the forms are embedded within another form.
I have a hidden div that contains two form elements, a drop down list and a text box, and a submit button that I anticipated it posting to the form it is enclosed in. On another button within the form itself (not submit button), I have javascript that launches jquery.Dialog, that code looks like this:
function showReleaseDiv() {
var div = $("#ReleaseHoldsDiv");
var f = div.closest("form");
div.dialog({ width: 270, height: 187, modal: true, title: 'Bulk Hold Resolution' });
div.parent().appendTo(f);
}
This part does function correctly. I've overcome the typical jquery issue where it pulls the contents of the dialog out of the form, so I put it back in the form, but wonder if this is causing my real issues which are:
The drop down list and text box are both required before I post, so I default the submit button to disabled, then I have an onchange event on the drop downlist, and the onkeyup on the text box call the following javascript:
function enablePopupRelease() {
var button = $("PopupReleaseButton");
if (button && button != null) {
button.attr("disabled", "disabled");
if ($("#ResolutionTypeCode").val() != "" && $("#ResolutionComments").val() != "") {
button.removeAttr("disabled");
}
}
return true;
}
Both events fire correctly and I step through the code; all seems fine, but the button disable state does not change.
Please help.
I believe you are missing a hash on this line:
Change:
var button = $("PopupReleaseButton");
to
var button = $("#PopupReleaseButton");
firstly I would clean some code as follows:
function enablePopupRelease() { var button = $("PopupReleaseButton"); if (button) { button.attr("disabled", "disabled"); if ($("#ResolutionTypeCode").val() && $("#ResolutionComments").val()) { button.removeAttr("disabled"); } } return true; }
Let me know if makes any difference please?
if you break through the code ... does it stop at button.removeAttr("disabled"); please?
Are you using the jQuery UI button widget for the form's submit button? If so, you will need to call
$("#PopupReleaseButton").button({disabled: true});
to disable the button.
disabled isn't an attribute, it's a property -- try using button.prop('disabled',true) and button.prop('disabled',false) instead.
http://api.jquery.com/prop/

Form confirmation on submit

I want to have a confirmation from the user before they submit a form. This will prevent accidental POSTing of the form, that may be incomplete or incorrect.
Here is my form element:
<form action="manager.php?method=update&id=<?php echo $user->id;?>" onsubmit="return confirm_update();" method="POST" id="user_update">
This calls my function confirm_update()
function confirm_update()
{
if(confirm("Do you wish to update details?"))
{
return 0;
}
else
{
return 1;
}
}
The problem with the script is that it does not prevent the form from POSTing if the user clicks Cancel in the JavaScript prompt.
How do I correct this so that the user does not accidently submit their form?
Here is a full description of the feature I am trying to implement:
Use Case - "Update Details"
User goes to update page
User enters details in form fields
User hits submit button
Confirmation message appears
If "Ok" button selected proceed to submit form
Else cancel action and stay on current page
Instead of returning 0 and 1, return true and false. You can actually shorten the function to:
function confirm_update() {
return confirm("Are you sure you want to submit?");
}
You're doing it the other way round!
if(confirm("Do you wish to update details?"))
{
return 1;
}
else
{
return 0;
}
Having said that, your code can be shortened to just one line:
return confirm("Hit OK to continue, Cancel to... cancel.");
Try:
function confirm_update() {
if(confirm("Do you wish to update details?")) {
return true;
}
else {
return false;
}
}
I would do an onclick returning false by default, this works for me
<form action="manager.php?method=update&id=<?php echo $user->id;?>" method="POST" id="user_update">
<input type='submit' onclick="return confirm('Do you wish to update details?');return false;"/>
</form>
First of all you should reconsider your approach. Instead of asking whether the user wants to submit a potentially incomplete or invalid form, you should use javascript to prevent this from happening, i.e. perform client-side validation using js. What you are doing is inherently done by clicking submit...
If however you want to keep your approach, you have to prevent the submit button from actually submitting the data to the specified action, e.g by changing the form action to "#" via javascript and then trigger the submit if ok was clicked with your js-code, e.g. by using a XmlHttpRequest.

Categories