javascript radio button validation, works in chrome, not in IE - javascript

I have this code to check that one from each group of radio buttons has been selected before the user can submit the form. It works fine in chrome, but in IE it always asks the user to answer all questions, even when they have. How can I change this to work correctly in all browsers?
<script>
function validate(){
if (checkRadio("Radio1") && checkRadio("Radio2") && checkRadio("Radio3")){
return true;
}else{
alert("Please answer all questions!");
return false;
}
}
function checkRadio(name){
var radio = document.forms.myForm[name];
for (var option in radio){
if(radio[option].checked){
return true;
}
}
return false;
}
</script>

The issue is in checkRadio() --- you should not use a fast/enhanced for loop with an array.
Calling for (var option in radio) simply returns the name of the radio button group each time (e.g., "Radio1").
You must use the long form for loop:
http://jsfiddle.net/ugZL9/
function checkRadio(name) {
var radio = document.forms.myForm[name];
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
return true;
}
}
return false;
}

Related

Validation to prevent duplicated values on input text

Im trying to prevent duplicated values on inputs with same name when I click a submit button, but it is not working and i am not sure why...
I need some help to understand why is not working?
Thanks lot in advance!
this is my code:
I tried with a solution I found here which it worked "on input change" behavior, but it doesnt with button click...
My button:
<button type="button" id="approve" class="positive valid" tabindex="-1">Approve</button>
and my jquery
$('#received').on('click',function() {
var $current = $(this);
if ($('input[name^="RE_SignedByID"]').val() == $current.val() && $('input[name^="RE_SignedByID"]').attr('tabindex') !== $current.attr('tabindex') ) {
alert('You can not have duplicated ID´s');
return false;
}else {
return true;
}
});
I want to show an alert and prevent the submit.
Thanks a lot for any help!
The issue is because you're comparing the value of the clicked button to the first input[name^="RE_SignedByID"] element.
To fix this you could instead create an array of all the input[name^="RE_SignedByID"] values using map(). You can then dedupe this list and compare the resulting array lengths. If they are different there was a duplicate. Try this:
$('#received').on('click', function(e) {
var values = $('input[name^="RE_SignedByID"]').map(function() {
return this.value.trim();
}).get();
var unique = [...new Set(values)];
if (values.length != unique.length) {
e.preventDefault();
alert('You can not have duplicated ID\'s');
}
});
Note that [...new Set(values)] will not work in IE. If you need to support legacy browsers there are plenty of alternatives to dedupe an array. See this answer for more information.
I could fix it! Here is the code... you can add a button event like:
$('#submit').on('click', function () {
var values = $('[name=RE_SignedByID]').map(function() {
return this.value.trim();
}).get();
var values2= $('[name=RE_OwnersID]').map(function() {
return this.value.trim();
}).get();
values.sort();
values2.sort();
for (var i = 0; i < values.length-1; i++) {
if( values[i] == values[i+1] && values[i] !=""){
showAlert(translator.getTranslation(' You can not have duplicated signers ID\'s'));
return false;
// break;
}
}
for (var i = 0; i < values2.length-1; i++) {
if( values2[i] == values2[i+1] && values2[i] !=""){
showAlert(translator.getTranslation(' You can not have duplicated owners ID\'s'));
return false;
// break;
}
}
});

java script function not working in windows

function bookingchanneldisable(stopSale){
if (stopSale == "N") {
document.getElementById("applicableBookingChannel").readOnly = false;
document.getElementById("applicableBookingChannelReservation").readOnly = false;
}else{
document.getElementById("applicableBookingChannel").checked = true ;
document.getElementById("applicableBookingChannelReservation").checked = false ;
document.getElementById("applicableBookingChannel").readOnly = true;
document.getElementById("applicableBookingChannelReservation").readOnly = true;
}
}
this function working fine in firefox (ubuntu) , but it is not working in firefox (windows). please can you help me
readonly prevents users from changing the field value. So it works with inputs in which you can change the value (like text boxes), but it doesn't work on inputs in which you do not change the value but the field state (like checkboxes).
To solve the problem, you should use disabled with checkboxes instead. Like this:
function bookingchanneldisable(stopSale){
if (stopSale == "N") {
document.getElementById("applicableBookingChannel").disabled = false;
document.getElementById("applicableBookingChannelReservation").disabled = false;
}else{
document.getElementById("applicableBookingChannel").checked = true ;
document.getElementById("applicableBookingChannelReservation").checked = false ;
document.getElementById("applicableBookingChannel").disabled = true;
document.getElementById("applicableBookingChannelReservation").disabled = true;
}
}
See it working on this JSFiddle: http://jsfiddle.net/fg1xLr1h/

Issue with Radio button checked in JavaScript

I am working on a JSP page which is having multiple radio buttons with ids ans1, ans2, ans3... etc.. No of radio buttons varies depending upon on the response in previous page. User should select answer for all the radio buttons. i.e. user must select response for all the radio buttons ans1, ans2, ans3 ... etc. I have written a Javascript code for submit button click event as below for validation and to make sure user has responded to all the answers:
function beforeSubmit(){
var obj = document.quizcreen;
var qCount = obj.totQuesHidden.value;
for (var i=1; i<=qCount; i++){
if(document.getElementById("ans"+i).checked){
// checked
}else{
alert("Please select ateleast one option"); // unchecked
return false;
}
}
obj.submit();
return true;
}
For some reason above code is not working. The form should not be submitted if all the radio buttons are not selected. Please help, I know it's very simple and common issue, but I am unable to figure it out. Thanks in advance.
Also following is the form action:
<form name="quizcreen" id="quizcreen" method="post" action="QuizResult.jsp" onsubmit = "return beforeSubmit();">
You have a return true statement in your loop. So when the first radiobutton is checked, it will not check the other ones.
function beforeSubmit(){
var obj = document.quizcreen;
var qCount = obj.totQuesHidden.value;
var allChecked = true;
for (var i=1; i<=qCount; i++){
if(! document.getElementById("ans"+i).checked){
allChecked = false;
}
}
if(! allChecked){
alert("Please select ateleast one option"); // unchecked
return false
}
obj.submit();
return true;
}
Ok I found out a better way to handle my scenario, So I am sharing my code for your info:
function beforeSubmit() {
var obj = document.quizcreen;
var allChecked = true;
$("input:radio").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
allChecked = false;
}
});
if (!allChecked) {
alert("Please answer all the questions."); // unchecked
return false;
}
obj.submit();
return true;
}
your problem is at least one to be checked.
do this stuff
function isRadioChecked() {
return ($('input[type=radio]:checked').size() > 0);
}

Verify that an Option has been Selected in a Drop Down Box

On
http://www.greekforme.com/999-apron-01.html, there are several Drop Down boxes.
The script called 'verifyselection' is supposed to show a pop-up box if the user does not change the drop down from 'Select an Option Below'
function verifyselection(form)
{
// result function
var blnResult = true;
// temp name form control
var nameControl = "";
// array of name of radio form controls
var arrNameControl = new Array();
// array of value checked of radio form controls
var arrValueControl = new Array();
// flag existence form control in array
var isExistOnArray = false;
// loop on all elements of form
for(i=0; i<form.elements.length; i++) {
// check type form control
if(form.elements[i].type=="radio") {
// save name form control
nameControl = form.elements[i].name;
// reset flag existence form control in array
isExistOnArray = false;
// loop on all found radio form control
for(j=0; j<arrNameControl.length; j++){
// if giving form control is exist in array
if(arrNameControl[j] == nameControl) {
// set flag
isExistOnArray = true;
// break loop
break;
}
}
// if giving form control is not exist in array
if(isExistOnArray == false){
// set index of array
j = arrNameControl.length;
// add new element to arrays
arrNameControl[j] = nameControl;
arrValueControl[j] = 0;
}
// if giving radio form control is checked
if(form.elements[i].checked == "1"){
arrValueControl[j] = 1;
}
}
if ((form.elements[i].selectedIndex > -1)) {
if (form.elements[i].selectedIndex == 0) {
var opttext = form.elements[i].value.toLowerCase();
if (opttext.indexOf('optional') < 0) {
blnResult = false;
alert('Please select one of the options from the list');
break;
}
}
}
}
// loop on all found radio form control
if(blnResult==true) {
for(j=0; j<arrNameControl.length; j++){
// if radio group form control is checked
if(arrValueControl[j] != 1) {
// set result function
blnResult = false;
// show error message
alert('Please select one of the options from the list');
break;
}
}
}
// return result function
return blnResult;
}
Currently, I can get the Pop-Up box to show when you click the Add to Cart button -
But... it still adds the items to cart.
I want the script to prevent the item from being added to cart if the user does not change the drop downs from 'Select an Option Below'
Where are you calling this function from? If it's in an onsubmit handler, the handler should return false. So, you should have this in your code somewhere:
form.onsubmit = function() {
return verifyselection(this);
}
Or, in html:
<form onsubmit="return verifyselection(this);" ...>
The important thing here being the return part. When the handler returns false, the default action won't be taken. In this case, the form won't submit.

Is there a way to check a form before submitting it to see if ANY of the checkboxes have been checked?

Is there a way to check a form before submitting it to see if ANY of the checkboxes have been checked in Javascript?
Something like...
function checkboxcheck(){
/*something in here to check name="brands[]" checkbox array?*/
}
Basically I just want it to alert me if 0 checkboxes were selected. 1 or more is required.
I would call this function on submit.
Thanks much!!
You could do something like this:
function anyCheckboxesChecked() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type === "checkbox" && inputs[i].checked)
return true;
}
return false;
}
Then you could call that function from your "submit" handler"
if (!anyCheckboxesChecked()) {
alert("Please check one of the appealing checkboxes on the page");
return false;
}
If your page is more complicated than what this implies (like, if there are multiple forms), then you'd find the appropriate form first and call .getElementsByTagName() from that point instead of from document.
How about:
function checkboxcheck(name) {
var els = document.getElementsByName(name);
for (var i = 0; i < els.length; i++) {
if (els[i].checked) {
return true;
}
}
return false;
}
using getElementsByName().
Usage:
var valid = checkboxcheck("brands[]");
Here's an example: http://jsfiddle.net/andrewwhitaker/2saJp/1/

Categories

Resources