jQuery finding dropdown with max selected “rel” attribute
문제
I have a bunch (the exact number may vary) of dropdowns with this code:
<div id="wrapf">
<div class="dropf">
<select name="number" id="number" class="options">
<option value="" rel="">Choose option!</option>
<option value="1" rel="20">Option 1</option>
<option value="2" rel="30">Option 2</option>
<option value="3" rel="40">Option 3</option>
</select>
</div>
</div>
I'm trying to set up a function where if I have 2 (or more) of these dropdowns showing, with different selected values, I can highlight the dropdown that has the selected option with the highest rel
attribute... I will add the class .highlight
to the #wrapf
that contains the dropdown with the largest rel
.... I have this so far:
Highlight CSS
.highlight {
box-shadow: 0px 0px 15px rgba(255, 40, 50, 0.4);
-webkit-box-shadow: 0px 0px 15px rgba(255, 40, 50, 0.4);
background: rgba(255, 40, 50, 0.4);
}
This is the jQuery:
$("#getMax").click(function () {
var values = $.map($(".options"), function(el, index) {
return parseInt($(el).find('option:selected').attr('rel'));
});
var max = Math.max.apply(null, values);
var opt = "[rel=" + max + "]";
//doesn't work :(
$('#wrapf').find('option:selected').attr(opt).addClass('highlight');
});
I think I'm close, just need the final function to .addClass('highlight')
!
해결책
$("#getMax").click(function (e) {
var values = $.map($(".options"), function(el, index) {
return $(el).find('option:selected').attr('rel');
// parseInt() was originally creating a problem as [] turned into NaN
});
var max = Math.max.apply(null, values);
//works :)
$('.wrapf').removeClass('highlight'); // remove all other references of highlight
$('.wrapf').find('select option:selected[rel="' + max + '"]').closest('.wrapf').addClass('highlight');
e.preventDefault(); // stops anchor from happening
});
제휴하지 않습니다 StackOverflow