Can someone help me correct this code. I need value attribute for some other purpose. I need the form to post both the category id and subcategory id.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var $optgroups = $('#subcategory > optgroup');
$("#category").on("change",function(){
var selectedVal = $(this).data('role');
$('#subcategory').html($optgroups.filter('[label="'+selectedVal+'"]'));
});
});
</script>
<select id="category">
<option value="1" data-role="Fashion">Fashion</option>
<option value="2" data-role="Electronics">Electronics</option>
</select>
<select name="subcategory" id="subcategory">
<optgroup label="Fashion">
<option value="Men's wear">Men's wear</option>
<option value="Women's wear">Women's wear</option>
</optgroup>
<optgroup label="Electronics">
<option value="Television">Television</option>
<option value="Game Console">Game Console</option>
</optgroup>
</select>
2
Answers
this
refers to the SELECT element itself which does not have the attributedata
you are looking for. You need to get the attribute from selected option:Change:
To:
Example Code:
The only thing you are missing to have ID for both category and subcategory is a name attribute on the
<select>
.Here is a vanilla JavaScript example.