1

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>'; 
5
  • do you need something bulletproof, or will Javascript suffice? Commented Jan 9, 2014 at 14:08
  • "If the current user is 5 (Jim Smith), then only show him in the dropdown" Well, how do you know current user? Commented Jan 9, 2014 at 14:11
  • I'd have to use the wordpress get_current_user_id() function and assign it to a jquery variable Commented Jan 9, 2014 at 14:46
  • Do you prefer to manipulate the dropdown server side before sending it to the browser? And if so, can you show the piece of code where that dropdown is generated? Commented Jan 9, 2014 at 15:04
  • I just added the portion of the code that generates that drop down Commented Jan 9, 2014 at 15:12

2 Answers 2

4

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(); 

JSFIDDLE DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

This is opposite of what OP is trying to do :)
2

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); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.