I want to toggle an input via a checkbox. Here’s the code:
css:
.moveaway{ position:absolute;top:-999rem;}
html
<p>
<label><?php _e('Setup Template')?></label>
<input class="check-toggle" name="toggle" type="checkbox" value="1" <?php echo $template ? 'checked="checked' : '';?> />
</p>
<p id="template-input" class="<?php echo $template ? '' : 'moveaway'?>">
<lable for="template-name">Template Name</lable>
<input id="template-name" type="text" name="template-name" value="<?php echo $tamplate; ?>" />
</p>
javascript:
$("input.check-toggle").change(function() {
if ($(this).is(':checked')) {
$("p#template-input").attr('class','');
}else{
$("p#template-input").attr('class','moveaway');
$("input#template-name").val(0);
}
});
The above code works when the template-name input field is empty. When the template-name field value is set, the wrapper p#template-input gets merged in to the p which contains the check-toggle input.
I don’t understand how the change function made this. I would like to learn how to get the result that the p#template-input can be toggled by the checkbox.
I’ve made some changes in your code and it works.
Look the demo.
So first I’ve changed the
<p>to<div>, it is better to change position from blocks then inline ones, but you can still change it’s property on CSS, to keep usingpor fromdivto still in the line, even put inside thep.Then for class I’ve used the
addClassandremoveClass, is better then change it attributes.It worked as you see in the demo the template-input.
Like my comment earlier, the cached method:
Will run even fast, and the result is same. You can see the demo here.