I am using the following select form and function to select the transport type first and I would like to have a list of cars or motorcycles in the second form depending on my choice at the first stage. I will really appreciate if you can let me know why my function is not working and what I am missing
<!doctype html>
<html>
<body>
<select id="transport" name="transport">
<option value="choose">Please choose a type</option>
<option value="cars">Cars</option>
<option value="motorcycles">Motorcycles</option>
</select>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="submit" />
</body>
<script>
(function(){
var type = document.getElementById('transport');
var model = document.getElementById('model');
var cars = {
Alfa_Romeo: '4 C Spider',
Aston_Martin: 'V12 Vantage',
Audi: 'A4 Allroad',
Ford: 'Focus'
};
var motorcycles = {
Yamaha: 'YZF-R6',
Kawasaki: 'Versys 650 LT',
Suzuki: 'Boulevard C50',
Honda: 'Super Cub C100'
};
addEvent(type, 'change', function() {
if (this.value === 'choose'){
model.innerHTML = '<option>Please choose a type first</option>';
return;
}
var models = getModels(this.value);
var options = '<option>Please choose a model</option>';
for (var key in models){
options += '<option value="' + key + '">' + models[key] + '</option>';
}
model.innerHTML = options;
});
function getModels(transport) {
if (transport === 'cars') {
return cars;
} else if (transport === 'motorcycles'){
return motorcycles;
}
}
}());
</script>
`
Use addEventListener. Check this working snippet
(function(){
var type = document.getElementById('transport');
var model = document.getElementById('model');
var cars = {
Alfa_Romeo: '4 C Spider',
Aston_Martin: 'V12 Vantage',
Audi: 'A4 Allroad',
Ford: 'Focus'
};
var motorcycles = {
Yamaha: 'YZF-R6',
Kawasaki: 'Versys 650 LT',
Suzuki: 'Boulevard C50',
Honda: 'Super Cub C100'
};
type.addEventListener('change', function() {
if (this.value === 'choose'){
model.innerHTML = '<option>Please choose a type first</option>';
return;
}
var models = getModels(this.value);
var options = '<option>Please choose a model</option>';
for (var key in models){
options += '<option value="' + key + '">' + models[key] + '</option>';
}
model.innerHTML = options;
});
function getModels(transport) {
if (transport === 'cars')
{
return cars;
}
else if (transport === 'motorcycles'){
return motorcycles;
}
}
}());
<select id="transport" name="transport">
<option value="choose">Please choose a type</option>
<option value="cars">Cars</option>
<option value="motorcycles">Motorcycles</option>
</select>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="submit" />
Related
I'm working with multiple select, and i want to remove the attribute disabled button if all select has value, however the "technician" has sub item which is required and other phase don't have sub.
I wan't to remove disable attribute if all select(NO SUB) has value, and select(with sub) has value.
Here's my code:
const type = document.getElementById("empType");
const phase = document.getElementById("phase");
const subPhase = document.getElementById("subPhase");
type.addEventListener("change", appendPhase);
function appendPhase(){
$("#phase").empty();
var option = '';
if(type.value == 1){
option += '<option value="0">SELECT</option><option value="1">Trainee</option><option value="2">Acting</option><option value="3">Competency</option>'
}
if(type.value == 2){
option += '<option value="0">SELECT</option><option value="1">Phase 1</option><option value="2">Phase 2</option>'
}
if(type.value == 0){
$(subPhase).attr("hidden", true);
option += '<option value="0">SELECT</option>'
}
$(phase).append(option);
$(subPhase).attr("hidden", true);
}
phase.addEventListener("change", showIfTech);
function showIfTech() {
if(type.value == 2){
$(subPhase).attr("hidden", false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="empType">
<option value="0">SELECT</option>
<option value="1">LINE LEADER</option>
<option value="2">TECHNICIAN</option>
</select>
<select id="phase">
<option value="0">SELECT</option>
</select>
<select id="subPhase" hidden>
<option value="0">SELECT</option>
<option value="1">COMMON</option>
<option value="2">ELECTRICAL</option>
<option value="3">MECHANICAL</option>
</select>
<br>
<br>
<button disabled>CHECK ME</button>
First, you need to add id attribute to button to use it later.
Second, use event listner change (using event delegation) to listen all select boxes change where it is not hidden with selector select:not([hidden]). And then test that all select boxes are selected where value is not 0.
Here is the code.
const type = document.getElementById("empType");
const phase = document.getElementById("phase");
const subPhase = document.getElementById("subPhase");
type.addEventListener("change", appendPhase);
function appendPhase() {
$("#phase").empty();
var option = '';
if (type.value == 1) {
option += '<option value="0">SELECT</option><option value="1">Trainee</option><option value="2">Acting</option><option value="3">Competency</option>'
}
if (type.value == 2) {
option += '<option value="0">SELECT</option><option value="1">Phase 1</option><option value="2">Phase 2</option>'
}
if (type.value == 0) {
$(subPhase).attr("hidden", true);
option += '<option value="0">SELECT</option>'
}
$(phase).append(option);
$(subPhase).attr("hidden", true);
}
phase.addEventListener("change", showIfTech);
function showIfTech() {
if (type.value == 2) {
$(subPhase).attr("hidden", false);
}
}
document.addEventListener('change', isAllSelected);
function isAllSelected() {
let allSelected = [];
const allSelectBoxes = document.querySelectorAll('select:not([hidden])');
allSelectBoxes.forEach((item) => {
if (item.value != '0') {
allSelected.push(item.value);
}
});
const checkMeButton = document.getElementById('check-me-button');
if (allSelected.length === allSelectBoxes.length) {
checkMeButton.disabled = false;
} else {
checkMeButton.disabled = true;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="empType">
<option value="0">SELECT</option>
<option value="1">LINE LEADER</option>
<option value="2">TECHNICIAN</option>
</select>
<select id="phase">
<option value="0">SELECT</option>
</select>
<select id="subPhase" hidden>
<option value="0">SELECT</option>
<option value="1">COMMON</option>
<option value="2">ELECTRICAL</option>
<option value="3">MECHANICAL</option>
</select>
<br>
<br>
<button id="check-me-button" disabled>CHECK ME</button>
could somebody tell me how to pass values from form to 2d associative array? I made simple associative array and it was easy to write it, but now I have problem with 2d array and getSalary() function. getWorkload() works fine, but getSalary() doesn't work. I would be grateful for some tip or code modification.
var salaries = [
[
"mrWh", ["intern", 2511],
["contractual", 2592],
["designated", 2932],
["certificated", 3411]
],
[
"mrbchWht", ["intern", 2121],
["contractual", 2200],
["designated", 2522],
["certificated", 3000]
],
[
"bchWht", ["intern", 1868],
["contractual", 1910],
["designated", 2200],
["certificated", 2600]
]
];
var worklooad = [];
worklooad["20"] = 20;
worklooad["25"] = 25;
worklooad["30"] = 30;
worklooad["35"] = 35;
function getSalary() {
var slr = 0;
var formData = document.forms["data"];
var selEdLvl = formData.elements["edLvl"];
var selDegree = formData.elements["degrees"];
slr = salaries[selEdLvl][selDegree.value];
return slr;
}
function getWorkload() {
var psm = 0;
var formularz = document.forms["data"];
var selPsm = formularz.elements["workload"];
psm = worklooad[selPsm.value];
return psm;
}
function chkEtat(pStr) {
var spl44 = document.getElementById("spl44");
if (!isNaN(pStr) && pStr !== "" && pStr <= getWorkload()) {
spl44.style.fontSize = "22px";
pStr = pStr / getWorkload();
spl44.innerHTML = pStr.toFixed(2) + "<br>";
return pStr;
} else if (isNaN(pStr)) {
spl44.style.fontSize = "18px";
spl44.innerHTML = "Enter number." + "<br>";
return 0;
} else if (pStr > getWorkload()) {
var spl44 = document.getElementById("spl44");
spl44.innerHTML = "inappropriate value." + "<br>";
return 0;
} else {
document.getElementById("spl44").innerHTML = "";
}
}
function calcpTime() {
var str = document.getElementById("inppn");
var vStr = document.getElementById("inppn").value;
var rpvStr = vStr.replace(/,/g, '.');
rpvStr = parseFloat(rpvStr);
var cmp = /^\d{1,2}$/.test(vStr);
if (cmp === true) {
var nStr = vStr.concat(".0");
document.getElementById("inppn").value = nStr;
var fnStr = parseFloat(nStr);
return chkEtat(fnStr);
}
return chkEtat(rpvStr);
}
function calcSalaries() {
calcpTime();
document.getElementById("spl55").innerHTML = getSalary() * calcpTime();
}
function clearInps() {
document.getElementById("data").reset();
}
<form id="data">
<div>
<label>Education level: </label>
<select id="edLvl">
<option value="" selected disabled hidden>Select</option>
<option value="mrWh">Master with pedagogical preparation</option>
<option value="mrbchWht">Master without pedagogical preparation</option>
<option value="mrbchWht">Bachelor with pedagogical preparation</option>
<option value="bchWht">Bachelor without pedagogical preparation</option>
</select>
</div>
<div>
<label>Ascension degree: </label>
<select id="degrees">
<option value="" selected disabled hidden>Select</option>
<option value="intern">intern</option>
<option value="contractual">contractual</option>
<option value="designated">designated</option>
<option value="certificated">certificated</option>
</select>
</div>
<div>
<label>Workload: </label>
<select id="workload">
<option value="" selected disabled hidden>Select</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
</select>
</div>
<div>
<label>Workload: </label>
<input onchange="calcSalaries()" type=text id="inppn">
<span id="spl44"></span>
</div>
<div>
<label>Salary: </label>
<span id="spl55"></span>
</div>
<button id="clear" onclick="clearInps()">Clear data</button>
</form>
Use .find to identify particular elements in an array:
var salaries = [
[
"mrWh", ["intern", 2511],
["contractual", 2592],
["designated", 2932],
["certificated", 3411]
],
[
"mrbchWht", ["intern", 2121],
["contractual", 2200],
["designated", 2522],
["certificated", 3000]
],
[
"bchWht", ["intern", 1868],
["contractual", 1910],
["designated", 2200],
["certificated", 2600]
]
];
document.querySelector('#data').addEventListener('submit', e => e.preventDefault());
function getSalary() {
const edLvlVal = document.querySelector('#edLvl').value;
const degreeVal = document.querySelector('#degrees').value;
const salary = salaries
.find(([level]) => level === edLvlVal)
.find(([degree]) => degree === degreeVal);
console.log('salary ' + salary);
}
<form id="data">
<div>
<label>Education level: </label>
<select id="edLvl">
<option value="" selected disabled hidden>Select</option>
<option value="mrWh">Master with pedagogical preparation</option>
<option value="mrbchWht">Master without pedagogical preparation</option>
<option value="mrbchWht">Bachelor with pedagogical preparation</option>
<option value="bchWht">Bachelor without pedagogical preparation</option>
</select>
</div>
<div>
<label>Ascension degree: </label>
<select id="degrees">
<option value="" selected disabled hidden>Select</option>
<option value="intern">intern</option>
<option value="contractual">contractual</option>
<option value="designated">designated</option>
<option value="certificated">certificated</option>
</select>
</div>
<div>
<label>Workload: </label>
<select id="workload">
<option value="" selected disabled hidden>Select</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
</select>
</div>
<div>
<label>Workload: </label>
<input onchange="calcSalaries()" type=text id="inppn">
<span id="spl44"></span>
</div>
<div>
<label>Salary: </label>
<span id="spl55"></span>
</div>
<button onclick="getSalary()">Get Salary</button>
<button id="clear" onclick="clearInps()">Clear data</button>
</form>
But your data structure is very difficult to deal with - you should use an object instead, so you can access by string keys, which is much simpler than .find. Use something like this instead:
const salaries = {
mrWh:
{intern: 2511,
contractual: 2592,
designated: 2932,
certificated: 3411
},
mrbchWht: {
intern: 2121,
contractual: 2200,
designated: 2522,
certificated: 3000
},
bchWht: {
intern: 1868,
contractual: 1910,
designated: 2200,
certificated: 2600
}
};
const prop1 = 'mrWh';
const prop2 = 'designated';
console.log(salaries[prop1][prop2]);
I think your main issue is that you're missing .value in a couple of places. For example: var selEdLvl = formData.elements["edLvl"]; should probably be changed to var selEdLvl = formData.elements["edLvl"].value;
If you turn your salaries array into an "associative" one:
var salaries_assoc = salaries
.reduce(function(ac,d,i){
ac[d[0]]=d.slice(1)
.reduce(function(ac,d,i){
ac[d[0]]=d[1];return ac
},{});
return ac
},{});
/*"{
"mrWh": {
"intern": 2511,
"contractual": 2592,
"designated": 2932,
"certificated": 3411
},
"mrbchWht": {
"intern": 2121,
"contractual": 2200,
"designated": 2522,
"certificated": 3000
},
"bchWht": {
"intern": 1868,
"contractual": 1910,
"designated": 2200,
"certificated": 2600
}
}"*/
Now you can do this in your event (or in your getSalaries function etc):
var value1 = document.getElementById("edLvl").value,//"mrWh"
value2 = document.getElementById("degrees").value;//"intern"
salaries_assoc[value1] && salaries_assoc[value1][value2];//2511
I using YUI 3, but I have a question about YUI usage.
I have a select tag with some option tags:
YUI().use( "node", "event", "cssbutton", function(Y){
Y.one('body').addClass('yui3-skin-sam');
Y.one('#btnSel2').on('click',function(){
Y.one('#mySelect').set('value', '5');
});
});
<select id="mySelect" size="10" multiple="true">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">PineApple</option>
<option value="4">Orange</option>
<option value="5">Peach</option>
</select>
<button id="btnSel2" class="yui3-button">Set Selected</button>
The above method just cover one value, can i set multiple value from array or string with comma delimited?
If you check yui3/build/dom-base/dom-base.js line 202 you will see this feature is not implemented:
if (options && options.length) {
// TODO: implement multipe select
if (node.multiple) {
} else if (node.selectedIndex > -1) {
val = Y_DOM.getValue(options[node.selectedIndex]);
}
}
Here is how we implemented this feature:
YUI().use( "node", "event", "cssbutton", function(Y){
Y.one('body').addClass('yui3-skin-sam');
Y.DOM.VALUE_GETTERS.select = function(node) {
var val = node.value,
options = node.options;
if (options && options.length) {
if (node.multiple) {
val = [];
for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) {
if (option.selected) val.push(Y.DOM.getValue(option));
};
} else if (node.selectedIndex > -1) {
val = Y.DOM.getValue(options[node.selectedIndex]);
}
}
return val;
};
Y.DOM.VALUE_SETTERS.select = function(node, val) {
if (node.multiple && !Y.Lang.isArray(val)) val = [val]; // Allow to set value by single value for multiple selects
for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) {
if ((node.multiple && val.indexOf(Y.DOM.getValue(option)) > -1) || (!node.multiple && Y.DOM.getValue(option) === val)) {
option.selected = true;
//Y_DOM.setAttribute(option, 'selected', 'selected');
}
}
};
Y.one('#btnSel2').on('click',function(){
Y.one('#mySelect').set('value', ['1', '5']);
});
});
<script src="http://yui.yahooapis.com/3.18.1/build/yui/yui-min.js"></script>
<select id="mySelect" size="10" multiple="true">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">PineApple</option>
<option value="4">Orange</option>
<option value="5">Peach</option>
</select>
<button id="btnSel2" class="yui3-button">Set Selected</button>
I'm new to jquery, I'm working on a survey form and I have multiple dropdown menus for different questions but they all have the same dropdown value. Supposed I have:
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
And other different dropdowns with different id's. What is the best way to count how many has selected Yes, No and N/A/ ? Thanks
you can do it simple this way
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
var yes = 0;
var no = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes') { yes++; }
if($(s).val() == 'No') { no++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
});
DEMO
Try this — https://jsfiddle.net/sergdenisov/h8sLxw6y/2/:
var count = {};
count.empty = $('select option:selected[value=""]').length;
count.yes = $('select option:selected[value="Yes"]').length;
count.no = $('select option:selected[value="No"]').length;
count.nA = $('select option:selected[value="N/A"]').length;
console.log(count);
My way to do it would be :
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
Check the console (or replace with alert).
With your code, it would be something like that (assuming you want to check on a button click event) :
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<button class="btn btn-primary" id="countYes"></button>
<script type="text/javascript">
$('#countYes').on('click', function(){
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
});
</script>
You can check at another event, I choosed a button click just for example.
There is likely a cleaner way to do this, but this will get the job done (assuming there is a button click to trigger things):
$("#theButton").on('click', function() {
var totalSelect = 0;
var totalYes = 0;
var totalNo = 0;
var totalNA = 0;
$("select").each(function(){
totalSelect++;
if ($(this).val() == "Yes") { totalYes++; }
if ($(this).val() == "No") { totalNo++; }
if ($(this).val() == "N/A") { totalNA++; }
});
});
Hope this helps the cause.
In common you can use change event:
var results = {};
$('select').on('change', function() {
var val = $(this).val();
results[val] = (results[val] || 0) + 1;
});
DEMO
If you want count for each type of select:
$('select').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
if (!results[name]) {
results[name] = {};
}
results[name][val] = (results[name][val] || 0) + 1;
});
DEMO
In the results will be something like this:
{
"Forms[AgentIsPitch]": {
"Yes": 1,
"No": 2,
"N/A": 3
},
"Forms[MandatoryOptIsStated]": {
"No": 5,
"N/A": 13
},
}
UPD: for counting current choice:
$('select').on('change', function() {
var results = {};
$('select').each(function() {
var val = $(this).val();
if (val) {
results[val] = (results[val] || 0) + 1;
}
})
console.log(results);
});
DEMO
I am working on a function in Javascript/jQuery.
The function will search for usernames in the "select" element "Y" and selects them whene you copied a bunch of usernames in the textarea "X" with ', ', ',', ';' or ' ' as separator and also if you do it the other way around:
javascript/jQuery:
$(document).ready(function() {
$("dd#id-element select#id").attr({"multiple": "multiple", "size": 25, "name": "id[]"});
});
$(function() {
$("select#id").change(function() {
var selected_id = $(this).val(),
selected_name = new Array();
$(this).find("option:selected").each(function() {
selected_name.push($(this).text());
});
$("textarea#id_field").val(selected_id);
$("textarea#name_field").val(selected_name);
console.log(selected_id, selected_name);
});
$("textarea#name_field").keyup(function() {
$("select#id option").removeAttr("selected");
var names_raw = $(this).val(),
names = names_raw.replace(/(, | |,)/gi, ";"),
selected_name = names.split(";"),
selected_id = new Array();
$.each(selected_name, function(i, value) {
if (value != "" && value != null) {
$("select#id option[label='" + value + "']").attr("selected", true);
selected_id.push($("select#id option[label='" + value + "']").val());
}
});
});
});
HTML code:
<select name="id" id="id">
<option value="1092" label="00lara00">00lara00</option>
<option value="5105" label="010201e">010201e</option>
<option value="1725" label="0411dennis">0411dennis</option>
<option value="1795" label="051259">051259</option>
<option value="2281" label="0815Timmey">0815Timmey</option>
<option value="3337" label="0vlinder0">0vlinder0</option>
<option value="127" label="1001gece">1001gece</option>
<option value="3693" label="111nizza">111nizza</option>
<option value="821" label="114helen">114helen</option>
<option value="2887" label="1212whopper">1212whopper</option>
<option value="5564" label="123boo">123boo</option>
</select>
<textarea name="name_field" id="name_field"></textarea>
when i select some usernames in the select element, it works fine, the usernames are copied to the textarea.
when i paste some usernames in the textarea, everything is deselected like it should, but there is nothing new selected
I finally got it working. This is how I did it
Javascript:
$(document).ready(function() {
$("dd#id-element select#id").attr({"size": 25});
});
$(function() {
$("select#id").change(function() {
var selected_id = $(this).val(),
selected_name = new Array();
$(this).find("option:selected").each(function() {
selected_name.push($(this).text());
$(this).addClass("checked");
});
$("textarea#name_field").val(selected_name);
$("textarea#name_field").keyup();
});
$("textarea#name_field").keyup(function() {
$("select#id option.checked").attr("checked", null).attr("selected", null).removeClass("checked");
var names_raw = filterValue($(this).val()),
names = names_raw.replace(/(, | |,|\s)/gi, ";"),
selected_name = names.split(";"),
selected_id = new Array();
$(this).val(names_raw)
$.each(selected_name, function(i, value) {
if (value != "" && value != null) {
if ($("select#id option[label='" + value + "']").length > 0) {
$("select#id option[label='" + value + "']").attr('checked', 'checked').attr('selected', 'selected').addClass("checked").focus();
selected_id.push($("select#id option[label='" + value + "']").val());
}
}
});
$("select#id").val(selected_id);
});
});
html code:
<select name="id[]" id="id" multiple="multiple">
<option value="1092" label="00lara00">00lara00</option>
<option value="5105" label="010201e">010201e</option>
<option value="1725" label="0411dennis">0411dennis</option>
<option value="1795" label="051259">051259</option>
<option value="2281" label="0815Timmey">0815Timmey</option>
<option value="3337" label="0vlinder0">0vlinder0</option>
<option value="127" label="1001gece">1001gece</option>
<option value="3693" label="111nizza">111nizza</option>
<option value="821" label="114helen">114helen</option>
<option value="2887" label="1212whopper">1212whopper</option>
<option value="5564" label="123boo">123boo</option>
</select>
<textarea name="name_field" id="name_field"></textarea>