iam trying to achieve this exact functionalty: http://jsfiddle.net/exttq/ BUT inside using my PHP, right now its displaying 2 checkboxes and 2 forms, BUT what I need is: those 2 forms shouldnt be visible unless I check any box..
so, please check whats wrong in below code…
function eshop_extras_checkout($echo){
$echo .= '
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(".formGroup").hide();
$("#chooseForm input:checkbox").on("change", function() {
if($(this).is(":checked")) {
$("#" + $(this).val()).show();
}
else {
$("#" + $(this).val()).hide();
}
});
</script>';
$echo .= '<fieldset class="eshop eshop_extra">' . "\n";
$echo .= ' <form id="chooseForm">
<input type="checkbox" name="form1" value="form1"> Form1<br>
<input type="checkbox" name="form1" value="form2"> Form2<br>
</form>
<form id="form1" class="formGroup">
<h2>FORM 1</h2>
<label>Name</label><input type="text"> <br>
<label>Address</label><input type="text">
</form>
<form id="form2" class="formGroup">
<h2>FORM 2</h2>
<label>Username</label><input type="text"> <br>
</form>';
$echo .= '<legend>Articles Order Form</legend>' . "\n";
return $echo;
}
waiitng for your replies…
The problem is that your script executes before the elements are present in the DOM. See:
Your fiddle’s JS is set to use the
onDomReadywrapper, that’s why it works properly there.You can put the script below the form’s HTML, and/or simply wrap the script contents inside a DOM ready handler:
One of jQuery’s best practices to always wrap your code in a DOM ready handler, that is:
or the much shorter shorthand:
Both have the same effect, they prevent the code from executing until the DOM is ready.
Another JavaScript best practice is to put the JS code in the footer of the page (right before the
</body>), this way scripts loading won’t block the page rendering and when the DOM parser reaches the scripts, your DOM will be already ready for them.Both best practices above are combinable. Nevertheless, simply using the DOM ready handler will solve the issue, as well as moving the scripts to below the form HTML will also suffice.
Your framework is already loading another copy of jQuery in
noConflictmode, that means you can’t use the$alias in the global scope. To remedy that, you can use this special DOM ready syntax, which will alias jQuery back to$inside its scope:More info on that from the DOM ready handler docs – Aliasing the jQuery Namespace: