I have an annoying problem where I have a jQuery selecting the various options of a SELECT option list. I want to set the SELECTED=SELECTED attribute to force something other than the first item to be the default.
Seems pretty basic, and if I set other characteristics of the OPTION tag it works fine. For instance:
$(this).addClass ('TEST');
works as you'd expect by adding the TEST class to what should be the default option. I also can do the following:
$(this).attr('annoying', "SELECTED");
This adds the attribute "annoying" with the value of "SELECTED. Sadly if I do the following:
$(this).attr('SELECTED', "SELECTED");
it just completely ignores it. If I go into Chrome's debugger and punch this in manually it does work but not from my JS file. :^(
Any ideas?
UPDATE Great suggestions so far but as nothings working I suspect something else is amiss. To provide further context ... this is a Wordpress site and I'm making the QuickEdit function bring up the right OPTION in a custom attribute to a taxonomy. For those of you who don't know Wordpress its probably not important (who knows at this stage).
Here's the full code:
jQuery(document).ready(
function ($) {
$('.editinline').on ('click',
function () {
var $data_ref = $(this).closest('tr');
$('.bespoke-item.quick-edit').each (
function () {
var col_name = $(this).attr('name');
var col_value = $data_ref.find ('.' + col_name).text();
$(this).val(col_value); // this will work for non-enumerated widgets
if ( $(this).is( "select" ) ) {
selected = false; // used as a flag on whether the SELECTED value has been found
options = $(this).find ('.select-option');
options.each(
function () {
if ( $(this).attr('value') == col_value ) {
$(this).addClass ('TEST');
selected = true;
$(this).attr('SELECTED', "SELECTED");
this.selected = 'SELECTED';
}
}
);
if ( !selected ) {
// The value of the did not match any of the selections (this likely means it wasn't set at all)
// In this case revert to the "static-default" setting
options.each(
function () {
if ( $(this).attr('static-default') ) {
$(this).attr ('SELECTED' , 'SELECTED');
alert ("Found value in static default " + $(this).val());
selected = true;
} else {
$(this).removeAttr ( 'SELECTED' );
}
}
);
}
}
}
);
}
);
});