Skip to content

how to remove attribute selected from all selected options in select in jquery

I’m not remove attribute selected from all selected options in jquery.

Please help me.

My html code is :

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js">
$('#commentform .comment-form-rating input#dap_rating').change(function () {
$('#commentform .comment-form-rating #rating option').on('change',function() {
   alert("nb = "+$(this).find(":selected").length);
});
$("#commentform .comment-form-rating #rating option:selected").removeAttr("selected");
$("#commentform .comment-form-rating #rating option:selected").prop("selected", false);
$("#commentform .comment-form-rating #rating > option:selected").each(function() {
});
$(document.body).on('change', '#commentform .comment-form-rating #rating', function () {
var c = $('#commentform .comment-form-rating #rating').filter((i, s) => $(s)[0].selectedIndex > 0).length;
console.log(c);
});
$('#mySelect option:selected').removeAttr('selected');
});
</script>
<select name="rating" id="rating" required="" style="display: none;">
    <option value="0" selected="selected">رای دهید</option>
    <option value="5" selected="selected">عالی</option>
    <option value="4" selected="selected">خوب</option>
    <option value="3">متوسط</option>
    <option value="2" selected="selected">نه خیلی بد</option>
    <option value="1">خیلی بد</option>
</select>

and all the top ways not working.

selected options length return only 1. i’m not to do select all selected options to remove attribute selected.

tank’s all.

Answer

Just use removeAttr() for all options:

$('#rating option').removeAttr('selected');

console.log($('#rating').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="rating" id="rating" required="">
    <option value="0" selected="selected">رای دهید</option>
    <option value="5" selected="selected">عالی</option>
    <option value="4" selected="selected">خوب</option>
    <option value="3">متوسط</option>
    <option value="2" selected="selected">نه خیلی بد</option>
    <option value="1">خیلی بد</option>
</select>