Call a recursive function with different variables - javascript

I am new to javascript. I am doing a feedback form where there are 12 radio buttons that need to get validated individually and a textarea will be displayed when I click a particular value.
Here, when I click that button, my textarea, which is in display, should be mandatory entered (eg: when I click fail option in a results question, then I should mention in which subject he failed through that textarea. something like that).
For this, I have written code, it's working fine with the 1st radio button, but unable to call this recursively for remaining buttons.
I need to call this code in a function recursively, but my variables need to get change everytime. Like for 2nd time, I should use option2,text2, likewise in next call option3,text3, etc.
var option = $("#form1 input[#name=radio1]:checked").val();
var text = document.getElementById("text1").value;
if (!$("#form1 input[#name=radio1]:checked").val()) {
alert("Please fill all the fields");
return false;
errs++;
} else if (option == "3" && trim(text) == "") {
alert("Please enter comments.");
return false;
}
This piece of code needs to be called for var option1 to option10 and same text1 to text10. Like:
var option2 = $("#form1 input[#name=radio2]:checked").val();
var text2 = document.getElementById("text2").value;
This should get called immediately of completion of first radio button.
Please help me out.

"Recursive" is the wrong word here. You just want to loop over all the elements.
Get all the radios, and loop over them. Then get the ID, and all the fields associated with that id.
I'm assuming you're using jQuery, so here's an example:
// Note: The "#" is not needed in jQuery
var radios = $("#form1 input[name^='radio']"); // "^=" means "starts with"
radios.each(function(){
var id = this.name.replace('radio', ''); // this will get the number, eg: 1
var option = $(this).val(); // get radio's value
var text = $('#text'+id).val(); // get textX's value
if(!$(this).is(':checked')){ // check if radio is checked
alert("Please fill all the fields");
errs++; // make sure to do this before "return false"
return false; // break the .each loop
}
else if (option == "3" && trim(text) == "") {
alert("Please enter comments.");
return false;
}
});

Related

Can not validate properly the radio button using JavaScript/jQuery

I cannot check the radio button select in my validation using JavaScript/jQuery. I am generating some multiple textarea, radio button and drop down list dynamically. My requirement is I will fill all field and check the validation. But it's not happening properly.
Here is my code:
function validate(){
var x =document.getElementById('ques').value;
console.log('value',x);
for(var i=0;i<x;i++){
var tid="questions"+ i;
var rid='answer_type'+i;
var sid="nscale"+i;
var scaleid='#scaleid'+i;
if(document.getElementById("questions"+ i)){
if(document.getElementById(tid).value==''){
alert('Please enter the question');
return false;
}else if($('input[id=answer_type' + i + ']').is(':checked')==false){
alert('Please check the answer type');
return false;
}else if($(scaleid).css('display') == 'block'){
if(document.getElementById(sid).value==''){
alert('Please select the scale');
return false;
}
}else{
}
}
}
}
My complete code is here plunkr. My problem is when user has selected all radio button and also click on validate button still its displaying the alert message as Please check the answer type. My requirement is I will check all field and drop down list whether these are blank or not in validation case.
Try and make the id of radio button in the addQuestionField() function as id="answer_type'+i+'" instead of id="answer_type0".

Highlight empty select box after alert

I have a site using input:text, select and select multiple elements that generate a text output on button click.
Having searched SO, I found examples of validation code that will alert the user when a select field returns an empty value-
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
$(this).addClass("highlight");
}
At the end, I tried to add a condition after the alert is dismissed, such that the offending select box will be highlighted by adding the 'highlight' class - but this doesn't do anything. My .highlight css is {border: 1px red solid;}
Any help here?
UPDATED WITH ANSWER - Thanks #Adam Rackis
This code works perfectly. I added a line to remove any added '.highlight' class for selects that did not cause an error after fixing
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
$('select').removeClass("highlight");//added this to clear formatting when fixed after alert
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
You were close. In your loop, this does not refer to each select that you're checking.
Also, you're returning false prior to the highlight class being added. You'll probably want to keep track of whether any select's are invalid, and return false at the very end after you're done with all validation.
Finally, consider moving your alert to the very bottom, so your user won't see multiple alerts.
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}
}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
Also, since you're already using jQuery, why not take advantage of its features a bit more:
$('select').each(function(i, sel){
if (sel.value === '') {
$(el).addClass("highlight");
anyInvalid = true;
}
});
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}

jquery check values in form

I have two inputs where I am checking to make sure that they are not empty before the form submits.
My issue is that it only validates #from_date. Is the issue that .val will only check the last id in the list?
$('#submitDates').click(function () {
// Get the fields you want to validate
var name = $("#to_date, #from_date");
// Check if field is empty or not
if (name.val()=='') {
alert ('Please Select Dates')
return false;
} ;
});
});
Any specific reason you're hooking on .click and not .submit?
You can iterate through the selected elements and check for a violating element using .each
var found = false;
$("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && $(name).val()=='') {
alert ('Please Select Dates')
found = true;
} ;
});
return !found;
In your example var name = $("#to_date, #from_date"); is giving you a collection of two inputs and by doing if (name.val()=='') jQuery is checking only the first element in the collection, so it's not working. You may try this
$('#submitDates').click(function () {
var name = $("#to_date, #from_date");
if ( name[0].value == '' || name[1].value == '' ) {
alert ('Please Select Dates');
return false;
}
});
In the above example name[0].value refers to the first element and name[1].value refers to the second element. If you want to use jQuery's val() method then you can use it like $(name[0]).val() and $(name[1]).val().
Also you should consider to use submit event of the form instead of button's click event.

How to test if users has made any changes to a form if they haven't saved it

Basically the same functionality as stackoverflow when posting a question, if you start writing a post then try to reload the page. You get a javascript alert box warning message.
I understand how to check if the form has been changed, although how do I do the next step.
I.E: How to I check this when leaving the page, on here you get "This page is asking you to confirm that you want to leave - data you have entered may not be saved."?
EDIT: found correct answer here to another question https://stackoverflow.com/a/2366024/560287
I'm very sure that if you search, 'jQuery detect form change plugin', you will find something much more usable than this semi-pseudo code i'm about to write:
formChanged = function(form) {
form.find('input[type="text"], textarea').each(function(elem) {
if (elem.defaultValue != elem.value) {
return true;
}
});
// repeat for checkbox/radio: .defaultChecked
// repeat for ddl/listbox: .defaultSelected
return false;
}
usage:
if (formChanged($('form')) { // do something }
Note that this is to detect changes against the original rendered value. For instance, if a textbox has a value = "x", and the user changes it to "y", then changes it back to "x"; this will detect it as NO change.
If you do not care about this scenario, you can just do this:
window.formChanged = false;
$(':input').change(function() {
window.formChanged = true;
});
Then you can just check that value.
Yes, it is JavaScript as HTML is just a markup language.
Yes, jQuery can be used for this. It's preferable over vanilla JavaScript as it makes things easier, although it does add some overhead.
There are a number of ways to check if any of a form's controls have changed.
To check for changes from the default, most can be checked against the defaultValue property. For radio buttons, you should always have one checked by default, so check if it's still selected or not. Similarly for selects, set the selected attribute for the default option and see if it's still selected, and so on.
Alternatively, if all your form controls have an ID or unique name, you can collect all their values onload and then check their values when the form is submitted.
Another method is to listen for change events on each form control, but that is a bit over the top.
Here's a POJS version that takes the same approach as rkw's answer:
/*
Check if any control in a form has changed from its default value.
Checks against the default value for inputs and textareas,
defaultChecked for radio buttons and checkboxes, and
default selected for select (option) elements.
*/
function formChanged(form) {
var control, controls = form.elements;
var tagName, type;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
tagName = control.tagName.toLowerCase();
type = control.type;
// textarea
if (tagName == 'textarea') {
if (control.value != control.defaultValue) {
return true;
}
// input
} else if (tagName == 'input') {
// text
if (type == 'text') {
if (control.value != control.defaultValue) {
return true;
}
// radio and checkbox
} else if (type == 'radio' || type == 'checkbox') {
if (control.checked != control.defaultChecked) {
return true;
}
}
// select multiple and single
} else if (tagName == 'select') {
var option, options = control.options;
for (var j=0, jLen=options.length; j<jLen; j++) {
option = options[j];
if (option.selected != option.defaultSelected) {
return true;
}
}
}
}
// Not really needed, but some like the return value to
// be a consistent Type
return false;
}
Note that you need to be careful with select elements. For a single select, you should always set one option to selected, as if there is no default selected, some browsers will make the first option selected and others wont.

trouble with confirmationboxes when submitting a form

I'm trying to compare some values of select fields.
When submitting my form I want to check whether the values are equal.
Well ... I've got two problems here.
The values aren't compared the first time I submit the form.
Example: I select option3 for id='idx' and id='idy'. In my case option3 is equal to option3. When I submit the form there should be a confirm box because the values are equal. No confirmationbox appears. I call the site again with the set values and submit the form; the confirmationbox appears. I chose option 1 for id='idx'. This would mean that the values of id='idx' and id='idy' are not equal. But now the box appears again.
What I want is that when I submit the form the values should be compared. In case they're equal a confirmationbox appears.
2.Somehow my code only checks for one condition. But it is possible that the two cases in my code can be true. How would I solve it?
This is my code:
var x = $('#idx option:selected').val();
var y = $('#idy option:selected').val();
var z = $('#idz option:selected').val();
$('#myform').submit(function() {
if (x === y ) {
if (confirm('text') == true){
return true;
} else {
return false;
}
}
if (x === z ) {
if (confirm('text') == true){
return true;
} else {
return false;
}
}
});
If there are any questions, please ask.
Thank you for your help.
First, you should put your $('...').val() lines inside the submit function, or else they will get the value of the select boxes when the page loads.
Second, once you return true or false, it will exit out of that submit function, so you should return false when it fails, or else continue until the end of your conditionals, then have one return true at the end.

Categories