How can I set the default value for a dropdown selection - javascript

I assumed that the my select state dropdown box would automatically display "select state" However, this did not work as I had expected. The dropdown box is empty until I choose a country and only then will the state dropdown box display "select state. How can I set my state dropdown box to "select state" by default?
function populateStates(countryElementId, stateElementId) {
var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;
var stateElement = document.getElementById(stateElementId);
stateElement.length = 0; //
stateElement.options[0] = new Option('Select State', '');
stateElement.selectedIndex = 0;
var state_arr = s_a[selectedCountryIndex].split("|");
for (var i = 0; i < state_arr.length; i++) {
if (state_arr[i] != "") {
stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]);
}
}
}
function populateCountries(countryElementId, stateElementId) {
// given the id of the <select> tag as function argument, it inserts <option> tags
var countryElement = document.getElementById(countryElementId);
jQuery("#" + countryElementId + " option").remove();
jQuery("#" + countryElementId).append("<option value=\"\">USA</option>");
for (var i = 0; i < country_arr.length; i++) {
countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
}
// Assigned all countries. Now assign event listener for the states.
if (stateElementId) {
countryElement.onchange = function() {
populateStates(countryElementId, stateElementId);
jQuery("#" + stateElementId + " option:eq(0)").attr("selected", "selected");
jQuery("#" + stateElementId).val("").change();
if (jQuery("#" + countryElementId).val() == "USA") {
jQuery("#Zip_Postal_Code__c").attr("maxlength", "5");
} else if (jQuery("#" + countryElementId).val() == "Canada") {
jQuery("#Zip_Postal_Code__c").attr("maxlength", "6");
} else {
jQuery("#Zip_Postal_Code__c").removeAttr("maxlength");
}
};
}
}

You can just use the default state dropdown html to contain only one option: Select State. e.g. in the html
<select id="state_select">
<option value="">Select State</option>
</select>

To prevent the first option from being selected:
<select>
<option value="" disabled selected hidden>Select State</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
</select>

Related

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>

Bind another dropdowns as per previous values

I have total 4 dropdowns list... all dropdown contain numbers.
The maximum number of the last three dropdowns together is always equal to the amount that’s selected in the 1st dropdown.
If user selected 4 from 1st dropdown.
In this case all remaining dropdowns contain the values 0, 1, 2 ,3 and 4.
If customer selects 2 from 2nd dropdown then other two dropdowns will only show the values 0,1 and 2.
If customer selects 1 from 3rd dropdown then last should only show the values 0 and 1.
can anyone help me to sort-out this. Thanks in advance
I have tried so far
var tripChildSelect = $('#trip-child-count-range_0');
var childRangeLength = "<?php echo $this->getChildRangeLength()?>";
var j;
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
}
tripChildSelect.change(function() {
tripChildSelect = $(this);
availableChildren = tripChildSelect.data('max-count') - tripChildSelect.val();
console.log(tripChildSelect.data('max-count') - tripChildSelect.val());
if(tripChildSelect.data('max-count') - tripChildSelect.val() === 0) {
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
childRange.prop('disabled', true);
}
} else {
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
childRange.find('option').each(function (index, element) {
selectOption = $(element);
if(selectOption.val() <= availableChildren) {
selectOption.show();
} else {
selectOption.hide();
}
});
childRange.prop('disabled', false);
}
}
});
//disable if sum equals
$('.trip-child-count-range').change(function() {
// body...
var sum = 0;
$('.trip-child-count-range :selected').each(function() {
sum += Number($(this).val());
});
// console.log('sum- '+sum);
if(sum == $('#trip-child-count').val())
{
$('.trip-child-count-range').each(function() {
if($(this).val() == 0)
$(this).attr('disabled', true);
});
}
else
{
$('.trip-child-count-range').each(function() {
if($(this).val() == 0)
$(this).attr('disabled', false);
});
}
})
$('#trip-child-count').change(function() {
// body...
var i;
for (i = 1; i <= $(this).val(); i++)
{
if ( $(".trip-child-count-range option[value='"+i+"']").length == 0 )
$('.trip-child-count-range').append( '<option value="'+i+'">'+''+i+'</option>' );
}
//set adta-max-xount
$('#trip-child-count-range_0').data( "max-count", $(this).val());
// console.log('hello' + $('#trip-child-count-range_0').data( "max-count"));
//remove greater options
$(".trip-child-count-range option").each(function() {
if($(this).val() > $('#trip-child-count').val())
{
$(".trip-child-count-range option[value="+this.value+"]").remove();
}
});
//added finalllu
$('.trip-child-count-range').attr('disabled', false);
$('.trip-child-count-range option[value=0]').attr('selected','selected');
availableChildren = $('#trip-child-count').val();
});
first dropdown id : #trip-child-count
common class for remaining 3 dropdowns: trip-child-count-range
Here I put your basic need. First create first drop down with 0-4 options and make other three drop down as empty. Then append options to other drop down based on the current drop down value
<!DOCTYPE html>
<html>
<body>
<div>
<select id="dropdown1">
<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 id="dropdown2">
</select>
<select id="dropdown3">
</select>
<select id="dropdown4">
</select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#dropdown1").on("change",function(){
var dd1 = parseInt($(this).val());
$("#dropdown2, #dropdown3, #dropdown4").empty();
for(var i=0;i<=dd1;i++){
$("#dropdown2, #dropdown3, #dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
$("#dropdown2").on("change",function(){
var dd1 = parseInt($("#dropdown1").val());
var dd2 = parseInt($(this).val());
$("#dropdown3, #dropdown4").empty();
for(var i=0;i<=dd1-dd2;i++){
$("#dropdown3, #dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
$("#dropdown3").on("change",function(){
var dd2 = parseInt($("#dropdown2").val());
var dd3 = parseInt($(this).val());
$("#dropdown4").empty();
for(var i=0;i<=dd2-dd3;i++){
$("#dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
});
</script>
</body>
</html>

Is there a way to select all option values in selectbox?

I have a function that creates many select boxes. I need an option value to select all the values in one select, because if I give "all" as value, I have to do a lot of switches and if / else statements, and it would be great if I could avoid that.
Here is the function:
function creaselect(nomeoggetto, oggetto, nome) {
var P_P_comodo = _(A_Punti_dati).groupBy(oggetto).map(function(item, itemId) {
console.log(oggetto);
var result = {};
result[itemId] = item[0][nome];
return result
}).value();
document.write("Seleziona " + nomeoggetto + "<select id=my" + nomeoggetto + ">");
document.write("<option value=all selected>Tutti</option>");
_.each(P_P_comodo, function(value, key) {
_.each(value, function(value, key) {
P_P[key] = value;
document.write("<option value=" + key + ">" + value + "</option>");
});
});
document.write("</select><br>");
}
You'll need to do 2 things:
Set up a function to iterate through each option and set the "selected" attribute to true
Set up a handler to call this function when the user selects "all"
HTML
<select id='control'>
<option value=''>(Select one)</option>
<option value='all'>All</option>
<option value='none'>None</option>
</select>
<select id='sel' name="sometext" size='5' multiple>
<option value='1'>text1</option>
<option value='2'>text2</option>
<option value='3'>text3</option>
<option value='4'>text4</option>
<option value='5'>text5</option>
</select>
Javascript
var control = document.getElementById('control');
control.onchange = setOptions;
function setOptions() {
var control = document.getElementById('control');
var val = control.value;
if (val == 'all' || val == 'none') {
var mySelectObj = document.getElementById('sel');
var bool = val == 'all'
setSelect(mySelectObj, bool);
}
}
function setSelect(sel, bool){
for(var i = 0; i <sel.length; i++) {
sel.options[i].selected = bool;
}
}
jsFiddle: https://jsfiddle.net/mspinks/qqp7w1qk/11/
Please note: in order to allow multi-select on a select input, you must specify the attribute "multiple". Otherwise, you'll need to use a third-party select control.

How do I remove old options in Jquery when parent select box is changed?

I have 3 chained select boxes using jquery and json.
Depending on first 2 values I filter third one my code actually works but the problem is when I change values of first 2 select boxes third select recieves new datas while keeping old ones.
I've tried to empty my array but it didn't work.
$(document).ready(function() {
var json = JSON.parse(jsonString);
var makesArray = [];
var selectedyear;
var selectedcourse;
var $yearDropDown = $("#DropDown_Year");
var $course_type = $("#course_type");
$yearDropDown.change(function() {
selectedyear = this.value;
//filter based on selected year.
});
$course_type.change(function(){
selectedcourse = this.value;
makesArray = jQuery.grep(json, function(course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
for(var i = 0, l = makesArray.length; i < l; i++){
var option = makesArray[i];
selectBox.options.add( new Option(option.course_code, option.course_code, option.course_code) );
}
makesArray= []; //makesArray.empty();
});
});
<div id="DrpDwn">
Year:
<select id="DropDown_Year">
<option>Yıl</option>
<option value="15">2015-2016</option>
<option value="16">2016-2017</option>
</select>
<select class="form-control" id="course_type" name="course_type" required>
<option value="" selected> Choose</option>
<option value="Yos">YÖS</option>
<option value="SatMatGeo">SAT (MAT)</option>
<option value="SatCriRea">SAT (ENG)</option>
<option value="TomerABC">TÖMER (ABC)</option>
<option value="TomerAB">TÖMER (AB)</option>
<option value="TomerBC">TÖMER (BC)</option>
<option value="TomerA1A2">TÖMER (A)</option>
<option value="TomerB1B2">TÖMER (B)</option>
<option value="TomerC1C2">TÖMER (C)</option>
</select>
Make:
<select id="DropDown_Make">
<option>None</option>
</select>
</div>
and this is JSFIDDLE
https://jsfiddle.net/rw7cb8c5/25/
Make DropDown_Make empty using selectBox.innerHTML = "" in $course_type.change() like following.
$course_type.change(function () {
selectedcourse = this.value;
makesArray = jQuery.grep(json, function (course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
selectBox.innerHTML = ""; //added this line
for (var i = 0, l = makesArray.length; i < l; i++) {
var option = makesArray[i];
selectBox.options.add(new Option(option.course_code, option.course_code, option.course_code));
}
makesArray.empty();
});
UPDATED FIDDLE

Count Unique Selection from Multiple Dropdown

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

Categories

Resources