JavaScript Form Validation Query - javascript

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();

Related

Form required fields not working when disabling submit for a few seconds

I have a submit form that needs to be disabled for a few seconds because some users are clicking more than one time since it takes a while to load, sending the request more than once.
Searching on here I have found the next code:
function disableSubmit(){
submit.value = 'Sending...';
document.getElementById("submit").disabled = true;
setTimeout(
function(){
document.getElementById("submit").disabled = false;
submit.value = 'Send';
},
5000);
}
const submit = document.getElementById("submit");
submit.addEventListener("click", disableSubmit);
I have made some additions to also change the text. The thing is that by doing this you can click the submit button without completing the fields (name, email... etc). The normal behavior is that it will throw an alert telling you need to complete this fields if they are empty, but after my personalized function the required fields are not required anymore. Any ideas? I guess it needs to take the submit normal functioning first and then my personalized function. How can I achieve this goal? Thanks

Navigate to element in Different tab of same page using focus() function

I am doing validation of entire form which is spread into different section where each section is a nav-tab , when i fill the entire form and cursor is in the last section, on clicking the save button if there is a validation mismatch of textbox in first section(first nav-tab) and if i want the user to be focused to the failed textbox document.getElementById(ID).focus()
is not navigating to the element where validation has failed.
How to achieve the above functionality??
function validate()
{
var valid = true;
var alphaFilter = /^[A-z]{0,}$/;
if (!(alphaFilter.test($('#fieldId').val()))
{
if(valid){$('#fieldId').focus();}
$('#fieldId').css("border-color", "#e84e40");
valid = false ;
}
--- each field has its own if condition
return valid;
}
validate function is called inside the submit function for further processing and valid variable is used to focus first invalid entry in the form.
I would make a param to take in selectors to make this more usable.
Something like this..
function switchtab (){
$("#tab1").removeClass("active");
$("#tab2").addClass("active");
$("#tabpanel1").removeClass("active");
$("#tabpanel2").addClass("active");
//should be good to focus now
$(selector).focus();
}

How to fade in and out a success message after page reload with jQuery?

I searched this topic a lot and got a lot of different responses, however, none of them work for me.
I have a form that when it gets successfully submitted, reloads the page.
$('form').on('submit', function(event){
if($('#input').val() == 0){
alert("Please insert your name");
event.preventDefault();
}
}
Now, on each successful submit I want a success message to slide at the top, stay there for 2 sec and then fade out.
I tried this, however, it doesn't stay after the page was reloaded.
else{
$('.success_message').fadeIn(1500);
}
Is that possible in pure jQuery?
Also, I am not looking for a way to reload the page. The page gets reloaded automatically after submitting the form.
After submitting the form, set a value in localStorage indicating that the success message should fade in:
$('form').on('submit', function(event) {
if ($('#input').val() == 0){
alert("Please insert your name");
event.preventDefault();
}
localStorage.fadeInSuccessMessage = "1"
});
Then check if the value exists in localStorage. If yes, fade in the message and delete the value from localStorage:
if ("fadeInSuccessMessage" in localStorage) {
$('.success_message').fadeIn(1500);
delete localStorage.fadeInSuccessMessage;
}

After validating & submitting form, reset form + change some css styles

I have a simple html contact form with validation check.
I would like to have some commands executed after a successful form submission. But the way I've set this whole thing up... I can't make it work.
HTML contact form:
<form id="mycontact_form" name="form_name" method="post" onsubmit="return validateForm();" action="https://domain.tld/cgi-bin/sendformmail.pl">
validateForm.js:
function validateForm() {
//validating input fields
if (!valid){
return false;
} else {
if(condition1 == true)
{
document.form_name.submit(); return;
}
else {
// doing stuff to form content
document.form_name.submit(); return;
}
}
}
When the submit button is pressed, the form is validated and will be submitted to the perl script sendformmail.pl which return a HTML Status 204 so the user stays on this page and is not redirected (that's the only way I got this part to work).
Now what I would like to have after a successful submission is:
clear/reset the form and
some minor UI stuff: change background of 2 elements + placeholder/inner text of 2 input fields for thank you message.
But for example if I put document.form_name.reset() after the document.form_name.submit(), it's too fast. It resets the form before submissions. I also tried to call another (independent) function after the validateForm() in the onsubmit but that seems to be wrong (well, at least it's not working).
So I guess I need to put these 2 things (reset + CSS changes) in a separate function and call it after a successful form submission.
But how, where and when?
I'm very interested to learn a simple yet effective solution. (but jQuery is also available)
Thank you for your help.
If your email script is on the same domain as your contact form, try submitting it via ajax. Here's a simple jQuery example, which would be in your onsubmit handler:
if (valid) {
$.ajax({
url: "/cgi-bin/sendformmail.pl",
method: "POST",
data: $("#mycontact_form").serialize()
})
.done(function() { // this happens after the form submit
$("#mycontact_form")[0].reset();
});
}
return false; // don't submit the form again non-ajax!
Otherwise, if on different domains, try setting the target of your form to the id of a hidden iframe on your page. Since this is cross-domain, you have no real way of knowing the result of the form submit due to the same origin policy. You can simply hope for the best and reset the form after X number of seconds:
if (valid) {
$("#mycontact_form").submit();
// clear form 3 seconds after submit
window.setTimeout(function() {
$("#mycontact_form")[0].reset();
}, 3000);
}
Both of these approaches keep the user on the same page without a refresh.
I ended up using beforeSend with ajax instead of done. And instead of resetting the form I chose to clear the value of the input fields/textarea (there are only 3). I also included the preferred 'post-submission' style of the input fields/textarea in beforeSend to leave nothing to chance.
Anyway, thank you for helping me & pointing me in the ajax direction.
$.ajax({
url: "/cgi-bin/sendformmail.pl",
method: "POST",
data: $("#mycontact_form").serialize()
beforeSend : function (){
// clear value of input fields/textarea & disable them
// use placeholders for "Thank you." etc.
}
});

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