HTML Connected dropdown (more than one)with number as value - javascript

Basically, I want to create more then 1, dropdowns, which contains numbers as value eg.
<select id="dp1">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
<select id="dp2">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
<select id="dp3">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
this is just one dropdown. lets say I have 3 dropdown lists with same numbers with different default value eg. dp1 -> 1, dp2 -> 2, dp3 -> 3 . So, Now if user changes value of dp3 to 1 the value of other dropdown list should get change automatically as per sequence like dp1 -> 2 and dp2 -> 3.
if i explain it with other example if user changes value of dp3 to 2 the value dp1 should not change and value of dp2 -> 3should change.
How is it possible to do using Javascript / jquery. (I am using php to populate dropdown from database)
Thank you in advance.

if you just want to change the previous dropdownlists buy changing the current dropdownlist maybe this sample code can help you :
$("select").change(function(){
var selectValue = $(this).val();
var toRemove = 'op';
var value = selectValue.replace(toRemove,'');
var selectId = $(this).attr('id');
var toRemove = 'dp';
var id = selectId.replace(toRemove,'');
id = id-1;
for(var i = id; i>=1; i--){
value = value -1;
var newValue = "op"+value;
$("#dp"+i).val(newValue);
}
});

If the data you're using is really just numeric, then something like this will work. Click here for a jsfiddle example that demonstrates the behavior I think you're looking for.
<select id="dp1" class="dropdown"></select>
<select id="dp2" class="dropdown"></select>
<select id="dp3" class="dropdown"></select>
<script type="text/javascript">
var values = [1, 2, 3];
$(function() {
initDropdowns();
$('select.dropdown').change(function() {
setDropdownValues($(this).attr('id'));
});
});
function initDropdowns() {
var optionsHtml = '';
for(var i = 0; i < values.length; i++) {
var value = values[i];
optionsHtml += '<option value="' + value + '">' + value + '</option>';
}
$('select.dropdown').append(optionsHtml);
setDropdownValues();
}
function setDropdownValues(excludeListId) {
var valuesClone = values.slice();
var $dropdowns = $('select.dropdown');
if(excludeListId) {
valuesClone.splice(Number($('#' + excludeListId).val()) - 1, 1);
}
$('select.dropdown').each(function() {
if($(this).attr('id') !== excludeListId) {
$(this).val(valuesClone[0]);
valuesClone.splice(0, 1);
}
});
}
</script>

Related

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

How can I refresh second select option when first select option is changed?

How can I refresh second select option when first select option is changed?
I am generating the array here for patient_code2:
//GENERATE NUMBERS FOR CYCLE
function patsient(selector) {
var i;
for (i = 1; i <= 99; i++) {
var text = '0' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 2, 2));
}
}
patsient(document.getElementById("patient_code2"));
I am generating the array for patient_code here:
function myFunction(selector) {
var i;
for (i = 1; i <= 999; i++) {
var text = '00' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 3, 3));
}
}
//usage:
myFunction(document.getElementById("patient_code"));
Here I am inserting the last value from database to the field:
//INSERT THE VALUE FROM DATABASE
var tsykkel_id = '<?php foreach ($tsykkel_id as $row){echo $row['patsiendi_tsykkel'];}?>';
$('#patient_code2')[0].options[parseInt(tsykkel_id)].selected = true;
$(document).ready().on('change', '#patient_code2', function () {
var index = $('option:selected', $(this)).index();
$('option', $(this)).each(function (i, x) {
if (i < index) { $(this).remove(); }
});
});
HTML
<select name="patient_code" data-placeholder="" id="patient_code" class="chosen-select form-control" tabindex="2">
</select>
<label class="control-label">Tsükkel:</label>
<select name="patient_code2" data-placeholder="" id="patient_code2" class="chosen-select form-control" tabindex="2">
</select>
So lets say that person chooses 002 from the first then the second should start from 01 again.
try this then. Code is tested.
$(document).ready().on('change','#patient_code2',function(){
var index = $('option:selected',$(this)).index();
$('option',$(this)).each(function(i,x){
if(i<index){$(this).remove();}
});
$('select#patient_code').prop('selectedIndex', 0);
});
fiddle : http://jsfiddle.net/roullie666/69j94ro6/2/
You can just start printing after the match has been found. I am writing both ways since you asked?
For javascript version use roullie's no point duplicating.
<?php
$flag = false;
foreach ($tsykkel_id as $row) {
if ($selected) {
$flag = true;
}
if ($flag) {
$row['patsiendi_tsykkel'];
}
}?>

jQuery - Get Total value of the next options in a dropdown after the selected one based on attribute

HTML Output
<option data-task-hours="100" value="1"> - Parent Task</option>
<option data-task-hours="50" value="2"> - - Child task</option>
<option data-task-hours="50" value="3"> - - Child task</option>
jQuery Code to fetch value of next option:
$('#dropDownId option:selected').next().data('task-hours');
Tried looping for multiple child task(s) but its not working:
var foo = [];
$('#dropDownId :selected').each(function(i, selected){
foo[i] = $(selected).data('task-hours');
});
How can I fetch total/combined value of next options after the selected one ?
In above case total value should be 50 (child 1) + 50 (child 2) = 100 (parent task) i.e. child task(s) total value should not exceed the value of parent task
There's the nextAll() method for this :
var selectedOption = $('#dropDownId option:selected')
var selectedOptionValue = selectedOption.data('task-hours');
var sum = 0;
selectedOption.nextAll().each(function(){
if (sum < selectedOptionValue) {
sum += $(this).data('task-hours');
} else {
sum = selectedOptionValue;
return false;
}
});
Why dont you loop it.First get the selected value.Then run the loop like below.
Note : below is not error free code , Its just like alogirthm or steps.
var startfrom = $('#dropDownId option:selected').attr('value');
var alltext = "";
$('option').each(function(key,attr) {
{
if(key<startfrom) return;
alltext += attr.text;
}
console.log(alltext);
You can use:
var sum=0;
alert($('select option:first').attr('data-task-hours'))
$('select option:gt(0)').each(function(){
sum+= parseInt($(this).attr('data-task-hours'));
});
if($('select option:first').attr('data-task-hours')==sum){
alert("parent and children have same hours");
}
Working Demo
$("#dropDownId").on('change', function () {
var a=$('#dropDownId option:selected+option').attr('data-task-hours');
var b=$("#dropDownId option:selected").attr('data-task-hours');
var c=Number(a)+Number(b);
alert(c);
});
JS FIDDLE
Are you after something like this? Demo#Fiddle
var sOpt = $("#sel option:selected");
var nextOpts = sOpt.nextAll();
var sum = 0;
nextOpts.each(function() {
sum += $(this).data("taskHours");
});
if ( sum > sOpt.data("taskHours") ) {
alert ("Total is greater than parent");
} else {
alert (sum);
}
HTML:
<select id="sel">
<option data-task-hours="100" value="1" selected="selected"> - Parent Task</option>
<option data-task-hours="50" value="2"> - - Child task</option>
<option data-task-hours="50" value="3"> - - Child task</option>
</select>
This works:
var indexOfSelected = $("#dropDownId option:selected").index()
var options = $("#dropDownId option")
var children = options.slice(indexOfSelected + 1, options.length)
total = 0
$.each(children, function(){
total += $(this).data("task-hours")
});
console.log("Total sum of children: " + total)
Try this Working Demo
$("#dropDownId").on('change', function () {
var one=$('#dropDownId option:selected+option').attr('data-task-hours');
var onetwo=$("#dropDownId option:selected").attr('data-task-hours');
var onethree=Number(one)+Number(onetwo);
console.log(onethree);
});

reset a drop down list value to previous value

I am using javascript to validate some drop down list selections. One selection is for the length of a buildings frame. The other 3 drop down are for garage doors that can be added to the side. I have the code alerting me if the total door widths have exceeded the frame length. I need the if condition to take the previous value of the last selected door drop down list and reset it to the amount before it if the amount exceeds my conditions in my if statement.
This is my html
Frame Length:
<select id="framewidth" onchange="doorsrightsideFunction()">
<option value="20">21</option>
<option value="25">26</option>
<option value="30">31</option>
<option value="35">36</option>
<option value="40">41</option>
</select>
<br>
<input type="hidden" name="eight_by_seven_width_right_side"
id="eight_by_seven_width_right_side" value="8">
<br>
<input type="hidden" name="eight_by_seven_height_right_side"
id="eight_by_seven_height_right_side" value="7">
<br>8x7:
<select id="eight_by_seven_right_side" onchange="doorsrightsideFunction()">
<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>
<br>
<input type="hidden" name="nine_by_seven_width_right_side"
id="nine_by_seven_width_right_side" value="9">
<br>
<input type="hidden" name="nine_by_seven_height_right_side"
id="nine_by_seven_height_right_side" value="7">
<br>9x7:
<select id="nine_by_seven_right_side" onchange="doorsrightsideFunction()">
<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>
<br>
<input type="hidden" name="ten_by_eight_width_right_side"
id="ten_by_eight_width_right_side" value="10">
<br>
<input type="hidden" name="ten_by_eight_height_right_side"
id="ten_by_eight_height_right_side" value="8">
<br>10x8:
<select id="ten_by_eight_right_side" onchange="doorsrightsideFunction()">
<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>
This is my javascript so far
function doorsrightsideFunction() {
function getValue(idElement) {
return document.getElementById(idElement).value;
}
var eightwidth = getValue("eight_by_seven_width_right_side");
var ninewidth = getValue("nine_by_seven_width_right_side");
var tenwidth = getValue("ten_by_eight_width_right_side");
var eightwidthamount = getValue("eight_by_seven_right_side");
var ninewidthamount = getValue("nine_by_seven_right_side");
var tenwidthamount = getValue("ten_by_eight_right_side");
var framewidth = getValue("framewidth");
var totaldoorwidth;
var totaldooramount;
var framewidthtotaldoorwidth;
var framespace;
totaldoorwidth = eightwidth * eightwidthamount
+ ninewidth * ninewidthamount
+ tenwidth * tenwidthamount;
totaldooramount = parseInt(eightwidthamount, 10)
+ parseInt(ninewidthamount, 10)
+ parseInt(tenwidthamount, 10);
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
} else { }
}
here is a link to my fiddle http://jsfiddle.net/steven27030/M52Hf/
http://jsfiddle.net/M52Hf/84/
you could use the data attribute and be sure to pass in the current element as a parameter on your doorsrightsideFunction call:
<select id="framewidth" onchange="doorsrightsideFunction(this)">
var previousValue = currentelement.getAttribute("data-prev");
if(previousValue == null)
previousValue = currentelement[0].value;
You will need to store the previous value so you can switch back when necessary, and update the previous value after a successful change. I would use arrays in various places.
var prevValue = Array();
function doorsrightsideFunction() {
function getValue(idElement) {
return document.getElementById(idElement).value;
}
function setValue(idElement,val) {
return document.getElementById(idElement).value = val;
}
var ids = Array("eight_by_seven_right_side","nine_by_seven_right_side","ten_by_eight_right_side");
var widths = Array(
getValue("eight_by_seven_width_right_side"),
getValue("nine_by_seven_width_right_side"),
getValue("ten_by_eight_width_right_side")
);
var values = Array();
for(i=0;i<ids.length;i++) {
if (!prevValue[i]) { prevValue[i]=0; }
values[i] = getValue(ids[i]);
}
var framewidth = getValue("framewidth");
var totaldoorwidth = 0;
var totaldooramount = 0;
var framewidthtotaldoorwidth;
var framespace;
for(i=0;i<ids.length;i++) {
totaldoorwidth += values[i] * widths[i];
totaldooramount += parseInt(values[i], 10);
}
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
for(i=0;i<ids.length;i++) { setValue(ids[i],prevValue[i]); }
} else {
prevValue = values;
}
}
updated fiddle
Edit: In answer to your follow on question in the comment:
is there a way to make it loop through and find the next size down that would work if they choose to many?
Yes, you can have it iterate the values to find one that fits, as long as the initial values are valid (in this case no doors is a perfect initial value). This also means you don't need to worry about storing any previous value.
I had some fun with this a took some liberties with your code.
First, a few changes in the HTMl:
for each element with an onChange, have it pass the element that was changed so we can tell which one to modify:
<select ... onchange="doorsrightsideFunction(this)">
change the IDs of the _width and _height hidden inputs so they are of the form <id of select element>_width (i.e. the width element for the select with id="eight_by_seven_right_side" should be "eight_by_seven_right_side_width" so you just need to take id + "_width" to find it)
wrap all of the door select elements in a <div id="doorchoices"> ... </div> so they can be found programmatically. This way adding a new door to the system is as simple as adding the select and height/width hidden inputs within the containing div, and the javascript finds and uses them automagically.
The javascript changes, I tried to comment inline:
//make ids and widths global to this page so we only have to construct it on page load
var ids;
var widths;
function getValue(idElement) {
var el = document.getElementById(idElement);
if (el) {
return parseInt(el.value);
} else {
return null;
}
}
function setValue(idElement, val) {
return document.getElementById(idElement).value = val;
}
window.onload = function () {
//construct id list from elements within the containing div when the page loads
ids = Array("framewidth");
widths = Array(null);
var container = document.getElementById("doorchoices");
var selections = container.getElementsByTagName("select");
var i;
for (i = 0; i < selections.length; i++) {
ids.push(selections[i].id);
// get each door's width from the _width element that matches the id
widths.push(getValue(selections[i].id + "_width"));
}
}
// el is the 'this' passed from the select that changed
function doorsrightsideFunction(el) {
console.log(widths);
console.log(ids);
var changedIndex = ids.indexOf(el.id);
//get all of the option elements of the changed select
var possibleValueEls = el.getElementsByTagName("option");
var values = Array();
var possibleValues = Array();
var framewidth;
var curValue;
var totaldoorwidth;
var totaldooramount;
var framewidthtotaldoorwidth;
var framespace;
var i;
function calcWidth() {
totaldoorwidth = 0;
totaldooramount = 0;
var i;
framewidth = values[0];
//start with 1 since index 0 is the frame width
for (i = 1; i < ids.length; i++) {
console.log(i + ")" + ids[i] + " " + values[i] + "(" + widths[i] + ")");
totaldoorwidth += values[i] * widths[i];
totaldooramount += parseInt(values[i], 10);
}
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
}
// get all possible values from the option elements for the select that was changed
for (i = 0; i < possibleValueEls.length; i++) {
possibleValues.push(parseInt(possibleValueEls[i].value));
}
// values should be increasing in order
possibleValues.sort();
// except framewidth should be decreasing
if (el.id == "framewidth") {
possibleValues = possibleValues.reverse()
};
// get the value of each element
for (i = 0; i < ids.length; i++) {
values[i] = getValue(ids[i]);
if (changedIndex == i) {
curValue = values[i]
};
}
calcWidth();
console.log(framewidthtotaldoorwidth);
console.log(framespace);
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
// start with the current value and try each until it fits
for (validx = possibleValues.indexOf(curValue); validx >= 0, framewidthtotaldoorwidth < framespace; validx--) {
//change the value in the values array
values[changedIndex] = possibleValues[validx];
//change the select to match
setValue(el.id, possibleValues[validx]);
//see if it fits
calcWidth();
}
}
}
New fiddle
and the simplicity of adding another door size - just add this to the HTML:
<input type="hidden" name="twelve_by_ten_right_side_width" id="twelve_by_ten_right_side_width" value="12" />
<input type="hidden" name="twelve_by_ten_right_side_height" id="twelve_by_ten_right_side_height" value="10" />
<br />
<label for="twelve_by_ten_right_side">12x10:</label>
<select id="twelve_by_ten_right_side" onchange="doorsrightsideFunction(this)">
<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>
New door fiddle

Categories

Resources