0

I am using wp_dropdown_categories to create a dropdown in the frontend. It creates a nice dropdown select. Now I would like to add onchange="myFunc()" to the <select>. I need this to trigger some js function when someone selects specific option.

I also took a look into another relevant codex link, could not figure it out. Is there a native wordpress way of doing this ? If not, can you suggest me a solution. I mean something like this.

<select id="my_cats" class="postform" name="my_cats" onchange="myFunc()">
1

you can add any attribute to <select> using wordpress filter wp_dropdown_cats . wp_dropdown_cats filter allows you to modify the content of the taxonomy drop-down output. Try below code.

function addAttributeToDropdown($html_content){
  $html_content = str_replace('<select','<select onchange="myFunc()"',$html_content);
  return $html_content; 
}

add_filter('wp_dropdown_cats','addAttributeToDropdown');

add this inside your functions.php file

1

Use JQuery change method

$('#my_cats').on('change', function() {
  myFunc();
});

function myFunc() {
     // your function code
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.