Note that there are some explanatory texts on larger screens.

plurals
  1. POToggle Corresponding Text Input on Checkbox Change
    text
    copied!<p>I have an array of checkboxes that need to display an input when their state is <code>:checked</code>.</p> <p>The checkboxes have different ID's than their corresponding text inputs obviously, so i've attempted to use <code>.replace</code> to edit the variable i've set in order to target their corresponding input.</p> <p>The checkbox parent id's are structured as <code>icon-metro-NAME</code> and the text inputs as 'input-NAME`.</p> <p>Here is my code in sections, and then the entire code after:</p> <pre><code>jQuery('input[type="checkbox"]').each(function () { var checkbox = jQuery(this); var checkboxParentID = jQuery(this).parent().attr('id'); var inputName = checkboxParentClass.replace(icon-metro, 'input'); </code></pre> <p>Attempting to set the <code>input[type="checkbox"]</code> as <code>this</code> and then find it's parent element ID and set it as <code>checkboxParentID</code>. Then I take <code>checkboxParentID</code> and replace <code>icon-metro</code> with <code>input</code> in order to target the corresponding text input field.</p> <pre><code>checkbox.change(function () { if (jQuery(this).is(":checked")) { jQuery(this).parent('.metro-icon').addClass('active'); jQuery(inputName).toggle('slow'); } else { jQuery(this).parent('.metro-icon').removeClass('active'); jQuery(inputName).toggle('slow'); } }); }); </code></pre> <p>I then detect the <code>:checked</code> state of the checkboxes and IF it is checked, I add an <code>active</code> class to it's parent <code>.metro-icon</code> element. After that I find <code>:checked</code> elements corresponding text input <code>inputName</code> from my variable and toggle it's visibility. Otherwise, if it is not checked, I remove the <code>active</code> class from it's parent and toggle/hide the corresponding text input.</p> <p>Full code:</p> <pre><code>jQuery('input[type="checkbox"]').each(function () { var checkbox = jQuery(this); var checkboxParentID = jQuery(this).parent().attr('id'); var inputName = checkboxParentClass.replace(icon-metro, 'input'); checkbox.change(function () { if (jQuery(this).is(":checked")) { jQuery(this).parent('.metro-icon').addClass('active'); jQuery(inputName).toggle('slow'); } else { jQuery(this).parent('.metro-icon').removeClass('active'); jQuery(inputName).toggle('slow'); } }); }); </code></pre> <p>I realize it is probably a mess. I am challenging myself to get more advanced with jQuery.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload