I have multiple selects for a user to chose from. I need to prevent duplicates and alert user of their duplicates. I don't know if i need to use different id's or i could use just one id for all of the selects. I need the duplicate select to alert red.
<form method="post" action="">
<select name="drop1" id="drop1" onchange="checkDropdowns()">
<option value=" " selected="selected"> </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
</select>
<select name="drop2" id="drop2" onchange="checkDropdowns()">
<option value=" " selected="selected"> </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
</select>
<select name="drop3" id="drop3" onchange="checkDropdowns()">
<option value=" " selected="selected"> </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
</select>
<select name="drop4" id="drop4" onchange="checkDropdowns()">
<option value=" " selected="selected"> </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
</select>
here is my Javascript
function checkDropdowns()
{
var iDropdowns = 4;
var sValue;
var sValue2;
for(var i = 1; i <= iDropdowns; ++i)
{
sValue = document.getElementById('drop' + i).value;
for(var j = 1; j <= iDropdowns; ++j)
{
sValue2 = document.getElementById('drop' + j).value;
if ( i != j && sValue == sValue2 )
{
document.getElementById('drop' + j).style.border = "solid 1px red";
return false;
}
}
}
return true;
}
Not sure what i am doing wrong. Any help will be welcome.
Here is my
Fiddle
Ok - plan B, I wrote a lot of rubbish last time. This one uses an array to save used values and checks if the next Select's value is a member of that array. Must simpler..
function checkDropdowns(){
var iDropdowns = 4,
sValue,
used =new Array();
for(var i = 1; i < iDropdowns+1; i++) {
sValue = document.getElementById('drop' + i).value;
if (sValue && used.indexOf(sValue)!==-1) {
document.getElementById('drop' +i).style.backgroundColor="#cc0000";
}
else {
used.push(sValue);
document.getElementById('drop' +i).style.backgroundColor="#fff";
}
}
}
function checkDropdowns(e){
var dup = false;
document.querySelectorAll("select").forEach(function(s){
if (e != s && e.value == s.value){
dup = true;
}
});
e.style.border = dup ? "1px solid #f00" : "inherit";
}
I'd do it this way - you'll need to pass 'this' as a parameter in each of your inline event calls.
Related
So this is the HTML code:
<select id='selUser' style='width: 200px;'>
<option value='0'>Select User</option>
<option value='1'>Yogesh singh</option>
<option value='2'>Sonarika Bhadoria</option>
<option value='3'>Anil Singh</option>
<option value='4'>Vishal Sahu</option>
<option value='5'>Mayank Patidar</option>
<option value='6'>Vijay Mourya</option>
<option value='7'>Rakesh sahu</option>
</select>
What I want to achieve is that, when I click on Value '1', the dropdownlist will display "1" instead of Yogesh Singh. Is it possible to do that?
This will display the value instead of the name when you select an option. I also wrote some code to put the name back if you change it again otherwise the number would just stay there added both examples:
var oldIndex = ''
var oldText = ''
function change(x) {
if (oldIndex != '' && oldText != '') {
x.options[oldIndex].innerHTML = oldText
}
oldIndex = x.value
oldText = x.options[x.selectedIndex].innerHTML
x.options[x.selectedIndex].innerHTML = x.value
}
function change2(x) {
x.options[x.selectedIndex].innerHTML = x.value
}
<select onchange="change(this)" id='selUser' style='width: 200px;'>
<option value='0'>Select User</option>
<option value='1'>Yogesh singh</option>
<option value='2'>Sonarika Bhadoria</option>
<option value='3'>Anil Singh</option>
<option value='4'>Vishal Sahu</option>
<option value='5'>Mayank Patidar</option>
<option value='6'>Vijay Mourya</option>
<option value='7'>Rakesh sahu</option>
</select>
<select onchange="change2(this)" id='selUser2' style='width: 200px;'>
<option value='0'>Select User</option>
<option value='1'>Yogesh singh</option>
<option value='2'>Sonarika Bhadoria</option>
<option value='3'>Anil Singh</option>
<option value='4'>Vishal Sahu</option>
<option value='5'>Mayank Patidar</option>
<option value='6'>Vijay Mourya</option>
<option value='7'>Rakesh sahu</option>
</select>
This script would do it:
document.body.onload = function(){
sel = document.getElementById('selUser');
opts = sel.childNodes;
for(var i in opts){
opts[i].innerHTML = opts[i].value;
}
}
Solution using jQuery:
var last_user_selected_name;
$(document).on('change', '#selUser', function() {
$('#selUser option:not(:selected)').each(function() {
if ($(this).text() === $(this).val()) {
$(this).text(last_user_selected_name);
}
});
var user_seleted = $('#selUser option:selected');
if (user_seleted.val() != 0) {
last_user_selected_name = user_seleted.text();
user_seleted.text(user_seleted.val());
console.log("User selected >> " + last_user_selected_name +
" >> " + user_seleted.val());
}
});
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<select id='selUser' style='width: 200px;'>
<option value='0'>Select User</option>
<option value='1'>Yogesh singh</option>
<option value='2'>Sonarika Bhadoria</option>
<option value='3'>Anil Singh</option>
<option value='4'>Vishal Sahu</option>
<option value='5'>Mayank Patidar</option>
<option value='6'>Vijay Mourya</option>
<option value='7'>Rakesh sahu</option>
</select>
I want to access options on select based on value. I have the array from backend then I converted it to JavaScript array, but I got this error
Uncaught Error: Syntax error, unrecognized expression: #workShop option[value=parentClosedWS[i]]
When I print the ParentCloseWS, it has values like this ["str1", "str2"]
Here is the code:
var parentClosedWS = <?php echo json_encode($parentClosedWS);?>;
var closedWS = <?php echo json_encode($closedWS );?>;
console.log(closedWS);
console.log(parentClosedWS);
for (i = 0; i < parentClosedWS.length; i++) {
console.log(typeof(parentClosedWS[i]));
var parent = String(parentClosedWS[i]);
console.log(parent);
$("#workShop option[value=" + 'parentClosedWS[i]' + "]").prop('disabled', true);
}
This is the HTML:
<select id="workShop" class="floatLabel" name="workshopsel">
<option value="" class="empty"></option>
<option value="Marketing">Marketing </option>
<option value="Sales">Sales</option>
<option value="IT">IT</option>
<option value="Graphic Design">Graphic Design</option>
<option value="HR">HR</option>
<option value="Supply chain">Supply chain</option>
<option value="Media production">Media production</option>
<option value="Development">Development</option>
<option value="TOT">TOT</option>
<option value="Project management">Project management</option>
</select>
Remove the single quotes around parentClosedWS[i];. Those single quotes are converting it to that specific string, rather than giving you the value.
The line should read:
$("#workShop option[value=" + parentClosedWS[i] + "]").prop('disabled', true);
Here is a working example:
var parentClosedWS = ["HR", "IT"];
for (i = 0; i < parentClosedWS.length; i++) {
$("#workShop option[value=" + parentClosedWS[i] + "]").prop('disabled', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="workShop" class="floatLabel" name="workshopsel">
<option value="" class="empty"></option>
<option value="Marketing">Marketing </option>
<option value="Sales">Sales</option>
<option value="IT">IT</option>
<option value="Graphic Design">Graphic Design</option>
<option value="HR">HR</option>
<option value="Supply chain">Supply chain</option>
<option value="Media production">Media production</option>
<option value="Development">Development</option>
<option value="TOT">TOT</option>
<option value="Project management">Project management</option>
</select>
This question already has answers here:
How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?
(16 answers)
Closed 3 years ago.
Is it possible to use JavaScript to open an HTML select to show its option list?
Unfortunately there's a simple answer to this question, and it's "No"
I had this problem...and found a workable solution.
I didn't want the select box to show until the user clicked on some plain HTML. So I overlayed the select element with opacity=.01. Upon clicking, I changed it back to opacity=100. This allowed me to hide the select, and when the user clicked the text the select appeared with the options showing.
I use this... but it requires the user to click on the select box...
Here are the 2 javascript functions
function expand(obj)
{
obj.size = 5;
}
function unexpand(obj)
{
obj.size = 1;
}
then i create the select box
<select id="test" multiple="multiple" name="foo" onFocus="expand(this)" onBlur="unexpand(this)">
<option >option1</option>
<option >option2</option>
<option >option3</option>
<option >option4</option>
<option >option5</option>
</select>
I know this code is a little late, but i hope it helps someone who had the same problem as me.
ps/fyi
i have not tested the code above (i create my select box dynamically), and the code i did write was only tested in FireFox.
This works on Google Chrome
dropDown = function (elementId) {
var dropdown = document.getElementById(elementId);
try {
showDropdown(dropdown);
} catch(e) {
}
return false;
};
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
After trying to solve this issue for some time, I managed to come with a working solution that is also valid:
var event = new MouseEvent('mousedown');
element.dispatchEvent(event);
I've tried to implement this in Jquery as well, using trigger and mousedown or only mousedown but with no success.
This is very late, but I thought it could be useful to someone should they reference this question. I beleive the below JS will do what is asked.
<script>
$(document).ready(function()
{
document.getElementById('select').size=3;
});
</script>
I'm fairly certain the answer is: No. You can select options with JavaScript but not open the select. You'd have to use a custom solution.
The solution I present is safe, simple and compatible with Internet Explorer, FireFox and Chrome.
This approach is new and complete. I not found nothing equal to that solution on the internet. Is simple, cross-browser (Internet Explorer, Chrome and Firefox), preserves the layout, use the select itself and is easy to use.
Note: JQuery is required.
HTML CODE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CustonSelect</title>
<script type="text/javascript" src="./jquery-1.3.2.js"></script>
<script type="text/javascript" src="./CustomSelect.js"></script>
</head>
<div id="testDiv"></div>
<body>
<table>
<tr>
<td>
<select id="Select0" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select1" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select2" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select3" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="Select4" >
<option value="0000">0000</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
<option value="0003">0003</option>
<option value="0004">0004</option>
<option value="0005">0005</option>
<option value="0006">0006</option>
<option value="0007">0007</option>
<option value="0008">0008</option>
<option value="0009">0009</option>
<option value="0010">0010</option>
<option value="0011">0011</option>
<option value="0012">0012</option>
<option value="0013">0013</option>
<option value="0014">0014</option>
<option value="0015">0015</option>
<option value="0016">0016</option>
<option value="0017">0017</option>
<option value="0018">0018</option>
<option value="0019">0019</option>
<option value="0020">0020</option>
<option value="0021">0021</option>
<option value="0022">0022</option>
<option value="0023">0023</option>
<option value="0024">0024</option>
<option value="0025">0025</option>
<option value="0026">0026</option>
<option value="0027">0027</option>
<option value="0028">0028</option>
<option value="0029">0029</option>
<option value="0030">0030</option>
<option value="0031">0031</option>
<option value="0032">0032</option>
<option value="0033">0033</option>
<option value="0034">0034</option>
<option value="0035">0035</option>
<option value="0036">0036</option>
<option value="0037">0037</option>
<option value="0038">0038</option>
<option value="0039">0039</option>
<option value="0040">0040</option>
</select>
</td>
</tr>
</table>
<input type="button" id="Button0" value="MoveLayout!"/>
</body>
</html>
JAVASCRIPT CODE
var customSelectFields = new Array();
// Note: The list of selects to be modified! By Questor
customSelectFields[0] = "Select0";
customSelectFields[1] = "Select1";
customSelectFields[2] = "Select2";
customSelectFields[3] = "Select3";
customSelectFields[4] = "Select4";
$(document).ready(function()
{
//Note: To debug! By Questor
$("#Button0").click(function(event){ AddTestDiv(); });
StartUpCustomSelect(null);
});
//Note: To test! By Questor
function AddTestDiv()
{
$("#testDiv").append("<div style=\"width:100px;height:100px;\"></div>");
}
//Note: Startup selects customization scheme! By Questor
function StartUpCustomSelect(what)
{
for (i = 0; i < customSelectFields.length; i++)
{
$("#" + customSelectFields[i] + "").click(function(event){ UpCustomSelect(this); });
$("#" + customSelectFields[i] + "").wrap("<div id=\"selectDiv_" + customSelectFields[i] + "\" onmouseover=\"BlockCustomSelectAgain();\" status=\"CLOSED\"></div>").parent().after("<div id=\"coverSelectDiv_" + customSelectFields[i] + "\" onclick=\"UpOrDownCustomSelect(this);\" onmouseover=\"BlockCustomSelectAgain();\"></div>");
//Note: Avoid breaking the layout when the CSS is modified from "position" to "absolute" on the select! By Questor
$("#" + customSelectFields[i] + "").parent().css({'width': $("#" + customSelectFields[i] + "")[0].offsetWidth + 'px', 'height': $("#" + customSelectFields[i] + "")[0].offsetHeight + 'px'});
BlockCustomSelect($("#" + customSelectFields[i] + ""));
}
}
//Note: Repositions the div that covers the select using the "onmouseover" event so
//Note: if element on the screen move the div always stand over it (recalculate! By Questor
function BlockCustomSelectAgain(what)
{
for (i = 0; i < customSelectFields.length; i++)
{
if($("#" + customSelectFields[i] + "").parent().attr("status") == "CLOSED")
{
BlockCustomSelect($("#" + customSelectFields[i] + ""));
}
}
}
//Note: Does not allow the select to be clicked or clickable! By Questor
function BlockCustomSelect(what)
{
var coverSelectDiv = $(what).parent().next();
//Note: Ensures the integrity of the div style! By Questor
$(coverSelectDiv).removeAttr('style');
//Note: To resolve compatibility issues! By Questor
var backgroundValue = "";
var filerValue = "";
if(navigator.appName == "Microsoft Internet Explorer")
{
backgroundValue = 'url(fakeimage)';
filerValue = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=\'scale\', src=\'fakeimage\' )';
}
//Note: To debug! By Questor
//'border': '5px #000 solid',
$(coverSelectDiv).css({
'position': 'absolute',
'top': $(what).offset().top + 'px',
'left': $(what).offset().left + 'px',
'width': $(what)[0].offsetWidth + 'px',
'height': $(what)[0].offsetHeight + 'px',
'background': backgroundValue,
'-moz-background-size':'cover',
'-webkit-background-size':'cover',
'background-size':'cover',
'filer': filerValue
});
}
//Note: Allow the select to be clicked or clickable! By Questor
function ReleaseCustomSelect(what)
{
var coverSelectDiv = $(what).parent().next();
$(coverSelectDiv).removeAttr('style');
$(coverSelectDiv).css({'display': 'none'});
}
//Note: Open the select! By Questor
function DownCustomSelect(what)
{
//Note: Avoid breaking the layout. Avoid that select events be overwritten by the others! By Questor
$(what).css({
'position': 'absolute',
'z-index': '100'
});
//Note: Open dropdown! By Questor
$(what).attr("size","10");
ReleaseCustomSelect(what);
//Note: Avoids the side-effect of the select loses focus.! By Questor
$(what).focus();
//Note: Allows you to select elements using the enter key when the select is on focus! By Questor
$(what).keyup(function(e){
if(e.keyCode == 13)
{
UpCustomSelect(what);
}
});
//Note: Closes the select when loses focus! By Questor
$(what).blur(function(e){
UpCustomSelect(what);
});
$(what).parent().attr("status", "OPENED");
}
//Note: Close the select! By Questor
function UpCustomSelect(what)
{
$(what).css("position","static");
//Note: Close dropdown! By Questor
$(what).attr("size","1");
BlockCustomSelect(what);
$(what).parent().attr("status", "CLOSED");
}
//Note: Closes or opens the select depending on the current status! By Questor
function UpOrDownCustomSelect(what)
{
var customizedSelect = $($(what).prev().children()[0]);
if($(what).prev().attr("status") == "CLOSED")
{
DownCustomSelect(customizedSelect);
}
else if($(what).prev().attr("status") == "OPENED")
{
UpCustomSelect(customizedSelect);
}
}
<select id="myDropDown">
<option>html5</option>
<option>javascript</option>
<option>jquery</option>
<option>css</option>
<option>sencha</option>
</select>
By jQuery:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
//close dropdown
myDropDown.attr('size',0);
By javascript:
var myDropDown=document.getElementById("myDropDown");
var length = myDropDown.options.length;
//open dropdown
myDropDown.size = length;
//close dropdown
myDropDown.size = 0;
Copied from:
Open close select
//use jquery
$select.trigger('mousedown')
I am building an online registration form. In the web form, there are six dropdown lists which is as follows :
<select name="hssub1" id="hssub1" onchange="checkUnique(this.id);">
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub2" id="hssub2" onchange="checkUnique(this.id);">
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub3" id="hssub3" onchange="checkUnique(this.id);">
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub4" id="hssub4" onchange="checkUnique(this.id);">
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub5" id="hssub5" onchange="checkUnique(this.id);">
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub6" id="hssub6" onchange="checkUnique(this.id);">
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<div id="notification"></div>
<button type="button" name="submit" id="submit" onclick="return saveNext();">Save and Next</button>
Now I want the users to be able to select options which are mutually exclusive, i.e., the selection set from the six lists should contain unique values. To ensure this I devised the following JavaScript code:
function checkUnique(elementID) {
var elt = document.getElementById(elementID);
var hssubcode = document.getElementById(elementID).value;
var elementIDsuffix = parseInt(elementID.substring(5)) - 1;
// to make it compatible with array index
var othercodes = [
document.getElementById('hssub1').value,
document.getElementById('hssub2').value,
document.getElementById('hssub3').value,
document.getElementById('hssub4').value,
document.getElementById('hssub5').value,
document.getElementById('hssub6').value
];
for(var i=0; i<=5; i++){
if(i != elementIDsuffix){
if(othercodes[i] == hssubcode){
document.getElementById("submit").setAttribute("disabled","disabled");
// so that it stops form submission;
document.getElementById("notification").innerHTML = elt.options[elt.selectedIndex].text + " Subject Already Choosen!";
return false;
break;
} else {
document.getElementById("notification").innerHTML = "";
document.getElementById("submit").removeAttribute("disabled");
// so that it allows form submission again;
}
}
}
}
The above script fails when the user first selects say Bengali, then again Bengali, then again Bengali and finally changes the second choice. I can understand the problem in the code, but being a novice programmer, I am unable to think how to build up the required logic. Please help.
You could use an empty object as a dictionary and count how many occurrences there are for each value. If any value occurrs over 2 times, disable the submit:
function checkUnique(elementID) {
var elt = document.getElementById(elementID);
var valCounter = {};
var othercodes = [
document.getElementById('hssub1').value,
document.getElementById('hssub2').value,
document.getElementById('hssub3').value,
document.getElementById('hssub4').value,
document.getElementById('hssub5').value,
document.getElementById('hssub6').value
];
for(var i=0; i<=5; i++){
var c = valCounter[othercodes[i]] = (valCounter[othercodes[i]] || 0) + 1;
if(c > 1){
document.getElementById("submit").setAttribute("disabled","disabled");
// so that it stops form submission;
document.getElementById("notification").innerHTML = elt.options[elt.selectedIndex].text + " Subject Already Choosen!";
return false;
}
}
document.getElementById("notification").innerHTML = "";
document.getElementById("submit").removeAttribute("disabled");
// so that it allows form submission again;
}
First, I would suggest using a default option like "Select subject" whose value is "null" or 0 - something that can be easily discarded. This way there are no default selected values.
Second, I would highly recommend not putting the event handlers in your markup. It's a real mess to maintain that.
<select name="hssub1" id="hssub1">
<option value=null>Select</option> //added default option
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub2" id="hssub2">
<option value=null>Select</option>
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub3" id="hssub3">
<option value=null>Select</option>
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub4" id="hssub4">
<option value=null>Select</option>
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub5" id="hssub5">
<option value=null>Select</option>
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select name="hssub6" id="hssub6">
<option value=null>Select</option>
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<div id="notification"></div>
<button type="button" name="submit" id="submit">Save and Next</button>
Here's the Javascript -fairly straightforward, but you can ask in case of any questions:
var selects = document.querySelectorAll('select'),
notify = document.getElementById('notification');
function getOthers(current){
var values = [];
for(var i=0;i<selects.length;i++){
if(selects[i].value!='null' && selects[i]!=current)
values.push(selects[i].value);
}
return values;
}
function checkUnique(){
if(this.value && getOthers(this).indexOf(this.value)>-1){
notify.innerText = 'You already selected that';
this.value = null;
}
}
for(var i=0;i<selects.length;i++)
selects[i].onchange = checkUnique;
document.getElementById('submit').onclick = function(){
var values = getOthers(); // will return all selected values this time
if(values.length < 6){
notify.innerText = 'select all six';
return false;
}
notify.innerText = '';
return true;
}
A fiddle: http://jsfiddle.net/p699m9x7/
First add new option to lists with an value you can easily recognize like this:
<select name="hssub1" id="hssub1" onchange="checkUnique(this.id);">
<option value="null">Select</option>
<option value="1">Bengali</option>
then add if condition before the conditions you have now and then the loop will be like this:
for(var i=0; i<=5; i++){
if(i != elementIDsuffix){
if(othercodes[i] === "null"){ //check whether anything is null
document.getElementById("notification").innerHTML = "Select in all lists to continue"; // if null print this
}else if(othercodes[i] == hssubcode){
document.getElementById("submit").setAttribute("disabled","disabled");
document.getElementById("notification").innerHTML = elt.options[elt.selectedIndex].text + " Subject Already Choosen!";
return false;
break;
} else{
document.getElementById("notification").innerHTML = "";
document.getElementById("submit").removeAttribute("disabled");
}
}
}
but with this at first time you enter the page the button will not disable. So for that call this function on body onload event;
<body onload="checkUnique('hssub1');">
I think this will help you to continue with minimal changes to your existing code
There's this JavaScript snippet on github. Just a 1.4 kB js file.
Just include jquery before including the script and you should be good to go.
https://github.com/akhilnaik/unique.js
You need to give a class for all the < select > tags you want to have unique values
Here I'm using class='abc' as example.
<select class='abc' name="hssub1" id="hssub1" onchange="checkUnique(this.id);">
<option value="null">Select One</option>
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
<select class='abc' name="hssub2" id="hssub2" onchange="checkUnique(this.id);">
<option value="null">Select One</option>
<option value="1">Bengali</option>
<option value="2">English</option>
<option value="3">Hindi</option>
<option value="4">Physics</option>
<option value="5">Chemistry</option>
<option value="6">Mathematics</option>
</select>
and so on .....
And call the constructor of Unique on window.onload like this
var k = new Unique('.abc','null');//u need to have a default null value
And thats it everything is taken care of.
The selected values will automatically be disabled.
Dont forget to include JQuery before including unique.js
Hope this helps.
I don't know if this fits your needs, but if you want to get a warning, if any value is already chosen, you could do it like that:
function checkUnique(elementID) {
var values = [];
var elements = document.getElementsByTagName('select');
for (var i=0, l=elements.length; i < l; i++) {
if (document.getElementById(elementID).value === elements[i].value && document.getElementById(elementID) != elements[i]) {
console.log('not unique');
}
}
}
Instead of console.log('not unique') you could do your warnings.
I've got some example code, what I want is when the value in the second select list is set to 0 the first one also resets to 0, at the moment they reset each other when a value is selected in one. Any help appreciated thanks:
HTML:
<select name="Standard" id="std" size="6" onClick="selectCheck(this,'del'); return true;">
<option value="0">Select one</option>
<option value="Eggs" selected>Eggs</option>
<option value="Bacon">Bacon</option>
<option value="Toast">Toast</option>
<option value="Ham">Ham</option>
<option value="Home">Home Fries</option>
<option value="Jelly">Jelly</option>
</select>
<select name="Deluxe" id="del" size="6" onClick="selectCheck(this,'std'); return true;">
<option value="0">Select one</option>
<option value="Omelet">Omelet</option>
<option value="Canadian">Canadian Bacon</option>
<option value="Muffin">Muffin</option>
<option value="Steak">Steak</option>
<option value="Cottage">Cottage Fries</option>
<option value="Preserves">Preserves</option>
</select>
JS:
function selectCheck(me,other) {
var ind = me.selectedIndex;
if (ind > 0) {
document.getElementById(other).selectedIndex = 0;
}
}
Look for the specific ID
if (ind > 0 && other !='del') {
document.getElementById(other).selectedIndex = 0;
}
DEMO
<select name="Standard" id="std" size="6">
<option value="0">Select one</option>
<option value="Eggs" selected>Eggs</option>
<option value="Bacon">Bacon</option>
<option value="Toast">Toast</option>
<option value="Ham">Ham</option>
<option value="Home">Home Fries</option>
<option value="Jelly">Jelly</option> </select>
<select name="Deluxe" id="del" size="6" onClick="selectCheck(this,'std'); return true;">
<option value="0">Select one</option>
<option value="Omelet">Omelet</option>
<option value="Canadian">Canadian Bacon</option>
<option value="Muffin">Muffin</option>
<option value="Steak">Steak</option>
<option value="Cottage">Cottage Fries</option>
<option value="Preserves">Preserves</option>
</select>
<script>
function selectCheck(me,other) { var ind = me.selectedIndex; if (ind<1) { document.getElementById(other).selectedIndex = 0; } }
</script>