简体   繁体   中英

How to create a new html element on radio button change event?

In my html form I have 3 radio button for user to choose a room type

<input type="radio" name="room" id="standard" class="left" checked>Standard&nbsp;&nbsp;&nbsp;           
<input type="radio" name="room" id="business" class="left">Business&nbsp;&nbsp;&nbsp;
<input type="radio" name="room" id="suite" class="left last">Suite<br>
<div id="select"></div>

In my js file I want it so that when the user change the radio button it will add or show/hide the corresponding select input

my js for this currently is:

$(":radio").change( () => {
        const radioButton = $(":radio:checked").val();
        if (radioButton == 'standard'){
            var label = '<label>Select number of bed: </label>';
            var option = '<select class=bed><option value="1">1</option><option value="2">2</option></select>'
            var html = '';
            $("#select").html('');
            html += label;
            for (i = 0; i < 2; i++) {
            html += option
            };

            $("#select").html(html);
        }
        else if(radioButton == 'business'){...}
                 

Nothing change when I change the radio option, I'm a beginner so I don't know what/where went wrong

Your radio buttons have no value attribute so when you check the value you will not match with any of your options

<input type="radio" name="room" id="standard" class="left" checked value="Standard">Standard&nbsp;&nbsp;&nbsp;           
<input type="radio" name="room" id="business" class="left" value="Business">Business&nbsp;&nbsp;&nbsp;
<input type="radio" name="room" id="suite" class="left last" value="Suite">Suite<br>

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