简体   繁体   中英

How do i add to this function a if #anders checkbox = checked, remove class hidden to show <textarea #otherInput and remove it when unchecked?

How do i add to this function a if #anders checkbox = checked, remove class hidden to show

 function persistProfessions(checkboxes) { if (checkboxes.length) { $('#category-professions-error').css('display', 'none'); var professions = []; checkboxes.each(function() { professions.push(this.value); }); container.professions = professions; } else { container.professions = []; $('#category-professions-error').css('display', 'block'); } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-6 category-checkbox"> <input id="anders" type="checkbox" name="profession" value="Anders" class="andersCheckbox"> <label class="LBN3" for="anders">Anders, namelijk ...</label> </div> <textarea id="otherInput" class="mt-2 hidden" rows="1" cols="50" name="Ander vakgebied" value="" placeholder="Typ hier uw antwoord"></textarea> 

window.addEventListener("DOMContentLoaded", function () {
    let andersCheckbox = document.getElementById("anders");

    andersCheckbox.addEventListener( 'change', function() {
        let textArea = document.getElementById("otherInput");
        textArea.classList.toggle('hidden')
    });
}, false);

You can add an event listener to the input tag to detect when the value changes. When the value changes, you want to check if it is checked or not, and add/remove the class there. You can do it by doing

$("#anders").change(function() {
    if ($("#anders").is(":checked")) {
      $("otherInput").addClass("hidden");
    } else {
      $("otherInput").removeClass("hidden");
    }
}

or if you know that the checkbox will start being unchecked, and the textarea will start with hidden (or if the checkbox starts being checked and the textarea starts without the class "hidden"), you can simplify it to

$("#anders").change(function() {
    $("otherInput").toggelClass("hidden");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM