Reputation: 549
I need to remove all of the options in a dropdown that don't have a specific value. Here's my code: `
<select name="worker">
<option value="0">John Doe</option>
<option value="5">Jim Smith</option>
<option value="6">Jane Doe</option>
</select>
`
I'm in wordpress, and basically need to say, "If the current user is 5 (Jim Smith), then only show him in the dropdown. Any help would be greatly appreciated.
Here is the php code that generates the dropdown:
/* Workers */
$workers = $wpdb->get_results("SELECT * FROM " . $this->workers_table . " " );
$html .= '<label>';
$html .= '<span class="title">'.__('Provider', 'appointments'). '</span>';
$html .= '<select name="worker">';
// Always add an "Our staff" field
$html .= '<option value="0">'. __('No specific provider', 'appointments') . '</option>';
if ( $workers ) {
foreach ( $workers as $worker ) {
if ( $app->worker == $worker->ID ) {
$sel = ' selected="selected"';
}
else
$sel = '';
$html .= '<option value="'.$worker->ID.'"'.$sel.'>'. $this->get_worker_name( $worker->ID, false ) . '</option>';
}
}
$html .= '</select>';
$html .= '</label>';
Upvotes: 1
Views: 3872
Reputation: 144689
In case that you are not using jQuery, you can use querySelector()
for selecting the select element and .removeChild()
for removing the dirty option
elements.
var userId = 5;
[].slice.call( document.querySelector('select[name="worker"]').children )
.forEach(function(elem) {
if ( elem.value != userId )
elem.parentNode.removeChild(elem);
});
Upvotes: 2
Reputation: 22619
You can use jquery remove()
method to remove all the item which is not matching a certain value using attribute not equal selector
var removeItemVal="5";
$('#selectId').find('option[value!="'+removeItemVal+'"]').remove();
Upvotes: 4