Reputation: 10256
I have a div that contains many classes. If the the div is clicked on and one of it's classes matches the value any option in the select box, i want that option to be selected.
<div class="abc cdf fff r10 yyy">
<select id="whatever">
<option value="r10">test10</option>
<option value="r20">test20</option>
<option value="r30">test30</option>
</select>
How do i achieve this with JavaScript or jQuery I tried the following but can't get it to work.
var roundclasses = $(this).attr('class').split(/\s/); //This outputs the array of classes sucessfully
for (var i in roundclasses){
$('#whatever').val(roundclasses[i]);
}
Upvotes: 0
Views: 339
Reputation: 8566
Here is the JSBin snippet.
HTML:
<div id="clickDiv" class="abc cdf fff r30 yyy">
<p>CLICK</p>
</div>
<select id="whatever">
<option value="r10">test10</option>
<option value="r20">test20</option>
<option value="r30">test30</option>
</select>
JS (using jQuery):
var div = $("#clickDiv");
var sel = $("#whatever");
var options = $("#whatever option");
div.click(function() {
options.each(function(index, e) {
if (div.hasClass(e.value)) {
sel.val(e.value);
}
});
});
EDIT:
Created a JSBin with shorter solution - HERE
var div = $("#clickDiv");
var options = $("#whatever option");
div.click(function() {
options.attr('selected', function() {
return div.hasClass(this.value);
});
});
Upvotes: 1
Reputation: 21466
Here is the jsFiddle.
HTML:
<div id="clickme" class="abc cdf fff r10 yyy">Click Me</div>
<br>
<br>
<select multiple="true" id="dd">
<option value="r1">test1 (r1)</option>
<option value="r2">test2 (r2)</option>
<option value="r2">test3 (cdf)</option>
<option value="yyy">test4 (yyy)</option>
<option value="r10">test9 (r10)</option>
<option value="r10">test10 (r10)</option>
</select>
CSS:
#clickme {
background: #FF0000;
color: #FFF;
font: 14px Arial, sans-serif;
height: 100px;
line-height: 100px;
text-align: center;
width: 100px;
}
JS:
var $dd = $("#dd"),
$dd_opts = $dd.find('option');
$("#clickme").click(function() {
var classes = $(this).attr('class').split(' '),
class_len = classes.length;
$dd.val('');
for (x = 0, class_len = classes.length; x < class_len; x++) {
var cls = classes[x],
$opts = $dd_opts.filter('[value="'+ cls +'"]');
$opts.attr('selected', 'selected');
}
});
Upvotes: 1