I'm writing a small php page with 2 form:
<div class="input-field col s12">
<select id="select1">
<option value="" disabled selected>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select id="select2">
<option value="" disabled selected>Choose your option</option>
<option rel="1" value="11">Option 11</option>
<option rel="1" value="12">Option 12</option>
<option rel="2" value="21">Option 21</option>
<option rel="2" value="22">Option 22</option>
<option rel="3" value="31">Option 31</option>
<option rel="3" value="32">Option 32</option>
</select>
</div>
After I select the first select form, I want that only the related values are showed in the second.
My js is:
$(function() {
$("#select1").on('change', function() {
$subcat = $("#select2");
var _rel = $(this).val();
$subcat.find("[rel="+_rel+"]").show();
$subcat.prop("disabled",false);
// re-initialize material-select
$('#select2').material_select();
});
});
I also try with
var selectobject=document.getElementById("select2")
for (var i=0; i<selectobject.length; i++)
{
if (selectobject.options[i].value == 'xxxx' )
{
selectobject.remove(i);
}
}
But I need the name option, not the value.
$(function(){
$('#select1').on('change', function(){
var val = $(this).val();
var sub = $('#select2');
$('option', sub).filter(function(){
if ($(this).attr('rel') === val) {
if ($(this).parent('span').length) {
$(this).unwrap();
}
} else {
if (!$(this).parent('span').length) {
$(this).wrap( "<span>" ).parent().hide();
}
}
});
});
});
I don't see which options at the second form corresponding to the first, however, try populating the second select rather than removing items from it. like:
<select id="select1" onchange="myfunction(this.value)">
<script>
function myfunction(opt){
var $Select2 = $('#select2');
var option1 = [
{
"name": "option description",
"value": "1"
}, {
"name": "option description",
"value": "1"
}]
var option2 = [
{
"name": "option description",
"value": "1"
}, {
"name": "option description",
"value": "1"
}]
if(opt === option1){
$.each(option1, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.name
}));
});
}
if(opt === option2){
$.each(option2, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.name
}));
});
}
}
</script>