Show Div based on multiple drop down selections - javascript

<select name="main">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="1">5</option>
</select>
<select name="sub">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
</select>
I have 2 seperate drop downs as seen here. I want to make it so that if they select main it will show a div for main with a text box equal to they number they select(ie. 4 will show 4 main textboxes for them to fill out) which I know how to do. The problem comes with sub I want them to show a text box equal to the sub for each main select(ie if main is 3 and sub is 3 then each of the 3 main text box will be followed by 3 sub text boxes) I can make it show 3 or all but I can not figure out how to make it go based of the selection of both main and sub to ive me the exact fields I am looking for. Do I just need to set in the function for the java script that if main == x then show xyz on the function for sub?

You can use onchange in the sub select:
<select name="sub" onchange="createSubInput(this)">
function createSubInput (selected) {
let mainSelectedValue = document.getElementById('main').value;
for(let i=0; i< mainSelectedValue; i++) {
for(let j=0; j< selected.value; j++) {
// todo: create sub input by each main input
}
}
}

In order to accomplish this you'll have to:
Use the change event on each select
Take advantage of the value attribute on each option
Demo:
const mainSelect = document.querySelector('select[name="main"]');
const subSelect = document.querySelector('select[name="sub"]');
const resultsDiv = document.getElementById("results");
mainSelect.addEventListener("change", event => {
handleChange(event);
});
subSelect.addEventListener("change", event => {
handleChange(event);
});
function handleChange(event) {
let textboxes = "";
let mainCount = Number(mainSelect.value);
let subCount = Number(subSelect.value);
for (let i = 0; i < mainCount; i++) {
let t = "<input type='text' placeholder='main' /><br/>";
for (let s = 0; s < subCount; s++) {
t += "<input placeholder='sub' style='margin-left: 10px;' /><br/>"
}
textboxes += t;
}
resultsDiv.innerHTML = `<h4>Please fill these out</h4>${textboxes}`;
}
<select name="main">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<br />
<select name="sub">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="results"></div>

Related

prevent options from being selected multiple times

I have a form that contains 5 select elements and each one has the same options as the others, now I want each option to be selected only once so i need the code to achieve the following:
when a user select some option in one of the select elements that option should be deleted or disabled in the other select elements
when the user change his selection the old option should be added again to the other select elements or re-enabled so that the user can select it in another select
I've achieved both of these but my code only works for 2 selects but if i add more selects when the user change the select number 3 or higher the old options will be enabled in lower selects
My code:
<!DOCTYPE html>
<html>
<head>
<script>
function updateDepartments2(event){
var selectNodes = document.getElementsByClassName("choice");
for (node of selectNodes){
if (node !== event.target){
for (child of node){
if (child.index != event.target.selectedIndex || child.index == 0){
var disabledState = ""
}else{
var disabledState = "disabled"
}
node[child.index].disabled = disabledState
}
if (node.selectedIndex == event.target.selectedIndex)
{
node.selectedIndex = 0
}
}
}
}
</script>
</head>
<body>
Person Number 1
<select id="choice1" name="choice1" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="choice2" name="choice2" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="choice3" name="choice3" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script type="text/javascript">
var selectNodes = document.getElementsByClassName("choice");
for (node of selectNodes){
node.onchange=updateDepartments2
}
</script>
</body>
</html>
First add all the selected options from all the checkboxes in an array.
Then traverse every option in other select box and see if value exists.
Here's the updated js function for it.
function updateDepartments2(event) {
var selectNodes = document.getElementsByClassName("choice");
var x = [];
for (node of selectNodes) {
var opt = node.options[node.selectedIndex].value;
x.push(opt);
}
for (node of selectNodes) {
if (node !== event.target) {
for (child of node) {
if (x.includes(String(child.index))) {
var disabledState = "disabled"
} else {
var disabledState = ""
}
node[child.index].disabled = disabledState
}
if (node.selectedIndex == event.target.selectedIndex) {
node.selectedIndex = 0
}
}
}
}
Updated fiddle
https://jsfiddle.net/se1dofzb/1/
Update 2 :
I have reworked your function from scratch and please check for any bugs or clarification needed.
function updateDepartments2(event) {
var selectNodes = document.getElementsByClassName("choice");
var x = [];
for (var node of selectNodes) {
if (node.selectedIndex != 0)
x.push(node.selectedIndex);// Add index of all selected elements
}
for (var node of selectNodes) {
for (var child of node) {
//Traverse all option in every select box
var disabledState;
if (x.includes(child.index)) {
//If it is selected, disable it
disabledState = "disabled"
} else {
disabledState = ""
}
node[child.index].disabled = disabledState
}
}
}
Call the function on change of the select and get the option index. Get all the select elements and disable the selected option in the select elements
function a(e)
{
console.log(e.selectedIndex)
var k=document.querySelectorAll('select')
for(let i=0;i<k.length;i++)
{
if(k[i]!=e)
k[i].options[e.selectedIndex].setAttribute("disabled","disabled")
}
}
function d()
{
var k=document.querySelectorAll('select')
for(let i=0;i<k.length;i++)
{
var c=k[i].querySelectorAll('option');
for(let i=0;i<c.length;i++)
c[i].removeAttribute("disabled")
}
}
<!DOCTYPE html>
<html>
<body>
Person Number 1
<select id="choice1" name="choice1" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="choice2" name="choice2" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="choice3" name="choice3" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<input type="button" onclick="d()" value="Reset">
</body>
</html>

Create inputs N times in JavaScript

I am working on a form that initially asks for an amount of people:
<select name="amount" onClick="update()" id="amount">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
This then triggers the update function when any option is clicked which toggles the visibility of the next part of the form which is contained in a div called step2:
function update(){
document.getElementById('step2').style.visibility='visible';
};
What I then want to do is create N inputs (N being how many people they selected)
So if they select 4 then 4 name inputs appear.
I have tried using this function:
function addinput(){
var wrapper = $("#step2"); //Fields wrapper
var x = document.getElementById(amount).value;
for(var i = 0; i < x; i++) {
$(wrapper).append('<div><input type="name" name="mytext[' + i + ']"/></div>');
}
};
And then placing addinput() at the end of the update function.
However this does not work.
Is there any other way that will, or even, what am I doing wrong in my code?

JavaScript - Check multiple SELECT for duplicate options

This question is based on THIS QUESTION
When an option from one of the SELECT boxes were selected, I wanted the rest to be repopulated, without said option, but instead, is there an easy way to loop through all these select items, to ensure the same option hasn't been selected twice?
Thanks.
Person Number 1
<select name="person1">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Person Number 2
<select name="person2">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Person Number 3
<select name="person3">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Basic Overview:
JavaScript loop to ensure none of the options have been selected twice?
<!DOCTYPE html>
<html>
<head>
<script>
function doAction(el) {
for (var i = 0; i < document.getElementById('person2').length; i++) {
var v = (i != el.selectedIndex ? '' : 'disabled');
document.getElementById('person2')[i].disabled = v;
if (document.getElementById('person2').selectedIndex == el.selectedIndex)
document.getElementById('person2').selectedIndex = 0;
document.getElementById('person3')[i].disabled = v;
if (document.getElementById('person3').selectedIndex == el.selectedIndex)
document.getElementById('person3').selectedIndex = 0;
}
}
</script>
</head>
<body>
Person Number 1
<select id="person1" onchange="doAction(this)" >
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="person2">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="person3">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
</html>
If you use
var x = document.getElementByName('person1').value;
var y = document.getElementByName('person2').value;
var z = document.getElementByName('person3').value;
you can get the values. Then, you have 3 items, to compare against all of them you just have to do 3 checks:
if(x == y || x == z || y == z){
...
}
Or you could throw all of the values into an array, and then splice out the first occurrence, and then check to see if it occurs again.
//get all selects
var selects = document.getElementsByTagName('select');
var setOfPeople = [];
for(i in selects){
setOfPeople[i] = selects[i].name;
}
var selections = [];
//put everything in an array
for(i in setOfPeople){
selections[i] = document.getElementByName(setOfPeople[i]).value;
}
for(i in setOfPeople){
var val = document.getElementByName(setOfPeople[i]).value;
//make sure the element is in the selection array
if(selections.indexOf(val) != -1){
//rip out first occurrence
selections.splice(selections.indexOf(val), 1);
}
//check for another occurrence
if(selections.indexOf(val) != -1){
...
}
}

Multiple identical <select> tags where each option can be selected once

I am creating a website where their are 4 identical dropdown menu's, each dropdown menu has got 10 options. But each of those options can only be selected in one of the dropdown menu's.
So for example:
When I select option 1 in this dropdown menu.
<select name="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">2</option>
<option value="4">4</option>
</select>
I can't select it in this one. So it should say disabled in option one.
<select name="select2">
<option value="1" //disabled >1</option>
<option value="2">2</option>
<option value="3">2</option>
<option value="4">4</option>
</select>
I don't know how to do it myself so I would be very glad if someone could help me.
To provide a better user experience, you should disable the items using JavaScript when the user selects something in a drop down. Are you using jQuery by any chance?
You should also enforce it on the server because as a general rule, clients are not to be trusted.
If I understand you correctly, what you are trying to achieve is better done via checkboxes.
Instead of <select> do this:
<input type="checkbox" name="1" value="1">option1<br>
<input type="checkbox" name="2" value="2">option2 <br> ...
The code below does what you are asking. I also made a jsfiddle
It will correctly disable and enable options as options from ANY of the select inputs are changed.
The javascript
<script type="text/javascript">
// *** EDIT THIS ***
var selectIds = new Array('select1', 'select2', 'select3', 'select4'); // all of the select input id values to apply the only one option value anywhere rule against
function process_selection(theObj){
var allSelectedValues = new Array(); // used to store all currently selected values
// == get all of the currently selected values for all the select inputs
for (var x=0; x<selectIds.length; x++){
var v = document.getElementById(selectIds[x]).value; // the value of the selected option for the select input currently being looked at in the loop (selectIds[x])
// if the selected option value is not an empty string ..
if(v!==""){
// store the value of the selected option and it's associated select input id value
allSelectedValues[v] = selectIds[x];
}
}
// == now work on each option within each select input
for (var x=0; x<selectIds.length; x++){
// loop thru all the options of this select input
var optionObj = document.getElementById(selectIds[x]).getElementsByTagName("option");
for (var i = 0; i < optionObj.length; i++) {
var v = optionObj[i].value; // the value of the current option in the iteration
// only worry about option values that are not an empty string ("")
if(v!==""){
if(allSelectedValues[v]){
if(allSelectedValues[v] && allSelectedValues[v] != selectIds[x]){
// disable this option because it is already selected
// and this select input is NOT the one that it is selected in
optionObj[i].disabled = true;
}
}else{
// enable this option because it is not already selected
// in any of the other select inputs
optionObj[i].disabled = false;
}
}
} // end for (option loop)
} // end for (select loop)
} // end func
</script>
The HTML that works with the above
But really the code above will work with any select inputs on your page by editing the one line indicated in the js code above
<select name="select1" id="select1" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select2" id="select2" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select3" id="select3" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="select4" id="select4" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
As others have mentioned, it is a cleaner way to do it in checkboxes. However, just to improve my JavaScript skills, I came up with something that should answer what you asked for:
var boxes, i, disableOthers;
boxes = document.getElementsByTagName('select');
disableOthers = function () {
'use strict';
var i, j, k, selectedValues = [],
options;
for (i = 0; i < boxes.length; i += 1) {
selectedValues.push(boxes[i].value);
for (j = 0; j < boxes.length; j += 1) {
if (boxes[j] !== boxes[i]) {
options = boxes[j].querySelectorAll('option');
for (k = 0; k < options.length; k += 1) {
options[k].disabled = (selectedValues.indexOf(options[k].value) > -1);
}
}
}
}
};
for (i = 0; i < boxes.length; i += 1) {
boxes[i].addEventListener('change', disableOthers, false);
}
See jsFiddle

select first drop down to be the same value as the other drop down

I would like to select all drop down to be the same as the value selected from the primary dropdown. I got it to work if there is one select selected from the primary dropdown, but will not work if there are two selects, I have added some code below for your information.
HTML:
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select Name</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
JavaScript:
function setDropDown() {
var index_name=document.QualificationForm.ForceSelection.selectedIndex;
document.QualificationForm.Qualifications.selectedIndex=index_name;
}
Try this
function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.getElementsByName('Qualifications');
for (i = 0; i < others.length; i++)
others[i].selectedIndex = index_name;
}
You could possibly use the following, though currently untested:
function setDropDown(el){
if (!el) {
return false;
}
else {
var index = el.selectedIndex,
selects = document.getElementsByName('qualifications');
for (var i=0, len=selects.length; i<len; i++){
selects[i].selectedIndex = index;
}
}
}
This requires that you pass the #ForceSelection select element into the function, and so is called like:
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown(this);">
<!-- other stuff -->
</select>
The selectedIndex of this passed-in element will be applied to the other select elements with the name of qualifications.
Also, please allow me to reiterate: an id must be unique within the document in order to be valid HTML.

Categories

Resources