I have list of selection, and I need value of that option. I have coded as below:
HTML code:
<select >
<option value="all_section" data-id="rid0">All Section</option>
<option value="id1" data-id="rid1">Section 1</option>
<option value="id2" data-id="rid2">Section 2</option>
</select>
<select >
<option value="all_section" data-id="rid0">All Section</option>
<option value="id3" data-id="rid3">Section 3</option>
<option value="id4" data-id="rid4">Section 4</option>
</select>
<select >
<option value="all_section" data-id="rid0">All Section</option>
<option value="id5" data-id="rid5">Section 5</option>
<option value="id6" data-id="rid6">Section 6</option>
</select>
Jquery code :
$(document).on("change",".sectionSelect",()=>{
let section_id = $(this).children(":selected").val();
let room_id = [value of 'data-id' attribute of that option]
console.log(section_id);
console.log(room_id);
})
Here, sectionSelect is common class for them all, I have applied on change event on them to detect change. Problem is that I'm getting this object but not able get value of that option.
And one more problem is I also need data-id attribute value of that option.
please help me
CodePudding user response:
You can do it like this:
$(document).on("change", ".sectionSelect", function() {
var selectedOption = $("option:selected", this);
let section_id = selectedOption.val();
let room_id = selectedOption.attr("data-id");
console.log(section_id);
console.log(room_id);
})
This will give you both the Id
and data-id
of the selected option.
demo
$(document).on("change", ".sectionSelect", function() {
var selectedOption = $("option:selected", this);
let section_id = selectedOption.val();
let room_id = selectedOption.attr("data-id");
console.log(section_id);
console.log(room_id);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select >
<option value="all_section" data-id="rid0">All Section</option>
<option value="id1" data-id="rid1">Section 1</option>
<option value="id2" data-id="rid2">Section 2</option>
</select>
<select >
<option value="all_section" data-id="rid0">All Section</option>
<option value="id3" data-id="rid3">Section 3</option>
<option value="id4" data-id="rid4">Section 4</option>
</select>
<select >
<option value="all_section" data-id="rid0">All Section</option>
<option value="id5" data-id="rid5">Section 5</option>
<option value="id6" data-id="rid6">Section 6</option>
</select>
CodePudding user response:
Hey please send the HTML code.