简体   繁体   中英

How do I change select to input text while checkbox is checked?

It's my first contact with js so please don't hate me I have something like this:

 function Zmiana(isChecked) { document.getElementById('test').type = 'text'; }
 <div class="dropdown"> <select id="test" name="producent" class="dropdown-select"> <option value="Apple">Apple</option> <option value="Samsung">Samsung</option> <option value="Lenovo">Lenovo</option> </select> <br> </div>

But it doesn't work

You won't be changing the select into a textbox. Instead, you'll have both a select and a textbox. The checkbox will simply determine which is shown.

Also, your select should include a first choice that is not considered valid so that you don't get a submitted value that the user didn't choose.

 .hidden { display:none; }
 <input type="checkbox" id="check">Check to enter text directly <div class="dropdown"> <select id="test" name="producent" class="dropdown-select"> <option value="">--- Choose ---</option> <option value="Apple">Apple</option> <option value="Samsung">Samsung</option> <option value="Lenovo">Lenovo</option> </select> <input id="data" class="hidden"> </div> <script> let text = document.getElementById('data'); let check = document.getElementById("check"); let select = document.getElementById("test"); // You must set up your function to handle the // click event of the checkbox check.addEventListener("click", Zmiana); function Zmiana(){ // Add or remvoe the hidden class based on // whether it's already in use select.classList.toggle("hidden"); text.classList.toggle("hidden"); } </script>

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