I have a signup form which is having some 12 fields. I want to validate data in those fields. First step is to check if any field is empty. One way of doing this is to get each field using Jquery and check if it is empty. I was planning to create a var array and check status of each field inside a loop using this code :
var input = new Array();
input[0] = $('.fullName')[0];
input[1] = $('.emailID')[1];
input[2] = $('.phno')[2];
input[3] = $('.userName')[3];
input[4] = $('.password')[4];
input[5] = $('.batch')[5];
input[6] = $('.nickname')[6]
input[7] = $('.enrno')[7];
input[8] = $('.dob')[8];
input[9] = $('.fromCity')[9];
input[10] = $('.currcity')[10];
input[11] = $('.interests')[11];
input[12] = $('.currComp')[12];
input[13] = $('.currDesig')[13];
Now I have to run a loop to get the values and check if any field is blank.
I am writing this code for checking
for(i=0;i<14;i++)
if(input[i].val()=="")
{
// do my work
}
But the problem is that the last 15 lines of code are pointing to actual HTML DOM element, so I can't use input[i].val() directly to access the value. Any way out?
You seriously need to just add a common class to the elements that needs validation, and then do
var is_valid = $('.validate_these').filter(function() {
return $.trim(this.value) === "";
}).length === 0;
That gets all the elements with that class, and filters them based on wether or not the value is empty. If no empty elements where found, it's valid
Related
I am trying to make a dynamic dropdown list and Section Navigation in Google Form. However, my script can auto delete the choice when the quota has been met, the choice can’t navigate to the related page for other selections.
I am planning a health check event for my hospital. It needs to reserve by timeslot and date due to the crow control policy. The links below are my Google Spreadsheet for the form and my daft Google Form of the function.
https://forms.gle/ZV9Djni8hyQGdAd86
https://docs.google.com/spreadsheets/d/1F1dpGCTSlpEOUMh5txsZouhx784JmJvh66IsiGfDTtg/edit?usp=sharing
Reference:
How to set the go to sections on a Google Forms question using app script
https://www.pbainbridge.co.uk/2019/04/dynamically-remove-google-form-options.html
function appointmentSlots() {
var form = FormApp.openById("1VqFBKBD_-iKYk_3Ze40j2tvRIi093-alaoCDsXpFi8k");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var date1timelist = form.getItemById("2101588132").asListItem();
var optionsSheet = ss.getSheetByName('Date Options');
var dateoptions = optionsSheet.getRange('A2:A3').getValues();
var dateleft = optionsSheet.getRange('C2:C3').getValues();
var day1sheet = ss.getSheetByName('9/3');
var day1timeoptions = day1sheet.getRange('A2:A4').getValues();
var day1left = day1sheet.getRange('C2:C4').getValues();
var formFieldsArray = [
["9/3", 2061926149],
["10/3", 1632977105]
];
for(var h = 2; h < formFieldsArray.length; h++) {
var datelist = form.getItemById(formFieldsArray[h][2]).asListItem();
var avaibledateoptions = [];
var sectionday1timeslots = form.getItemById("2101588132").asPageBreakItem();
var sectionday2timeslots = form.getItemById("1630116063").asPageBreakItem();
var datechoice = datelist.getChoices();
var optionsDataLength = dateoptions.length;
for (var i=0; i<optionsDataLength; i++) {
var choice = dateoptions[i][0];
var left = dateleft[i][0];
if ((choice != '') && (left > 0) == formFieldsArray[h][2]) {
if (formFieldsArray[h]= "9/3") {
datechoice.push(datelist.createChoice(avaibledateoptions,sectionday1timeslots));
}
else {
datechoice.push(datelist.createChoice(avaibledateoptions,sectionday2timeslots));
datelist.setChoices(avaibledateoptions);
}
}
}
}
var day1avaibledateoptions = [];
var optionsday1Length = day1timeoptions.length;
for (var i=0; i<optionsday1Length; i++) {
var day1timechoice = day1timeoptions[i][0];
var day1timeleft = day1left[i][0];
if ((day1timechoice != '') && (day1timeleft > 0)) {
day1avaibledateoptions.push(day1timechoice);
}
}
date1timelist.setChoiceValues(day1avaibledateoptions)
}
//etc for day2 timeslots choice and day3 timeslots
}
}
}
In order to modify your form depending on the changing cell values in your Spreadsheet (caused by new form submissions) you will need to set up an installable onChange trigger that will basically run your function when a change on your Spreadsheet is done (like one coming from a form submission). To create such a trigger, please access your trigger pannel and then click on Create trigger and select as the event type onChange assigning it to the function you will be using to create/delete the form items.
Once a user submits a new form and you do certain calculations on your Spreadsheet to determine how many slots are free for that time slot, you can take the value of the cell that tells you how many free appointments are free for that time and if that number is 0 you can proceed to delete that question element using the method deleteItem().
If you eventually end up resetting the form (because your time slot is free again or someone cancels the meeting), you can undo this by creating back the element.
The following piece of code is a basic example on how to delete and create form items based on the changes of a Spreadsheet cell. It has self explanatory comments:
function onChange() {
// Get the different sheets where you have all your left places in your time slots
var sheet = SpreadsheetApp.getActive().getSheetByName('A');
// Get your form
var form = FormApp.openById('FORMID');
// Here you would get each element that might depend on whether there are any
// appointments left or not
var element = form.getItems()[2];
// Get the cell value that tells you if the time slot is already full (full=0)
var value = sheet.getRange('C2').getValue();
// If the value is 0 it means that this time slot is all completed and nobody
// should be able to select it again
if (value == 0) {
// delete this item
form.deleteItem(element);
// if it is not full yet, it might be because your reset the time slot and therefore
// the element does not exist any more
} else {
// if the element exists dont do anything but if it doesnt and there are available
// apointments create it again
if (!element) {
form.addMultipleChoiceItem().setTitle('B').setChoiceValues(['Cats', 'Dogs']);
}
}
}
If you want to remove a choice option rather than an Item, you can look for the item, get all the choices as an array and then remove the choice you don't want any more from this array. Finally, you can update the item with your updated options with setChoices(). Here is a code example on how to achieve this:
function myFunction() {
// This is an example where I only have a single multiple choice item
var choiceItem = FormApp.getActiveForm().getItems(FormApp.ItemType.MULTIPLE_CHOICE)[0].asMultipleChoiceItem();
// Get current choices array
var choices = choiceItem.getChoices();
// Get choice you want to delete, this would be your times or dates obtained from
// the cell values
var choiceToBeRemoved = "A";
// remove choice from array
choices = choices.filter(function(choice){return choice.getValue() !== choiceToBeRemoved});
// Set updated choices
choiceItem.setChoices(choices);
}
References
setChoices
Javascript filter()
On my page with payment I need two inputs with total payment value:
- one that the client can see
- another one which is hidden.
I wrote a code which pass price of every element to the input when a client check a box with a product they want to pay for, but it works only with the one input.
I was trying to use different options (like getElementsByName and getElementsByClassName) but I am learning JS now and I have no idea how to solve this problem. :(
function select(selector, parent){
return Array.from((parent||document).querySelectorAll(selector));
}
var inputs = select('.sum'),
**totalElement = document.getElementById('payment-total');**
function sumUpdate(){
totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
WHAT I TRIED:
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total, payment-total2')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total).getElementsByName('payment-totalTwo);**
If I'm understanding you right, you want to put the computed value in both the id="payment-total" element and the id="payment-total2" element.
If so, just do what you've already done for payment-total, but for payment-total2 as well, see *** comments:
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total'),
totalElement2 = document.getElementById('payment-total2'); // ***
function sumUpdate(){
//vvvvvvvvvvvvvvvvvvvvvv---- ***
totalElement2.value = totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
I don't immediately see the reason for having both a visible and a hidden input, but if you need that for some reason, that's how you'd do it.
If it got to the point there were three or more elements you wanted to update, I'd probably give them all a class and select them the way you've selected your .sum elements, then compute the total once and assign it to all of them in a loop. But for just two, repeating the lookup and assignment seems fine.
I have a number of checkboxes that are generated from a JavaScript API call from a database. I need to be able to pass the values of the checkboxes which are then selected by the user, and sent to the processing page. The issue is that the checkboxes don't have ID's associated with them(or this wouldn't be a problem) They all have the same name, but no ID's.
What is the best way to find which check boxes are selected, and pass their values to the following page?
One way I started was with an array:
var options = ["option1","option2","option3"];
var option 1 = [0];
var option 2 = [1];
var option 3 = [2];
On the processing page, using:
var option1 = getFromRequest('option1') || '';
var option2 = getFromRequest('option2') || '';
var option3 = getFromRequest('option3') || '';
Is there a better way of doing this?
I've changed the implementation to the following:
var values = []
$("input:checkbox.subIndustry").each(function(){
values.push(this.value);
});
passing the values to the success page with
window.location.href = REGISTER_SUCCESS +'&values='values.join(",")
which should then get the value with
var variablname = getFromRequest('values') || "";
This is returning Undefined. Any help?
An easy way to select them would be something like $("input[type=checkbox]:checked")
However, if you wanted to keep up with them as they are checked, even if they are added after you load, you could create a variable, then asign a delegation to the "change" state of each input that is a checkbox and update this variable on each change.
It's as simple as:
var checked, checkedValues = new Array();
$(function() {
$(document).on("change", "input[type=checkbox]", function(e) {
checked = $("input[type=checkbox]:checked");
// if you wanted to get an array of values of the checked elements
checkedValues = checked.map(function(i) { return $(this).val() }).get();
// make a string of the values as simple as joining an array!
var str = checkedValues.join(); // would return something like: value1,value2,ext...
});
})
Working Example
Since all your checkboxes have the same name, you can retrieve the checked ones using a variation of:
var checked = $('input[name=ckboxname]:checked');
see: :checked selector for more information
you can simply get the values of checked checkboxes by using
$('input[name=checkboxname]:checked').val();
this will give you the value of checkbox which is checked and for all values simply use
each function of jquery.
Turns out, the answer was to utilize indexOf in the underscore.js library. The solution had to be applied in the API being used to send data.
(_.indexOf(values, '9') != -1 ? 1 : '0'),
I have a form on my page that is located in a class .class-lesson. The form itself only contains text field and radio buttons. I do not know how many of each are in the form since it is dynamically generated by PHP. Each new input in the form is named q1, q2, ... qn.
I am trying to get all the values, whether answered or not, and stored into a javascript array. This is my code so far:
// get the value of each input field
var numQuestions = $(".class-lesson label").not(".csubmit").length;
// store each answer
for (var i = 0; i < numQuestions; i++) {
// store our variables
var tempAnswer = undefined;
var tempReference = $(":input[name=q"+(i+1)+"]");
// loop through each item
if ( tempReference.attr('type') == 'radio' ) tempAnswer = $(":input[name=q"+(i+1)+"]:checked").val();
else tempAnswer = tempReference.val();
// output / store the item
alert( tempAnswer );
}
I am sure there has to be an easier way to do this but I don't know. This is why I am asking. If I don't have the :checked then it will just grab the first value of the radio group.
So, how can I make this more efficient?
To get an entire <form> (or any set of inputs) in serialized form, as it would be if submitted to the server normally (without any JavaScript involved), use .serialize(), like this:
var formData = $(".class-lesson :input").serialize();
//or...
var formData = $("#formID").serialize();
If you're submitting via AJAX for example this makes your code incredibly simple, for example:
$.post("test.php", $("#formID").serialize(), function(data) {
alert("Response was: " + data);
});
I have a form that currently only parses the first input variable in the POST.
I have had to add multiple variables, so I would like the function to loop through and grab all the input parameters and add to the POST
Here's the working code for grabbing the first name and value.... How can I get it to check the form and grab all custom name's and variables.
example here
// dynamically add key/value pair to POST body
function read_custom_param(){
var nameEl = document.getElementById("custom_name");
var valueEl = document.getElementById("custom_value");
// save custom param name and value
var cust_param_name = nameEl.value;
var cust_param_value = valueEl.value;
// remove old custom param form elements
if (valueEl.parentNode && valueEl.parentNode.removeChild){
valueEl.parentNode.removeChild(valueEl);
}
if (nameEl.parentNode && nameEl.parentNode.removeChild){
nameEl.parentNode.removeChild(nameEl);
}
// add new custom param form elements
var el=document.createElement("input");
el.type="text";
el.name=cust_param_name;
el.value=cust_param_value;
document.getElementById("dcapiform").appendChild(el);
}
Kind Regards,
Chris
for whatever purpose ur trying to send ambiguous field names to the server, here is what ur looking for (u should consider a smarter way, may br processing on the server side instead)
var elems = document.getElementsByTagName("input");
var arr = [];
for (var i = 0; i<elems.length; i++){
if (elems[i].type != "text") continue;
if (elems[i].name.indexOf("custom_name") < 0) continue;
var index = parseInt(elems[i].name.substring(11)); // you should rename custom_name to custom_name1, and so for custom_value
arr[arr.length] = elems[i].value+"=" + elems["custom_value"+index].value;
}
document.forms[0]["passedITems"] = arr.join(",");
docmentt.forms[0].submit();
on your server side, read "passedItems", and split by ",", you get an array of "name=value", split again on "=" you get a sub array of name, and value