I'm creating a custom widget that uses a select element with a bunch of options and a simple jQuery function to trigger the visibility for some <div>s below it based on the selection, through a jQuery's .change() event.

As you see below, this fails when the widget is saved. If I select another option, it works again.

The event is lost after save, or adding the widget

Here's the abbreviated code:

HTML view

<div class="widget-test">
        <select id="my-select" name="my-select" class="my-select">
            <option value="0">Select an option</option>
            <option value="1" selected="selected">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
    <div class="row one">
        <label for="option1">Option 1</label>
        <input name="option1" class="widefat" type="text" value="">
    <div class="row two">
        <label for="option2">Option 2</label>
        <input name="option2" class="widefat" type="text" value="">
    <div class="row three">
        <label for="option3">Option 3</label>
        <input name="option3" class="widefat" type="text" value="">


(function ($) {
    "use strict";
    $(function () {

        $('body').on('change', '#widgets-right select.my-select', function(){
                else if($(this).attr("value")=="2"){
                else if($(this).attr("value")=="3"){

I tried attaching the JS function to the widget-added and widget-updated events, without luck.

Any ideas on how to make the <div> visibility persistent after saving the widget, based on the selection?

1 Answer 1


The form reloads itself each time you save returning to the initial state where all are shown. What you can do is this:

// Getting the value of the selected field
var my_select_value = $('#widgets-right select.my-select').val();

// If there's no value selected, hide everything.
if(my_select_value == 0){
    $('.widget-test .row').hide();
// Otherwise, show the specific rows
if(my_select_value == 1){
    $('.widget-test .row').hide();
    $('.widget-test .row.one').show();
if(my_select_value == 2){
    $('.widget-test .row').hide();
    $('.widget-test .row.two').show();
if(my_select_value == 3){
    $('.widget-test .row').hide();
    $('.widget-test .row.three').show();

At the initial stage of the JavaScript.

  • Thanks @marcovega ! That worked fine. I just had to enclose this in the widget-updated and widget-added events. Jun 29, 2015 at 20:13
  • Glad it helped out buddy.
    – marcovega
    Jun 29, 2015 at 20:14

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.