You need to get the value of the select
element, not its selected option
:
$('.add_attribute').on('click', function () {
var selected = $('#attribute_taxonomy');
alert(selected.val());
});
JS Fiddle demo.
I'd also tend to prevent the user interacting with the button
until a choice is made in the select
element (using the disabled
(Boolean) property) and then, once a choice is made, prevent the user from reselecting what appears to be an option
label (note this is more complicated than it needs to be, a possibly improved approach will follow). First, the HTML:
<!-- select element unchanged -->
<button type="button" class="button button-primary add_attribute" disabled>Add</button>
jQuery:
$('#attribute_taxonomy').on('change', function(){
// cache the $(this) jQuery object since we're potentially using it twice:
var $this = $(this);
// if there are no disabled options we run the following jQuery:
if (!$this.find('option:disabled').length) {
$this
// find the option that has no value set:
.find('option[value=""]')
// set its 'disabled' property to true (to disable it)
.prop('disabled', true)
// go back to the original selector ($(this))
.end()
// move to the next element (if it's a button element):
.next()
// unset its 'disabled' property (to enable it):
.prop('disabled',false);
}
});
$('.add_attribute').on('click', function () {
var selected = $('#attribute_taxonomy');
alert(selected.val());
});
JS Fiddle demo.
A slightly better approach (to my mind) is to use HTML, and its elements, properly; using an optgroup
to associate the relevant option
elements, with a label
attribute set to explain the contents of that group:
<select name="attribute_taxonomy" id="attribute_taxonomy" class="attribute_taxonomy">
<optgroup label="Custom product attribute">
<option value="pa_bedroom">Bedroom</option>
<option value="pa_bathroom">Bathroom</option>
</optgroup>
</select>
JS Fiddle demo.
This approach means that an option, with a value, is always set (though initially to a default unless one of those option
s is given a selected
attribute), which means the button
doesn't need to have its disabled
property set/unset to prevent accidentally choosing an option
without a value.
References: