Multiple select validation - javascript

I have a form in HTML, that has several select elements, what is the best way to make validation for them in such way that no two select elements can have same value, validation function should fire on select, so it can check are there any selects with the same option value if yes then alert something, can I get a explanation how to write this in javascript?
Thank you
here is a bit of HTML code I want to validate :
<form name="forma" action="" method="POST">
<select name="sel1">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
<select name="sel2">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
<select name="sel3">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
</form>
Here is the solution slightly adjusted but this is it:
var selectTest = function () {
var i, j;
sels = [document.getElementById("sel1"), document.getElementById("sel2"), document.getElementById("sel3")];
for (i = 0; i < sels.length; i += 1) {
for (j = i + 1; j < sels.length; j += 1) {
if(sels[i].value != "Please select")
{
if (sels[i].value === sels[j].value) {
alert("Selected values must be different");
return;
}
}
}
}
};
Special tnx to austin cheney, thanks to everyone who posted and participated.

First, don't use the name attribute as a reference point for script. Name refers to an array of named elements in the DOM, which is typically useless in the global DOM outside of form controls. When using the name array it is difficult to tell child nodes apart from child nodes of a same named element. Use the id attribute for use with script, which is a unique identifier instead.
var selTest = function () {
var i, j, error = document.getElementById("error"),
sels = [document.getElementById("sel1"), document.getElementById("sel2"), sel3 = document.getElementById("sel3")];
for (i = 0; i < sels.length; i += 1) {
for (j = i + 1; j < sels.length; j += 1) {
if (sels[i].value === sels[j].value) {
error.display = "block";
sels[i].backgroundColor = "#f00";
sels[j].backgroundColor = "#f00";
return false;
}
}
}
};
EDIT: changed return; to return false; for use with an onsubmit event.
Simply add the id attribute value of the select lists to the "sels" array in the code above. The above code will make a hidden element with an id of "error" appear if the test results in a true condition. It will also change the background color of the offended select lists to red.

I would generally recommend using jQuery for this as it simplifies it quite a bit. You'd want to do something along these lines.
function hasDuplicates() {
var dupe = false;
$("select option:selected").each(function(i) {
var id = $(this).parent().attr("id");
var value = $(this).attr("value");
$("select option:selected").each(function(c) {
if ($(this).parent().attr("id") != id && $(this).attr("value") == value) {
alert("Duplicate");
dupe = true;
return false;
}
});
if (dupe) {
return false;
}
});
return dupe;
}
This will cycle through all the select boxes on the page and compare each one to every other one. If there's a duplicate value it will popup an alert and return true.
For it to fire when a change to a select box is made you'd want to add onchange events to each as shown below. Each select will need a unique id to be set, although you could change the calls to attr("id") to attr("name") if you don't want to add ID's.
<select onchange="hasDuplicates()">...
Performance wise it may make sense to store the values in an array, as this solution hits the DOM quite a lot by having a nested loop.

Give onchange="validate('1')" onchange="validate('2')" onchange="validate('3')" for each selecte statement.
function validate(x){
if(x==1)
{
var selectedvalue=document.forma.sel1.options[document.forma.sel1.selectedIndex].value
if(selectedvalue==document.forma.sel2.options[document.forma.sel2.selectedIndex].value ||
selectedvalue==document.forma.sel3.options[document.forma.sel3.selectedIndex].value)
alert("No two values cannot be same");
}
esle if(x==2)
{
var selectedvalue=document.forma.sel2.options[document.forma.sel2.selectedIndex].value
if(selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value ||
selectedvalue==document.forma.sel3.options[document.forma.sel3.selectedIndex].value)
alert("No two values cannot be same");
}
else if(x==3)
{
var selectedvalue=document.forma.sel3.options[document.forma.sel3.selectedIndex].value
if(selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value ||
selectedvalue==document.forma.sel1.options[document.forma.sel1.selectedIndex].value)
alert("No two values cannot be same");
}
}

Related

Using Javascript to select a value from a Html Select box

Hey guys I am using JavaScript to select a specific value(option) from the html select form tag, but whenever I call my JavaScript function I get a single message repeating for all the choices I want to select.
Ex: If I choose to select 'Rabbit' from the list of options and then display a message saying 'Rabbit chosen'; the message will display for each option/value selected.
Here is my JavaScript Code:
var element = document.getElementById('choices').value;
function SelectElement() {
if (element = 'Rabbit') {
alert("Rabbit Selected");
}
else if (element = 'Wall') {
alert("Wall Selected");
}
else if (element = 'Arrow') {
alert("Arrow Selected");
}
}
Here is my html code:
<form>
<select id="choices" >
<option>Rabbit</option>
<option>Wall</option>
<option>Arrow</option>
</select>
<input type="button" value="Submit" onclick="SelectElement()"/>
</form>
Can you smart guys please help me????
A. You should fetch the value each time before calling the function and then check it otherwise your element variable won't refresh at all.
B. To compare two values you should use ==, = is an assignment operator.
function SelectElement() {
var element = document.getElementById('choices').value;
if (element == 'Rabbit') {
alert("Rabbit Selected");
}
}
(As your question is not much clear) if you just want to alert the selected value for every option clicked, just do:
function SelectElement() {
var element = document.getElementById('choices').value;
alert(element+" Selected");
}
This is basic string concatenation.
There is a something called selected == true or false in a "select" tag.
You could write in HTML :
<form>
<select id="choices">
<option id="Rabbit">Rabbit</option>
<option id="Wall">Wall</option>
<option id="Arrow">Arrow</option>
</select>
</form>
<button onclick="TakeElement()">Click</button>
You could write in javascript:
var ra = document.getElementById('Rabbit');
var wa = document.getElementById('Wall');
var ar = document.getElementById('Arrow');
function TakeElement() {
if (ra.selected == true) {
alert("Rabbit is selected");
}
if (wa.selected == true) {
alert("Wall is selected");
}
if (ar.selected == true) {
alert("Arrow is selected");
}
}
I think you must replace element ='rabbit' with element =='rabbit'
== is comparison operator
and = is assignment operator

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

Logic for multiple and single select/combo boxes

Below is my code:
<%#taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%#taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<script type="text/javascript">
var flag = false;
function test(selObject)
{
alert("hi");
var form = document.forms[0];
alert("form"+form);
var txtS = form["city"];
alert("txt"+txtS);
var len = txtS.length;
alert("len"+len);
for(var i=0; i<len; i++)
{
if (selObject == txtS[i] )
{
if(txtS[i].value==txtS[i].options[3].value)
{
alert("YOU ARE SELECTING MYSORE CITY");
flag = true;
}
if(!txtS[i].options[3].selected && flag)
{
var result = confirm("Are you sure you wnat to travel to this city");
if(result)
{
flag = false;
}
else
{
txtS[i].options[txtS[i].options.selectedIndex].selected=false;
txtS[i].options[4].selected=true;
}
}
}
}//end of for loop
}
</script>
<html:form action="/login">
username:<input type="text" name="username" /></br>
password:<input type="password" name="password"/></br>
<%
for(int i = 0; i < 10; i++){
%>
<html:select property="city" onchange="javascript:test(this);">
<html:option value="B">BANGALORE</html:option>
<html:option value="C">CHENNAI</html:option>
<html:option value="M">MANGALORE</html:option>
<html:option value="MR">MYSORE</html:option>
</html:select></br>
<%
}
%>
<input type="submit" value="submit"/>
</html:form>
When select-box or combo-box is looped for ten times then I am getting form["city"] length as 10 properly and behaviour of alerts within combox-box is appropriate, but if I have a single-select-box, then instead of giving form["city"] length as 1 it gives it as 4 which is the number of option elements in my dropdown-box.
So my logic doesn't work here.
How do I make it work for both single as well as multiple combo/select boxes.
Any help would be appreciated.
Please use a javascript library like jQuery for cross-browser compatibility.
You can use the following code to determine that only a single select element is present or multiple select elements with the same name are present:
if (selObject == txtS) {
alert("Single select");
// ... your logic for a single combo-box follows after this
} else {
// your logic for multiple combo-box follows, like the "for" loop and if-else
}
When there is only one select box the line var txtS = form["city"]; will return an array of option elements within that select box and when more than one select box with the same name it returns an array of the select boxes.
Hope this helps.
Not related to your question, but this logic if(!txtS[i].options[3].selected && flag) will always return false.

Cannot properly get the value of a dropdown

I have a dropdown list and a javascript function which disables other fields when a certain value from the dropdown list is selected.
Javascript Code
function maritalStatusChange()
{
var dropdown = document.getElementById("maritalstatus").value;
if(dropdown == 'Single')
{
document.getElementById("spousefld").disabled = true;
document.getElementById("spouse_occupation").disabled = true;
document.getElementById("address3").disabled = true;
document.getElementById("children_no").disabled = true;
document.getElementById("spousefld").value = "";
document.getElementById("spouse_occupation").value = "";
document.getElementById("address3").value = "";
document.getElementById("children_no").value= "None";
}
if(dropdown == 'Married')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
document.getElementById("maritalstatus").value= 'Married';
}
if(dropdown == 'Separated')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
}
if(dropdown == 'Widowed')
{
document.getElementById("spousefld").disabled = false;
document.getElementById("spouse_occupation").disabled= false;
document.getElementById("address3").disabled = false;
document.getElementById("children_no").disabled = false;
}
}
Here is the HTML code of the dropdown list and where I call the javascript function.
<select name="maritalstatus" id="maritalstatus" onchange="maritalStatusChange();">
<option>---------------</option>
<option value='Single'>Single</option>
<option value='Married'>Married</option>
<option value='Separated'>Separated</option>
<option value='Widowed'>Widowed</option>
</select><font color="red">*</font>
Right now, the only thing that works is when I select the "Single" option however, it does not seem to get proper selected value for the rest of the options. Can anyone tell me what I did wrong?
Thanks!
Try This:
var dropdown = document.getElementById("maritalstatus").options[document.getElementById("maritalstatus").selectedIndex].value;
You should try "selectedIndex":
document.getElementById("maritalstatus").selectedIndex;
The above code works fine. You can see it at: http://jsfiddle.net/WmHCs/
What is the actual error? Maybe some other part of the code?
Try Below code
var eve = document.getElementById("maritalstatus");
var data = eve.options[eve.selectedIndex].value;
You are using single quotas in HTML. Switch them to double quotas. All values for options are assigned with those single quotas. This is what you are actually comparing: ("'Single'"=="Single") => false.
EDIT
If this code is supposed to add the selection in your db, check if-blocks other than Single. In case Single you set some values, but other blocks are making some disablings only.
You just need to get value from element by id and then alert the value.
Create a function and call it on change. it works in many of values dynamically generated, no limitaion of entries in dropdown.
<select name="maritalstatus" id="maritalstatus" onchange="maritalStatusChange();">
function maritalStatusChange()
{
var getValue = document.getElementById("maritalstatus").value;
alert(getValue);
}

Simple JavaScript check not working?

I have this validate form function:
function ValidateForm() {
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
for (var i=0;i<chks.length;i++){
if (chks[i].checked){
hasChecked = true;
break;
}
}
if (!hasChecked){
alert("Please select at least one friend.");
chks[0].focus();
return false;
}
}
html for this is:
<input type="checkbox" name="sendto[]" value="2" >
I know this is not full code. Full code is huge. But basically if i have only one checkbox in the code the above code gives a message undefined on ValidateForm(). Which is called when form is submitted and and above checkbox is checked.
But if i have two checkboxes in the code like this:
<input type="checkbox" name="sendto[]" value="2" >
<input type="checkbox" name="sendto[]" value="4" >
On submit when ValidateForm() function is called this works correctly. Am i doing something wrong that it is not working for 1 checkbox even if it is checked?
The statement
var chks = document.register.elements['sendto[]'];
gets the element (element*s*, if there are more then one) with namesendto[]
If there is only one element with name sendto[] then you have the reference of that element in chks.
If there are more than one element with name sendto[], then chks holds the reference to the array of those elements.
When you do this:
for (var i=0;i<chks.length;i++){
You try to loop based on chks.length. If chks is an array (see above: when there are multiple elements by name sendto[]), then chks.length will hold the number of elements in the array.
If there is only one sendto[] element, then chks will hold that element and since the element (<input type="checkbox" name="sendto[]" value="2" >) does not have a property called length, the browser says length is indefined
So you have o differentiate between two scenarios, when there is only one sendto[] checkbox and when there are more than one.:
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
//Check whether there is one checkbox or whether there are more
if(chks.length)
{
for (var i=0;i<chks.length;i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
}
else
{
if(chks.checked)
{
haschecked = true;
}
}
PS:
code gives a message undefined on ValidateForm() does not convey much. Even for you it is not clear what this means right (That's why you have asked this question). Try to give more details. Any modern browser will give more details on the undefined, the what is undefined which line etc. Even pre-historic browsers will tell you the line number where the undefined error was thrown. With those details you can try to find the line and try to see what is happening. You most likely will find out. If you don't, post it to the community here with all these details.
<script language="javascript">
function validate() {
var chks = document.getElementsByName('sendto[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++) {
if (chks[i].checked) {
hasChecked = true;
break;
}
}
if (hasChecked == false) {
alert("Please select at least one friend.");
return false;
}
return true;
}
</script>
Here is how I would do it.
if(!validate()){
alert("Please select at least one.");
return false;
}
function validate(){
var els=document.getElementsByName('sendto[]');
for(var i=0;i<els.length;i++){
if(els[i].checked){
return true;
}
}
return false;
}
You could use validate as an anonymous function.

Categories

Resources