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.
Here's the abbreviated code:
HTML view
<div class="widget-test">
<div>
<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>
</select>
</div>
<div class="row one">
<label for="option1">Option 1</label>
<input name="option1" class="widefat" type="text" value="">
</div>
<div class="row two">
<label for="option2">Option 2</label>
<input name="option2" class="widefat" type="text" value="">
</div>
<div class="row three">
<label for="option3">Option 3</label>
<input name="option3" class="widefat" type="text" value="">
</div>
</div>
JS
(function ($) {
"use strict";
$(function () {
$('body').on('change', '#widgets-right select.my-select', function(){
$(this).find("option:selected").each(function(){
if($(this).attr("value")=="1"){
$(".row").not(".one").hide();
$(".one").show();
}
else if($(this).attr("value")=="2"){
$(".row").not(".two").hide();
$(".two").show();
}
else if($(this).attr("value")=="3"){
$(".row").not(".three").hide();
$(".three").show();
}
else{
$(".row").hide();
}
});
}).change();
});
}(jQuery));
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?