Dependent and Dynamic Dropdown form in js - javascript

Hey so I am trying to to make both a dynamic and dependent dropdown form. Essentially I want the second form to be dependent of the first forms option, and when you add a new form field I want it to generate a new div form with a different ID and and the option in the first form removed from the second and then third form. In the case the user only selects on form and doesn't decide to add a second or a third, I would like to still submit a NULL value through the form's that aren't submitted. Js is not my strong suit so any help would be appreciated
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="nativelangdrop">
<option value="1">Fashion Designer</option>
<option value="2">Visual Artist</option>
<option value="3">Clothing reseller</option>
<option value="4">Musician</option>
<option value="5">Videographer</option>
<option value="6">Photographer</option>
<option value="7">Dancer</option>
<option value="8">Sculpter</option>
</select>
<span id="additional"></span>
<input id="addBtn" type="button" value=" + "/>
<hr />
<select id="genre">
<option value="1">Fashion Designer</option>
<option value="2">Visual Artist</option>
<option value="3">Clothing reseller</option>
<option value="4">Musician</option>
<option value="5">Videographer</option>
<option value="6">Photographer</option>
<option value="7">Dancer</option>
<option value="8">Sculpter</option>
</select>
<span id="additional2"></span>
<script>
var total;
// To auto limit based on the number of options
// total = $("#nativelangdrop").find("option").length - 1;
// Hard code a limit
total = 2;
//if total two hide plus button
$("#addBtn").on("click", function() {
var button = document.getElementById('addBtn');
var ctr = $("#additional").find(".extra").length;
var ctr2 = $("#additional2").find(".extra2").length;
if (ctr < total) {
var $ddl = $("#nativelangdrop").clone();
var $ddl2 = $("#genre").clone();
$ddl.attr("id", "ddl" + ctr);
// $ddl2.attr("id", "ddl2" + ctr);
$ddl.addClass("extra");
$ddl2.addClass("extra2");
$("#additional").append($ddl);
$("#additional2").append($ddl2);
}
else{
button.style.display = 'none';
}
});
//implement dependent genre form.
/*implement creating form after each iteration of ctr, var MyIDvariable = "MyID123";
var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
... the rest of your code ... */
</script>
</body>
</html>```

Related

Comparing answer key array with input answers

This is my first day using HTML/Javascript. I've done some Java a while ago. I'm trying to make a quiz that will get answers from a drop down list and compare them to the answer key. I've tried so many things I can't even remember them all. Any help would be appreciated. Specifically, I cant figure out how to compare each element in the two arrays. I'm sure there is a lot more wrong than just the arrays. I;ve googled answers for 4 hours and got nothinggggg. Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.<p>
<br>
<br>
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width = 300 height = 200>
<br>
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br>
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br>
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br>
<br>
<button onclick="myFunc()">Click me</button>
<script>
var q1 = document.getElementById("Q1");
var valueQ1=q1.options[q1.selectedIndex].value
var q2 = document.getElementById("Q2");
var valueQ2=q2.options[q2.selectedIndex].value
var q3 = document.getElementById("Q3");
var valueQ3=q3.options[q3.selectedIndex].value
var array ans = [1,2,3]
var array inpans = [valueQ1,valueQ2,valueQ3]
var counter = 0;
var count = 0;
function myFunc(){
while (count<ans.length){
if(ans[count]==inpans[count])
{
counter ++;
count ++;
}else {
counter = counter;
count ++,
}
}
document.getElementById("one").innerHTML = "You got " + counter + " right.";
}
</script>
<p id="one"></p>
</body>
</html>
You have a number of issues which need fixing:
Your HTML is invalid. Your're not closing your <p> tag on line 11:
<p>Please match the letter to the corresponding answer.</p> <!-- <-- close this -->
You have many syntax errors in your code. Whenever your code isn't working, the first thing you should look for is syntax errors. Syntax errors can be identified by your brower's console. The first syntax errors are on lines 58 and 59. There should only be one variable name (identifier) after the var keyword:
var ans = [1, 2, 3]; // <-- used to be: var array ans
var inpans = [valueQ1, valueQ2, valueQ3]; // used to be: array inpans
Another syntax error occurs on line 70. Here you're using a comma instead of a semi-colon. Again, the console could of helped you identify this error yourself:
count++; // used to be: count++,
Your next issue is a logical issue. The following code runs when the page loads:
var q1 = document.getElementById("Q1");
var valueQ1 = q1.options[q1.selectedIndex].value
var q2 = document.getElementById("Q2");
var valueQ2 = q2.options[q2.selectedIndex].value
var q3 = document.getElementById("Q3");
var valueQ3 = q3.options[q3.selectedIndex].value
...as it runs when the page initially loads, the values of valueQ1 etc. will all be the initial value of the dropdowns when the page initially loads. These values don't change when you change the selected value in the dropdowns. If you wanted that behaviour you'd need an event listener. However, an easy way to fix this is to set the values of valueQ1 through to valueQ3 inside your function. This way, your code will grab the values from the dropdowns when you click your button, which should be after the user has manually selected a value from the dropdowns themselves:
var q1 = document.getElementById("Q1");
var q2 = document.getElementById("Q2");
var q3 = document.getElementById("Q3");
...
function myFunc() {
// get value of dropdown elements
var valueQ1 = q1.value; // you can just grab the dropdown's value, no need for `q1.options[q1.selectedIndex].value`
var valueQ2 = q2.value;
var valueQ3 = q3.value;
var inpans = [valueQ1, valueQ2, valueQ3];
while (count < ans.length) {
...
Fixing all these will allow your code to check against answers. Currently, as your count variable is defined outside of the myFunc, your button will only run your while loop once (as the second time it runs count >= ans.length, making your while loop condition false - thus not running the code within it). If you want users to have multiple attempts at a given question you define count inside your function so that it gets reset when the button is clicked.
As a side note, if you're planning on using this code in production keep in mind that users will be able to see the answers to the questions by inspecting your website's source.
See altered code below:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.</p>
<br>
<br>
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width=300 height=200>
<br>
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br>
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br>
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br>
<br>
<button onclick="myFunc()">Click me</button>
<script>
// Get dropdown elements when page loads
var q1 = document.getElementById("Q1");
var q2 = document.getElementById("Q2");
var q3 = document.getElementById("Q3");
var ans = [1, 2, 3]
var counter = 0;
var count = 0;
function myFunc() {
// get value of dropdown elements
var valueQ1 = q1.value;
var valueQ2 = q2.value;
var valueQ3 = q3.value;
var inpans = [valueQ1, valueQ2, valueQ3];
while (count < ans.length) {
if (ans[count] == inpans[count]) {
counter++;
count++;
} else {
counter = counter;
count++;
}
}
document.getElementById("one").innerHTML = "You got " + counter + " right.";
}
</script>
<p id="one"></p>
</body>
</html>
For what it's worth, here's how I would write the equivalent code. It takes advantage of the class you have on each dropdown, and then iterating over all dropdowns to check whether they equal the correct answer. If you want the user to have multiple attempts at the question you can remove the {once: true} option:
// Get dropdown elements when page loads
const dropdowns = document.querySelectorAll('.Q');
const submitBtn = document.querySelector("#guess-btn");
const resultElem = document.getElementById("one");
const ans = [1, 2, 3];
submitBtn.addEventListener("click", () => {
const correctCount = [...dropdowns].reduce(
(total, dropdown, i) => total + (+dropdown.value === ans[i]), 0
);
resultElem.innerText = `You got ${correctCount} right.`;
}, {once: true});
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.</p>
<br />
<br />
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width="300" height="200" />
<br />
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br />
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br />
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br />
<br />
<button id="guess-btn">Click me</button>
<p id="one"></p>

How to display multiple dropdown value on another html fields using jquery

I have few dropdown with text fields.
I want to get all those values and display on a button.
The only condition is that button should be generate upto 5 time.
means -> if all the value of dropdown & text field are displaying on a button field so i want to generate another button and again i want to display my value on that by clicking on generate button.
Here is my code for reference.
$('#left_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#left_period_guider").html('(period,offset)');
}else if ($(this).val()=='ema') {
$("#left_period_guider").html('(close,period,offset)');
}
});
$('#right_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#right_period_guider").html('(period,offset)');
}else if ($(this).val()=='ema') {
$("#right_period_guider").html('(close,period,offset)');
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<select name="left_indicator" id="left_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator">
<option>select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
This button should generate by clicking above the button with the all field provided values.
example : sma(10.2) < ema(3.2)
<button type="button" id="generated1" name="generated1" value="">value will display here</button>
<button type="button" id="removethis" name="removethis">removethis</button>
</div>
</body>
</html>
As you can see here,
I'm just expecting the solution like all the dropdown and text field value should display on a button and generate the button so i can do the same strategies on another button upto 5 time.
so value should display on each generated button like. sma(10.2) < ema(3.2).
The following code would do the Job !
To perform better validation, I added a class name 'chk' to check all input fields.
This would be used to validate and generate the buttons' data.
Notice that I also added an empty value property to your select boxes, that's required for this code.
var data='';
var btnid=0;
function generateBtn(data){
btnid++;
var btns='<button type="button" id="generated'+btnid+'" name="generated'+btnid+'" value="" data-id="'+btnid+'">'+data+'</button><button type="button" id="removethis" class="removethis" data-id="'+btnid+'">removethis</button>';
$('#container').append(btns);
}
function check_inputs() {
var i=0;
//validation to check for empty inputs
//Same loop used to generate valid Button' Data
data='';
//we reset Data
$('.chk').each(function(){
if( $(this).val() === "" ){
$(this).css({'border-color':'red','border-size':'3px'});
} else{
$(this).css({'border-color':'green','border-size':'3px'});
if($(this).is('input')){
data+='('+$(this).val()+')';
} else {
data+=' '+$(this).val();
}
i++;
}
});
if(i==$('.chk').length){
//We gernerate the button
generateBtn(data);
} else{
return;
}
}
//Dynamically generated buttons are non-Dom, so we base selction on the parent container
//Data-id attribute is used to match targeted buttons
$("#container").on('click','.removethis', function() {
$('button[data-id='+$(this).data('id')+']').remove();
});
$("#generateButton").on('click', function() {
//Because we can remove buttons
//We count generated buttons before generating more than 5
if($("[id^=generated]").length<5){
check_inputs();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<select name="left_indicator" id="left_indicator" class="chk">
<option value="">select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)" class="chk">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator" class="chk">
<option value="">select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator" class="chk">
<option value="">select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)" class="chk">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
</div>
I commented the code, but I suggest you revise your HTML code for the small (Non standard) mistakes. Just to pay attention to What's unique and what's not! I don't know if this is meant to be in <form> or not, repeating name property in buttons for example should be taken care of.
From your question, I'm not sure where to put the buttons, so I assumed to place it at the end of the document. To make it even simple I added a div at the end before the closing of the body.
<div id="displayButtons" style="display:block;">
Then you can add the following code in the script tag to achieve what you are looking for.
var buttonCount = 0;
$('#generateButton').click(function () {
if (buttonCount < 5) {
// Get all values
let left_indicator = $("#left_indicator").val();
let left_PeriodAndOffset = $("#left_PeriodAndOffset").val();
let comparator = $("#comparator").val();
let right_indicator = $("#right_indicator").val();
let right_PeriodAndOffset = $("#right_PeriodAndOffset").val();
// Define Button to display
let buttonText = left_indicator + " (" + left_PeriodAndOffset + ") " + comparator + " " + right_indicator + " (" + right_PeriodAndOffset + ")";
let button = '<button id="' + buttonCount + '">' + buttonText + '</button>';
// Display button inside Div
$("#displayButtons").append(button);
buttonCount++;
} else {
alert("Limit of 5 reached");
}
})
$("#removethis").click(function () {
if (buttonCount > 0) {
$("#displayButtons > button:last-child").remove();
buttonCount--;
}
else {
alert("No more buttons to remove.");
}
})
Another additional thing I would like to mention is ;
$('#left_indicator').on('change', function (event) {
event.preventDefault();
/* Act on the event */
if ($(this).val() == 'sma') {
$("#left_period_guider").text('(period,offset)'); <== I think you need to replace html with text to display what you require..
} else if ($(this).val() == 'ema') {
$("#left_period_guider").text('(close,period,offset)');
}
});
I hope that's what you were looking for...
Complete working Code:
var buttonCount = 0;
$('#generateButton').click(function () {
if (buttonCount < 5) {
// Get all values
let left_indicator = $("#left_indicator").val();
let left_PeriodAndOffset = $("#left_PeriodAndOffset").val();
let comparator = $("#comparator").val();
let right_indicator = $("#right_indicator").val();
let right_PeriodAndOffset = $("#right_PeriodAndOffset").val();
// Define Button to display
let buttonText = left_indicator + " (" + left_PeriodAndOffset + ") " + comparator + " " + right_indicator + " (" + right_PeriodAndOffset + ")";
let button = '<button id="' + buttonCount + '">' + buttonText + '</button>';
// Display button inside Div
$("#displayButtons").append(button);
buttonCount++;
} else {
alert("Limit of 5 reached");
}
})
$("#removethis").click(function () {
if (buttonCount > 0) {
$("#displayButtons > button:last-child").remove();
buttonCount--;
}
else {
alert("No more buttons to remove.");
}
})
$('#left_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#left_period_guider").text('(period,offset)');
}else if ($(this).val()=='ema') {
$("#left_period_guider").text('(close,period,offset)');
}
});
$('#right_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#right_period_guider").text('(period,offset)');
}else if ($(this).val()=='ema') {
$("#right_period_guider").text('(close,period,offset)');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="left_indicator" id="left_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator">
<option>select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
This button should generate by clicking above the button with the all field provided values.
example : sma(10.2) < ema(3.2)
<button type="button" id="generated1" name="generated1" value="">value will display here</button>
<button type="button" id="removethis" name="removethis">removethis</button>
</div>
<div id="displayButtons" style="display:block;">

Local Storage With JavaScript

I want to store a string locally so when the user reloads the page it saves what was last there.
I looked at this and tried to implement it.
I had this code which basicllay has a button and a dropdown list of colors to change the background.
When I close and reopen the doc I want it to be the color that I saved.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<form>
<script language="JavaScript">
<!--
function inputForm(){
var color = document.getElementById("color");
var outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
//-->
</script>
</body>
</html>
I made this code to do that but it didn't work
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="storeColor()">
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<input type="button" onClick="storeColor()" value="save color"/>
<script>
var outputContents;
function inputForm(){
var color = document.getElementById("color");
outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
function storeColor(){
// Store
localStorage.color = outputContents;
// Retrieve
document.body.style.backgroundColor = outputContents;
}
</script>
<form>
</body>
</html>
Local storage in JavaScript is uses (key, value) pairs of strings so if you wanted to save the value This is my test value. you would need to give it a key that you can get it from later, for example myTestValue.
So in code this would be
// set the value in window.localStorage
window.localStorage.setItem('myTestValue', 'This is my test value.')
// get the value from window.localStorage
window.localStorage.getItem('myTestValue')
Here is some more information: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
You code is almost complete. You only need to apply background color on window load. I added one more function applyColor:
function applyColor(color) {
color = color || localStorage.color;
document.body.style.backgroundColor = color;
// Select corresponding option in selectbox
var select = document.getElementById("color");
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value == color) {
select.options[i].selected = true;
return;
}
}
}
applyColor();
Also note that when page is loaded we should also select the option from selectbox corresponding to currently saved color.
Demo: http://jsfiddle.net/sd2Cx/

Can not select sub options when there are more than one rows in a table

I have a table, which has 2 columns. First column is maindrop down list of options and second column is a corresponding sub dropdown list of options for the main drop down.
Everything works fine for single row, but as soon as I have multiple rows, nothing is selected from subdrop down menu.
Below is the simple html and JavaScript to reproduce this problem. If you uncomment the second row, you will see the problem. Hope someone can help me in this.
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script language="JavaScript">
function SubCat(cn, scn, scnm)
{
this.CatNum = cn;
this.SubcatNum = scn;
this.SubcatName = scnm;
}
var subcatInfo = new Array(
new SubCat('26', '1', 'MainOpt1_SubOpt1'),
new SubCat('26', '2', 'MainOpt1_SubOpt2'),
new SubCat('27', '3', 'MainOpt2_SubOpt1'),
new SubCat('27', '4', 'MainOpt2_SubOpt2')
);
function doCategory(sel) {
var ix;
var subcat = sel.form.repairSubcategoryCode;
// regardless of what else we do, we wipe out all the
// options in the subcategory dropdown by
// going backwards, removing selected options
for (ix = subcat.options.length - 1; ix >= 0; --ix) {
subcat.options[ix] = null;
}
// now, did the user select a category?
if (sel.selectedIndex == 0) {
// no...so give user the "no subcats" msg
subcat.options[0] = new Option("-- no subcategories yet --", "0");
return; // and we are done
}
// yes, so get the appropriate subcategories:
subcat.options[0] = new Option("-- choose a subcategory below --", "0");
// what category number was selected?
var catnum = sel.options[sel.selectedIndex].value;
var cursc = 0;
for (ix = 0; ix < subcatInfo.length; ++ix) {
// looking for all subcat's with the requested category number
var subcatObj = subcatInfo[ix];
if (subcatObj.CatNum == catnum) {
subcat.options[++cursc] = new Option(subcatObj.SubcatName,
subcatObj.SubcatNum);
}
}
}
</script language="JavaScript">
<form name="priceOpinionForm" method="post" action="/brokerPriceOpinion.do">
<table id="repirImprTab">
<tr>
<td>
<select name="repairTypeCode" onchange="doCategory(this)">
<option value="-1">Select Repair Type</option>
<option value="26">MainOpt1</option>
<option value="27">MainOpt2</option>
</select>
</td>
<td>
<select name="repairSubcategoryCode" >
<OPTION Value="-1">-- now subcategories yet --</option>
</select>
</td>
</tr>
<!--
<tr>
<td>
<select name="repairTypeCode" onchange="doCategory(this)">
<option value="-1">Select Repair Type</option>
<option value="25">Septic Maintenance</option>
<option value="26">Bathroom Items</option>
<option value="27">Cabinets & Shelves</option>
<option value="28">Counter Tops</option>
</select>
</td>
<td>
<select name="repairSubcategoryCode">
<OPTION Value="-1">-- now subcategories yet --</option>
</select>
</td>
</tr>
-->
</table>
</form>
</body>
</html>
Every named field in an HTML form may only have one value at a time. In your case, there would be multiple selects named "repairTypeCode" and "repairSubcategoryCode", which leads to all fields with the same name being set to the same value if any one of them is changed.
Fix: Append an numerical index to the names (e.g. "repairTypeCode1", "repairTypeCode2", ...) or convert them into array (e.g. "repairTypeCode[]").
AS Kurrija mentioned, you cannot have two elements named the same.
Here is a jsfiddle with an added variable for the doCategory method which allows the code to decide which sub category dropdown to populate. I've changed the name attribute to id as well to provide better readability.

Syncing 2 multiple choice lists in javascript

I'm trying to figure out how to sync two multiple choice lists in javascript. Here's the code which works:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<script language="JavaScript">
<!--
function SelectEmail(name)
{
var listboxEmails = document.getElementById('emails');
for (var i=0;i<listboxEmails.length;i++)
{
listboxname = listboxEmails[i].innerHTML
if (listboxname == name)
{
listboxEmails.selectedIndex = i;
break;
}
}//end for
}//end function SelectEmail
// -->
</script>
<body>
<select id='names' name ='names' style = "width: 100" multiple="multiple" onClick="SelectEmail(this.value);">
<option value ="joe">joe</option>
<option value ="albert">albert</option>
<option value ="gary">gary</option>
<option value ="ace">ace</option>
</select>
<select id="emails" name ="emails" style = "width: 100;" multiple="multiple">
<option value ="joe#asds.com">joe</option>
<option value ="albert#asds.com">albert</option>
<option value ="gary#asds.com">gary</option>
<option value ="ace#asds.com">ace</option>
</SELECT>
</body>
</html>
However I want to make it show multiple choices. So for example if I choose albert and gary on the left list, I want the right list to select albert and gary as well. Please help me with this. Cheers.
Your function SelectEmail() can't work because it sets selectedIndex of your select, which selects one option and deselects the rest. Also, you are using the text content of the options in #emails in order to map them with the values of #names. That's not a good practice, because text nodes are supposed to show text and not to enable the identification of elements in your script.
Instead, you can access the selected attribute separately for each option you want to select. By adding an additional attribute to your #emails element's options, it could look like:
<select id="emails" name="emails" style="width: 100;" multiple="multiple">
<option value="joe#asds.com" data-name="joe">joe</option>
<option value="albert#asds.com" data-name="albert">albert</option>
<option value="gary#asds.com" data-name="gary">gary</option>
<option value="ace#asds.com" data-name="ace">ace</option>
</select>
You can now use the data-name attribute to map the options, for example in the following way:
function selectEmail() {
// deselect all
$('#emails option').removeAttr('selected');
var names = $('#names').val();
if (names == null) {
// none selected
return;
}
$.each(names, function (i, name) {
var selector = 'option[data-name="' + name + '"]';
$('#emails ' + selector).attr('selected', true);
});
}
Here's a working fiddle (you will notice that I also used the onchange event instead of onclick:
http://jsfiddle.net/H9hNH/2/

Categories

Resources