Reputation: 1052
How can I transform the following jQuery code to working JavaScript code?
jQuery
$('select :visible:selected').each(function(i) {
// instructions
}
The visible selector I've already implemented with JS. Or is there a better solution?
JavaScript
for (var i=0;i<$('select').length;i++) {
if ($('select')[i].style.visibility == "visible") {
// instructions
}
}
Thanks for your help!
Upvotes: 1
Views: 333
Reputation: 2861
Selected takes selected OPTION from SELECT list. So to get all selected options from all visible SELECTs from the page with pure JavaScript
var selects = document.getElementsByTagName('select');
for(var i=0; i<selects.length; i++) {
var select = selects[i];
if(select.style.visibility == 'visible'){
for(var j=0; j<select.options.length; j++) {
if(select.options[j].selected){
// ... your code goes here ..
}
}
}
}
UPDATE So if I undestand you corectly you need all selected OPTIONS from ALL visible SELECTs and you CAN use jQuery
$('select:visible option:selected').each(function(i,elm) {
// instructions
alert(elm.value);
});
Upvotes: 4
Reputation: 51807
iQuery is javascript, so the "jQuery code" is working JavaScript code.
additionally, the fact that you're using in your second example, too ($('select')
) makes me wonder why you don't just simply use your first one.
if you don't want to use jQuery and stick to "plain" javascript instead, it should look like this:
var elements = document.getElementsByTagName('select');
for (var i=0;i<elements.length;i++) {
var element = elements[i];
// use:
element.style.visibility // to check for visibility
element.selectedIndex // to check if/what option is selected (-1 = no selection)
// a 'select' doesn't have a 'selected' property
// because it's the <option> that gets selected
// so we end up:
if (element.style.visibility == "visible" && element.selectedIndex >= 0) {
// instructions
}
}
more information about selectedindex and selected
Upvotes: 3