Jquery Replace Value In Select Depending On Other Select Box
I have the following array: var LWTable = []; LWTable.push([6,200,200,220]); LWTable.push([8,220,220,240]); LWTable.push([10,240,240,260]); LWTable.push([12,260,260,290]); LWTable.
Solution 1:
If its possible to change the data structure in the JS code to an object you can make this very striaghtforward. Firstly you can create the plength
select options on load from the keys of the object. Then on change of plength
you can use the selected value to find the key in the object and populate the options of pwidth
. Try this:
varLWTable = {
'6': [200, 200, 220],
'8': [220, 220, 240],
'10': [240, 240, 260],
'12': [260, 260, 290],
'15': [290, 310, 340],
'18': [330, 360, 400],
'21': [385, 420, 460],
}
var plengthOptions = '';
Object.keys(LWTable).forEach(function(key) {
plengthOptions += '<option value="' + key + '">' + key + ' in.</option>';
});
$('#plength').append(plengthOptions).change(function() {
var pwidthOptions = '';
LWTable[this.value].forEach(function(width, i) {
pwidthOptions += '<option value="Width' + (i + 1) + '">Width' + (i + 1) + ' (' + width + ')</option>';
});
$('#pwidth').html(pwidthOptions);
}).change();
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectname="plength"id="plength"></select><selectname="pwidth"id="pwidth"></select>
Solution 2:
You could try something like the following:
$(function(){
varLWTable = [];
LWTable.push([6,200,200,220]);
LWTable.push([8,220,220,240]);
LWTable.push([10,240,240,260]);
LWTable.push([12,260,260,290]);
LWTable.push([15,290,310,340]);
LWTable.push([18,330,360,400]);
LWTable.push([21,385,420,460]);
$("#plength").change(function(){
var ele = $(this)
var length = ele.val();
var widths = LWTable.find(function(item){
return item[0] == length;
});
if(widths){
var $pWidth = $("#pwidth");
$pWidth.empty();
$.each(widths.slice(1), function(key,value) {
var txt = 'Width'+(key+1)+' ('+value+')';
$pWidth.append($("<option></option>")
.attr("value", value)
.text(txt));
});
}
});
$("#plength").trigger("change");
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectname="plength"id="plength"><optionvalue="6"selected>6 in.</option><optionvalue="8">8 in.</option><optionvalue="10">10 in.</option><optionvalue="12">12 in.</option><optionvalue="15">15 in.</option><optionvalue="18">18 in.</option><optionvalue="21">21 in.</option></select><selectname="pwidth"id="pwidth"><optionvalue="Width1"selected>Width 1 (xw1x)</option><optionvalue="Width2">Width 2 (xw2x)</option><optionvalue="Width3">Width 3 (xw3x)</option></select>
Post a Comment for "Jquery Replace Value In Select Depending On Other Select Box"