Search code examples
jqueryajaxdropdownbox

Calling a function to show text on select change


I want to call a jQuery function to show this text (Dropdown):

<select name="filter" data-userid="3" onchange="getPoints(this.value)">
    <option value="one">One</option>
    <option value="two">Two</option>
</select>";

My query should looks like this:

function getFilterOption() {
    $(this).html(Dropdown)
    success: function(result){
        $("#Target").html(result);
    }
};

How can I do that? I just want to show the dropdown (Beginners question)


Solution

  • Just a little tip, it would be a good idea to get away from using the inline code which you're using to do the onChange. You're using JQuery so use it's ability of doing the check for changes of dropdown.

    Here an idea of what you can do:

    (This is if the select box isn't already added to page, you append it to the page)

    $( document ).ready(function() 
    {
         getFilterOption();
      
         $(document).on('change', "select[name*='filter']" ,function() 
         {
           getPoints(this.value);
         });
    });
    
    function getPoints(result) 
    {
       $("#Target").text(result);
    };
    
    function getFilterOption() 
    {
       $("#filterWrapper").append('<select name="filter" data-userid="3"><option value="one">One</option><option value="two">Two</option></select>');
    };
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <div id="Target">PlaceHolder Text</div>
    
    <div id="filterWrapper">
    
    </div>