dimanche 24 mai 2020

Add "other"-input to HTML-Form-checkbox using javascript

I wanted a checkbox with an adjacent text input where the user can specify an "other"-option. As it took me a while and I did not find anything usesful on this topic I just want to share my solution:

HTML (using bootstrap.css):

<input class="form-check-inline" type="checkbox" id="checkbox1.1" value="Other: ">
<label class="form-check-label" for="checkbox1.1">Other: </li></label>
<input class="input-sm" type="text" id="checkbox1.1.text" onkeyup="checkValueOther('checkbox1.1')">

and javascript:

function checkValueOther(elem) {        
    document.getElementById(elem).value = "Other: " + document.getElementById(elem + ".text").value;
    document.getElementById(elem).checked = true;   
}

If you know a more elegant solution, let me know.

Pat




Aucun commentaire:

Enregistrer un commentaire