Ray
Ray

Reputation: 11

How to run Javascript in Wordpress Admin control panel?

I'm creating a WordPress plugin that returns the value of a select box when an admin selects a value from the select box in admin panel, however, it doesn't seem to work. The alert window doesn't pop up. Here's my HTML code.

<select id="sweets">
  <option>Chocolate</option>
  <option>Candy</option>
  <option>Taffy</option>
</select>
<div id="choice"></div>

Here's my code for the plugin.

<?php
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
function theme_name_scripts(){
    wp_register_script('selection', get_stylesheet_directory_uri() . '/js/selections.js', array('jquery') );
    wp_enqueue_script('selection');
}
?>

And lastly, here's my Javascript code.

jQuery(document).ready(function() {
    jQuery("#sweets").change(function() {
        var str = "";
        jQuery("select option:selected").each(function() {
            str += $(this).text() + " ";
        });
        jQuery( "#choice" ).text( str );
    }).change();
});

Thanks for your help.

Upvotes: 1

Views: 1238

Answers (1)

Scarecrow
Scarecrow

Reputation: 4137

admin_enqueue_scripts hook is the first action hooked into the wp admin scripts actions.

so you should use this

<?php add_action( 'admin_enqueue_scripts', 'theme_name_scripts' ); ?>

instead of

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

Upvotes: 1

Related Questions