0

I'm trying to achive this thing in wordpress wiget admin panel : http://jsfiddle.net/George02/mkuxcwf5/1/

The problem is that the jQuery seems to not work .

public function form( $instance ) { ?>
<?php
wp_register_script('customscript', get_template_directory_uri() . '/widgets/custom_widget/widget.js', array('jquery'), null, true);
wp_enqueue_script('customscript');
?>
<div id="wrapper">
    <ul id="category-list">

    </ul>
    <div id="add-category">
        <select id="categories">
            <option>Option 1</option>
            <option>Option 2</option>
        </select>
        <div id="btn-add">Add category</div>
    </div>
</div>

<?php }

widget.js contains the code from the fiddle. If I View Source of the page It's seems that the script is there, in the head section, and if I open up the console I can see the log from document ready function . I think the problem is that wordpress doesn't allow me to add items into DOM, because when I inspect the $list element I can see that he has a <li> inside it.I'm right or it's something else?

2
  • If you have more than 1 of those widgets you'll have multiple clashing IDs, also can we see your widget.js in full?
    – Tom J Nowell
    Aug 29, 2014 at 12:07
  • After changing all <div id=""> with <div class=""> seems that the script is working, but has a inexplicable problem. When I do $('.category-list').append(newCategoryHTML); a new jQuery object is created, so when I log $('.category-list') I can see in the console 2 <ul> tags. What about this ? Aug 30, 2014 at 5:41

1 Answer 1

0

So here is what's happen :

When you create a widget and init it in functions.php he will be placed, with all it's content(that means the html from public function form( $instance )), into <div id="widget-list"> (the area from the left of the admin panel which list all the widgets). So when you will drag it onto the widget area you will have 2 of them on the admin panel. One placed into <div id="widget-list"> and one into <div id="widget-area">. So your jQuery script need to work only with the widget from the widget area, for that you will need to have something like $("#widget-area .another-selector") in your script .

Another thing that it can be easily understand from what I wrote above is that all your divs (elements) must have classes and not ids.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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