0

I want to get the value of the selected item in dropdown in some variable and use it in my code. I want to use this data for another dropdown next to this list:

    <html>
         <head>
         <title>Home Page</title>
         <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">        
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
   </head>
        <body>
        <button id="mybtn">Emp Name</button>
        <div>
        <select id="output">    
         <script>
                 $('#mybtn').click(function () {
                 $.getJSON('empData', function (data) {
                 $("select#output > option").remove();
                 $.each(data, function (key, value) {
                 $("#output").append('<option>' + value['empId'] + " " + value['empName'] +'</option>');                 
                  });
                  });
                  }); 
            </script>
        </select>
        </div>
        </body>
            </html>
someone
  • 358
  • 1
  • 14
Dev
  • 23
  • 1
  • 4

2 Answers2

0

Vanilla JavaScript:

var o = document.getElementById("output");
var value = o.options[o.selectedIndex].value;
var text = o.options[o.selectedIndex].text;

jQuery:

$("#output:selected").text(); // The text content of the selected option
$("#output:selected").val(); // The value of the selected option
someone
  • 358
  • 1
  • 14
Rahul Singh
  • 690
  • 1
  • 5
  • 10
  • Can you please also tell me, how to display the selected value on the webpage. – Dev Jul 13 '20 at 05:47
  • This would be of help...https://stackoverflow.com/questions/40858456/how-to-display-a-javascript-var-in-html-body – Rahul Singh Jul 14 '20 at 13:37
0

If its multiple select drop down you have to push your selected values in an array and also when deselect you have to pop the value from an array.Then you can use that array in your another drop down.

use the below code to get the values asusal in drop down:

var select = document.getElementById('output');
var value = select.value;

this will gives you the selected values.

Harifrais
  • 47
  • 4
  • 18