Change values in form submitted and the JQuery serialize function - javascript

Please look at the following code. When the form gets submitted, is it actually submitting the values I have entered i.e. val(50) or at the point it serialzies does it just get data from the form on the actual html page?
// stop all forms from submitting and submit the real (hidden) form#order
$('form:not(#order)').submit(function(event) {
alert($(this).attr('id'));
//event.preventDefault();
if($(this).attr('id')==='quick2a'){
alert('quick2a being submitted');
//submitQuick2a();
$('form#order input[name=custom_channels]').val(50);
var name = 'het-';
name += $('form#order input[name=platform]').val('astsk');
name += '-ga-';
name += $('form#order input[name=license]').val('floating');
$('form#order input[name=productname]').val(name);
$.post('/store/cart/add/ajax/', $('form#order').serialize(), function() {
document.location.href = '/store/checkout';
});
}else{
//
}
I want those values to be set in the form regardless of what is set by the user, am I doing this correctly?
Thanks all

Why not just construct the data directly instead of stuffing it into a form and then grabbing the values via serialize?
$('form').submit(function(event) {
if($(this).attr('id')==='quick2a') {
var data = {
'custom_channels': 50,
'platform' : 'astsk',
'license' : 'floating',
'productname' : 'het-astsk-ga-floating'
};
$.post('/store/cart/add/ajax/', data, function() {
document.location.href = '/store/checkout';
});
}else{
//
}
return false;
});

It gets the values from the HTML page... but by calling .val(...) you're setting the values on the HTML page, so your code will work as you want it to.

Related

Store form in localstorage, retrieve it later for submit

In a wordpress website I want that when someone fills a product form (select attributes etc) and clicks buy now, if is not logged in then he is redirected to login form. On succesfull login I want to get the submitted form contents from localstorage, fill the form and then submit the form automatically.
Is that possible?
I found that I can store the submitted form like this (but how I can refill the form automatically?):
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
var formFields = $(this).serialize();
localStorage.setItem('myForm', formFields);
//data = localStorage.getItem('myForm'); //retrieve it later
});
});
You should be able to retrieve data from localStorage, get your form fields using DOM selectors and fill their values using the data from localStorage.
In vanilla JS, you can probably do the following:
document.addEventListener('load', () => {
// check if user is logged in according to your usecase
if(isLoggedIn()) {
try {
const formData = JSON.parse(localStorage.getItem('myForm'));
// get input fields. If you have some unique id associated to them, you can use document.querySelector(`#${inputId}`);
const inputFields = document.querySelectorAll('input');
for(let i = 0; i<inputFields.length; i++) {
const inputId = inputFields[i].getAttribute('data-id');
// fallback to empty string in case it is not found in localStorage object
inputFields[i].value = formData[inputId] || '';
}
} catch(e) {
// handle error
}
// Now you have the form input fields pre-filled, add custom logic from here ..
}
})
/*
--- Sample DOM ----
<input data-id="name" />
<input data-id="city" />
---- Form fields saved in localStorage ---
{ name : 'Naruto', city: 'Leaf Village' }
*/

jQuery form: on submit validation issue + stay on the same page after submit

I'm not a programmer, just trying to fix & improve my contact form. Right now it's a HTML form (name, email, 4 checkboxes as subject, message). And mail.php (update: method="POST"). Everything works, I receive all form data.
But I have found a script to validate name, email & message inputs, here it is:
<script>
$(document).ready(function() {
<!-- Real-time Validation -->
<!--Name can't be blank-->
$('#contact_name').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Email must be an email -->
$('#contact_email').on('input', function() {
var input=$(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email=re.test(input.val());
if(is_email){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Message can't be blank -->
$('#contact_message').keyup(function(event) {
var input=$(this);
var message=$(this).val();
console.log(message);
if(message){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!-- After Form Submitted Validation-->
$("#button").click(function(event){
var form_data=$(".myform").serializeArray();
var error_free=true;
for (var input in form_data){
var element=$("#contact_"+form_data[input]['name']);
var valid=element.hasClass("valid");
var error_element=$("span", element.parent());
if (!valid){error_element.removeClass("error").addClass("error_show"); error_free=false;}
else{error_element.removeClass("error_show").addClass("error");}
}
if (!error_free){
event.preventDefault();
}
else{
alert('No errors: Form will be submitted');
}
});
});
</script>
Originally, it was showing error messages next to input fields, I decided not to use them (spans in HTML, "error" & "errow_show" classes in CSS), leaving just input field highlighting ("valid" green/"invalid" red CSS classes).
I feel like the problem is these lines:
var error_element=$("span", element.parent());
if (!valid){error_element.removeClass("error").addClass("error_show"); error_free=false;}
else{error_element.removeClass("error_show").addClass("error");}
And this script highlights empty name, invalid email and empty message. But when I click "SEND" button, the script, despite highlighting invalid fields, shows the alert "No errors. Form will be sumbitted" and sends form to me. The problem seems to be in its last part. I do not know how to properly remove "span", "error" and "error_show" from this script (3 lines before the second IF). I want my form to send everything to me if everything is valid and not send anything ("disabled button"?) if something is invalid. Without any alerts. If it also could stay on the same page after sumbitting... it would be an ideal thing (Submit form and stay on same page?, Submit a form using jQuery, jQuery AJAX submit form). Any help would be greatly appreciated!:)
UPDATE: form html: (removed as unnecessary now)
UPDATE 2: well, guys, this (weird? incorrect? semi-correct?) code I suddenly made up checks and highlights correctly as "valid"/"invalid" all 3 required fields (name, email, message) and shows correct alerts (I'll remove them later) on #button_send click and even sends the whole form with non-required non-validated checkboxes to me:
$('#button_send').click(function(){
if ($('#contact_name').hasClass('valid') && $('#contact_email').hasClass('valid') && $('#contact_message').hasClass('valid')) {
alert('No errors');
$('.form').submit();
} else {
alert('Errors');
return false;
}
});
I want to thank everyone for every piece of advice and help.
You want to prevent the default action of the button and then call submit when you are ready.
http://api.jquery.com/event.preventDefault/
<!-- After Form Submitted Validation-->
$("#button").click(function(event){
// prevent the form from being submitted
event.preventDefault();
var form_data=$(".myform").serializeArray();
var error_free=true;
for (var input in form_data){
var element=$("#contact_"+form_data[input]['name']);
var valid=element.hasClass("valid");
var error_element=$("span", element.parent());
if (!valid){error_element.removeClass("error").addClass("error_show"); error_free=false;}
else{error_element.removeClass("error_show").addClass("error");}
}
if (error_free) {
alert('No errors: Form will be submitted');
// submit the form if no errors
$( ".myform" ).submit();
}
else{
alert('Errors shown');
}
});
});
The Problem:
The behavior you're seeing is because you deleted the controls that your code was using to validate/invalidate your form. Without those controls, due to the way it was written, it defaults to a valid state regardless of the actual validity of the inputs.
Solution #1:
If you have a backup, the easy thing to do would be to revert back to how it was before you touched it and just add 'hidden' as properties to your spans. This way they wouldn't be visible to your user, but would still validate the inputs for you.
Solution #2:
If you aren't able to do that, then you'll need to modify your submission code to validate off the remaining controls and their classes. I don't have your full code to test this, but I believe something like this would work:
<!-- After Form Submitted Validation-->
$("#button").click(function(event){
var error_free=false;
$.each($('.myform > input'), function() {
error_free = $(this).hasClass('valid');
if (!error_free){
event.preventDefault();
return false;
}
});
if (error_free){
alert('No errors: Form will be submitted');
}
});
The snippet above loops over any inputs inside of the control with the class 'myform' and checks if they have the 'valid' class, then sets a variable true or false depending. If it detects there is an invalid control, it exits the loop and does not proceed with Posting the form.
Hope that helps.
If you want it to be save, I recommend you to do backend validation to.
If in your HTML form, the method is set to "post", this will do the magic;
$(document).ready(function() {
<!-- Real-time Validation -->
<!--Name cant be blank-->
$("#contact_name").on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Email must be an email -->
$("#contact_email").on('input', function() {
var input=$(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email=re.test(input.val());
if(is_email){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Message cant be blank -->
$("#contact_message").keyup(function(event) {
var input=$(this);
var message=$(this).val();
console.log(message);
if(message){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!-- After Form Submitted Validation-->
$("#button").click(function(event){
event.preventDefault();
var form_data=$(".myform").serializeArray();
var error_free=true;
for (var input in form_data){
var element = $("#contact_"+form_data[input]['name']);
var valid = element.hasClass("valid");
if (!valid){
error_free=false;
element.addClass("invalid");
}
}
if (error_free){
//Submit the form
$.post({url: 'mail.php', data: form_data, dataType: 'json'}).done(function(){
//clear the fields
$("[id^=contact_]").val('');
})
}
});
});

How to remember form data that has not been submitted?

How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});

Working form without action

I'm trying to do html form without action. It must:
1) Remember input data as normal form do.
2) Doesn't reload page
I tried:
<form action="javascript:void(0);" id="simple-form">
But on
$('#simple-form').submit();
form didn't remember input data.
Normal form
<form action="#" id="simple-form">
reloads page but also remembers input data.
Does exist another way to remember data without forms with javascript?
Update #1:
event.preventDefault(); // onsubmit event prevert
Doesn't work same because it's preventing not only reload of page but also saving of data (autocomplete).
With javascript
var form = document.getElementById("simple-form")
form.onsubmit = function (event) { event.preventDefault() }
if(localStorage){
var textfield = document.getElementById("yourTextfield");
var data = localStorage.getItem("yourTextfield");
if(data){
textfield.value = JSON.parse(data);
}
textfield.onkeydown = function(){
localStorage.setItem("yourTextfield",JSON.stringify(textfield.value));
}
}
ok alternative solution with history object
var data = history.state.textfieldName;
if(data){
textfield.value = data;
}
textfield.onkeydown = function(){
history.state.textfieldName = textfield.value;
}

Referencing a form assigned to a variable in jQUERY

I have a form with id='form1' as well as another one with 'form2'. On submit, i want to pass both forms as objects to a single validate function which can validate them. I am confused on how to do this.
If i do something like
var form = $('#form1');
Validate(form);
how do i access the text-fields of the variable form?
i don't want to write duplicate validate functions as both forms are ALMOSt similar.
You can do following also...
A Complete example is here...
function validate(formid){
var form = $("#"+formid);
var name = form.find("#name");
var number = form.find("#number");
alert(name.val());
alert(number.val());
}
validate("form1");
validate("form2");
Try .find. Your form will serve as the context and you could reuse it for different forms.
See below:
var form = $('#form1');
function Validate(form){
var field1 = form.find(".field1");
}
With the name of the fields, you can do this:
function Validate(form) {
form = form[0]; // raw element
if (check_syntax(form.name.value)) { doSomething(); }
if (check_syntax(form.email.value)) { doSomething(); }
if (check_syntax(form.anotherfield.value)) { doSomething(); }
}
If every field in the form has a name, you can access it via form.fieldName or form['fieldName'].
Regards.
Assuming both forms are similar:
ValidateForm($("#form1, #form2"));
function ValidateForm(forms){
forms.each(function(){
$(this).find('input[type=text]').each(function(){
//Do something to validate text field
})
$(this).find('input[type=checkbox]').each(function(){
//Do something to validate checkbox
})
})
}

Categories