multiple select remove disable button if select is not empty - javascript

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>

Related

Sorting selectbox with Javascript

I'm Setup a <select> dropdown list and I trying to make options sorting in numerical order (Ascending) :
HTML
<select id="singleSelector">
<option value="/single?id=544">1</option>
<option value="/single?id=598">4</option>
<option value="/single?id=605">6</option>
<option value="/single?id=604">3</option>
<option value="/single?id=603">7</option>
<option value="/single?id=602">5</option>
<option value="/single?id=601">2</option>
</select>
Edit :
When using the following JS by #Sanjay, the order is not correct :
JavaScript :
$(function() {
// choose target dropdown
var select = $('select');
select.html(select.find('option').sort(function(x, y) {
// to change to descending order switch "<" for ">"
return $(x).text() > $(y).text() ? 1 : -1;
}));
});
Output :
It's possible to make order 1,2,3,4,5 instead of 1,10,11...,2,20,21 ?
Here is working example.
$(function() {
var select = $('select');
select.html(select.find('option').sort(function(x, y) {
var num1 = parseInt($(x).text());
var num2 = parseInt($(y).text());
return num1> num2 ? 1 : -1;
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="wrapper">
<select>
<option selected>Choose a number</option>
<option value="3">3</option>
<option value="1">1</option>
<option value="0">0</option>
<option value="2">2</option>
<option value="8">8</option>
</select>
</div>
try THIS
var target = document.getElementById('singleSelector');
function sortIt(target ) {
var tmp = new Array();
for (var i=0;i<target.options.length;i++) {
tmp[i] = new Array();
tmp[i][0] = target.options[i].text;
tmpA[i][1] = target.options[i].value;
}
tmp.sort();
while (target.options.length > 0) {
target.options[0] = null;
}
for (var i=0;i<tmp.length;i++) {
var op = new Option(tmp[i][0], tmp[i][1]);
target.options[i] = op;
}
return;

Append options to select box depend on extracted part from array

I have 4 selectboxs moduleName, submoduleName, ProgrameName and last selectbox has all data for username, module, submodule and programe name merged and splited with ";" between each other, I need: when user select module name from moduleName Selectbox it filters values in all data selectbox and splites submoduleNames under this moduleName and append it as options to submoduleName Selectbox, also the same when user select from submoduleName selectbox it filters programeNames under this module and subModuleNames and append it as options in programeName selectbox. I tried to splite each line in allData selectbox but i failed to continue. here what i tried but it is not working.
Thank you for your help.
$(document).ready(function(){
function check(){
var lines = $('#splitedOptions').val().split(/\n/);
var texts = [];
for (var i=1; i < lines.length; i++) {
texts.push(lines[i]);
}
for (var i=0; i < texts.length; i++) {
var extractedPart = texts[i].split(';'),
ModuleNameVal = $("#moduleName option:selected").val();
if(extractedPart[1] == ModuleNameVal){
var newOption = "<option value='"+extractedPart[2]+"'>"+extractedPart[2]+"</option>";
$('#SubModuleName').append(newOption);
}
}
}
function c1() {
var optionsCount = $('#allData').find('option').size();
var textArea ="";
for (var i = 1; i <= optionsCount; i++) {
if(i!=1){
textArea += '\n';
}
var xItem = $('#allData').find('option:nth-child(' + (i) + ')').text();
textArea += xItem ;
}
$('#splitedOptions').val('');
$('#splitedOptions').val(textArea);
check();
}
$('#moduleName').change(function(){
c1()
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions" ></textarea>
One way to achieve above is to filter the options from allData select-box and get only those option which has the value which user has selected using value*="yourvalue".
Then , onces you get the options you need to know which select-box has been change so that we can get required value only when we do split and pass required index .
Lastly , we need to loop through the options which we have got from filtering select-box .Suppose user select Master so there are Master in many places so to avoid getting data from all option i have check the value of select with the first select-box as well if matches apppend only those options.
Demo Code :
$('select').change(function() {
//get value
var name = $(this).val();
//filter option and get only option which has the value which user has slected
var s = $("#allData").find('option').filter('[value*=' + name + ']').each(function(ele) {
return $(this).val();
});
var module_namess;
var index;
//check the id of select-box
if ($(this).attr("id") == "moduleName") {
module_namess = "SubModuleName";
index = 2;//set index
} else if ($(this).attr("id") == "SubModuleName") {
name = $("#moduleName").val()
module_namess = "programeName"
index = 3
}
$("#" + module_namess).empty()
$('#' + module_namess).append("<option >Select one</option>")
var valuess = ''
//loop through options
for (var i = 0; i < s.length; i++) {
valuess += $(s[i]).val()
//if first value is same
if ($(s[i]).val().split(";")[1] == name) {
var sub_value = $(s[i]).val().split(";")[index]//get the value
var newOption = "<option value='" + sub_value + "'>" + sub_value + "</option>";
$('#' + module_namess).append(newOption);//append
}
}
$('#splitedOptions').val(valuess);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions"></textarea>

Select values not correctly increasing/decreasing total number in js

I thought I had solved this javascript 'for' loop to sum up the numeric choices of several select fields to a number, each time one of them is changed.
But, modifying a choice in any of the selected fields is adding the number again, instead of replacing the initial choice number - which is what I want.
Example: a user chooses from 3 fields, these values: +15, -5, +1.
The total should be "11"
If the user modifies their first select to +10 instead of #+15, the total value should be "6". Instead, it's ADDING the modified number to everything. So the number becomes "21" - not what I want.
Note: I want to increase the number incrementally with each select choice - NOT a total of all of them when the user is done with the fields
Here's what I've got:
<form action="/cgi-bin/dropdown.cgi" method="post">
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (+10)</option>
<option value="-5">Choice 2 (-5)</option>
<option value="60">Choice 3 (+60)</option>
</select>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="8">Choice A (+8)</option>
<option value="-10">Choice B (-10)</option>
<option value="15">Choice C (+15)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (+5)</option>
<option value="15">Choice ii (+15)</option>
<option value="12">Choice iii (+12)</option>
</select>
</form>
<div id="tally" style="">0</div>
<script>
var sum = 0;
document.addEventListener("DOMContentLoaded", function(event) {
var gg1 = new JustGage({
id: "gg1",
value: 0,
textRenderer: customValue
});
var userSelection = document.getElementsByClassName('selectables');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
fieldvalue = userSelection[i].value;
fieldname = userSelection[i].id;
if (fieldvalue > 0) {
// using += breaks other scripts for some reason
sum = sum + parseInt(fieldvalue);
} else if (fieldvalue < 1) {
fieldvalue = fieldvalue * -1;
sum = sum - parseFloat(fieldvalue, 10);
}
document.getElementById("tally").innerHTML = sum;
// this is the value that takes the number I'm trying to increment based on choices in selects
gg1.refresh(sum);
return false;
})
}
});
</script>
This happens because inside the callback function of the change listener you're not considering the values of the other dropdowns. Grab them using a second for-loop and recalculate the sum.
Here's your modified callback function:
for (let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
sum = 0;
for (var b = 0; b < userSelection.length; b++) {
fieldvalue = userSelection[b].value;
if (fieldvalue > 0) {
// using += breaks other scripts for some reason
sum = sum + parseInt(fieldvalue);
} else if (fieldvalue < 1) {
fieldvalue = fieldvalue * -1;
sum = sum - parseFloat(fieldvalue, 10);
}
}
document.getElementById("tally").innerHTML = sum;
// this is the value that takes the number I'm trying to increment based on choices in selects
gg1.refresh(sum);
return false;
})
}
Whenever any of the select values is changed, you should re-compute the entire sum. Something like this:
onload = function {
var userSelection = document.getElementsByClassName('selectables');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
var sum= computeSum();
//whatever you want to do with sum
})
}
function computeSum() {
var sum = 0;
for(const select in userSelection) {
sum += select.value;
}
return sum;
}
}
Like others have mentioned, you need to recalculate the total every time any of select control value changes. Here's a demo (un-optimized):
document.querySelectorAll('select').forEach(select => select.addEventListener('change', (event) => {
if (allValid()) {
document.querySelector('#tally').innerHTML = calcTotal();
}
}))
const allValid = () => {
let status = true;
document.querySelectorAll('select').forEach(select => {
if (select.selectedIndex === 0) status = false;
})
return status;
}
const calcTotal = () => {
let total = 0;
document.querySelectorAll('select').forEach(select => {
total += parseInt(select.value);
})
return total;
}
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (+10)</option>
<option value="-5">Choice 2 (-5)</option>
<option value="60">Choice 3 (+60)</option>
</select>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="8">Choice A (+8)</option>
<option value="-10">Choice B (-10)</option>
<option value="15">Choice C (+15)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (+5)</option>
<option value="15">Choice ii (+15)</option>
<option value="12">Choice iii (+12)</option>
</select>
<div id="tally" style="">0</div>

Default value not working in select tag if the user doesn't select any options?

Hello,
I'm trying to make a default value of language selection to be English whose value is 1. So if the user doesn't select language option, it should still be 1 so that I can run my algorithm. But when I test it that doesn't select any value, it doesn't make it default value.
And I decided to check the datatype of language option, it's a string type, but even if I make if(isNaN(languageOption)){ languageOption = "1";}, it's still not working. Can anyone tell me why?
Thank you for your help
<body>
<div>
<img src="image/MindScribe-cursive.png" id="cursive">
</div>
<div id="container">
<img src="image/MindScribe-zebra.png" id="ImageEnterVariables" alt="Hello, I'm Stripes">
<img src="image/MindScribe-zebra2.png" id="onlyShowZebraImage" alt="Hello, I'm Stripes" style=display:none>
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
<script>
var languageOption = parseInt($("#languageSelection").val() );
$("#languageSelection").on("change", function(){
if(isNaN(languageOption)){ languageOption = "1";}
languageOption = $(this).val();
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
</script>
</body>
Why you are doing these much stuff for making English default value? You can just add selected attribute to that option which you want to make default.
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1" selected>English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
And in your script, you can apply below logic to set default option to 1 :
languageOption = $(this).val();
if(languageOption==""){
languageOption="1";
}
$("#languageSelection").on("change", function(){
var languageOption = $(this).val();
if(languageOption.length==0){
languageOption=1;
}
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="languageSelection" >
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
Above code works for me, it gives me 1 if Choose a language is selected.
If you need the "Choose a language" to be displayed, set its value to 1 (the same as English):
<option value="1">Choose a language</option>

YUI 3: Set Value to Multiple Select

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>

Categories

Resources