Search code examples
alertdropdown

read variable from dropdown function in javascript


i am using this dropdown in html file:

<select id="read-type"  onchange="checkrt()">                           
                    <option value="1">2word</option>                    
                    <option value="2">3word</option>
                    <option value="3">line</option>
                    </select>
            </div>

and read it by:

var dro = document.getElementById("read-type");
var readtype = dro.options[dro.selectedIndex].value;

but this code can't read "onchange" or i don't now how?, so i change the code to:

$(function checkrt(){
    $('#read-type').on('change', function(){        
        window.readtype = $(this).val();
        alert(readtype);
    });
})

the last code work good with "alert", but i can't read the the variable "readtype" in the next function by:

    Function delta(text){
if (readtype == 1) 

this give me msg (un define readtype)?, please what th problem.

note: the code can get readtype if i clicked on "refresh" button in the browser after i change the selected item in dropdown.

  • the code in app.js not in html.

Solution

  • You don't need a named function to contain the onchange trigger. To get access to the value, you'll have to pass readtype into your next function.

    Change your code to this:

    $(function(){
        $('#read-type').on('change', function(){        
            var readtype = $(this).val();
            nextFunction(readtype);
        });
    
        function nextFunction(readtype){
            if (readtype == 1) {
                alert(readtype);
            }
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="read-type">
        <option value="1">2word</option>
        <option value="2">3word</option>
        <option value="3">line</option>
    </select>