Search code examples
javascriptjqueryjavaquery

Jquery code, clicking on radio button selects an option


Hello Im new to Html/Java(script/query)/css, around half year.
I have few question.
Right now Im trying to make a function/code that doing this:I have 2 radio buttons.
clicking on the 1st radio button selects the 1st option, and removing the others.
while clicking on the 2nd radio buttons open up the other options and removing the first option that dedicating it self to the first radio button.

<form  enctype="multipart/form-data">
    <fieldset>
        <legend>מפרט טכני של הסמארטפון:</legend>
        <label for="memory">זיכרון פנימי:</label>
        <input id="less1" type="radio" value="less" name="memory" onclick="(myFun())" /> פחות מ 1GB
        <input id="more1" type="radio" value="more" name="memory" onclick="(myFun1())" />מעל 1GB
        <br />
        <label for="extra">אפשרות להרחבת זיכרון:</label>
        <br />
        <select size="5" id="sel">
            <option name="extra" value="no1" id="no">לא</option>
            <option name="extra" value="yes8">כן,8GB</option>
            <option name="extra" value="yes16">כן,16GB</option>
            <option name="extra" value="yes32">כן,32GB</option>
            <option name="extra" value="yes64">כן,64GB</option>
        </select>
        </fieldset>
</form>

        function myFun() {
        $("#sel").prop('size', "1")
        select('option', $("no")).select('option:not(:selected)').remove()         
    }
    function myFun1() {
        $("#sel").prop('size',"4")
    }

I have checke another topic here and it helpd me little bit (jQuery on change only shows the selected option, remove/disable rest of them)


Solution

  • That's the code that does what you want. I removed the select() event because that event is triggered when the text is selected using the mouse.

    It's better to hide/show the elements instead remove them.

    function myFun() {
    
        // 1. Find the first option and set as selected
        $("#sel").find('option').first().prop("selected",true)
        // 2. Find its not selected siblings and hide it
        .siblings('option:not(:selected)').hide();
    
        // 3. The first radio button is selected, so show the first option
        $("#no").show();
    
    }
    
    function myFun1() {
    
        // 1. Find the last option, set as selected and show it
        $("#sel").find('option').last().prop("selected",true).show()
        // 2. Find its siblings and show them
        .siblings('option:not(:selected)').show();
    
        // 3. Hide the first option
        $("#no").hide();
    
    }