262

I am a novice at JavaScript and jQuery. I want to show one combobox-A, which is an HTML <select> with its selected id and contents at the other place on onChange().

How can I pass the complete combobox with its select id, and how can I pass other parameters on fire of the onChange event?

Mark
  • 2,961
  • 1
  • 16
  • 24
Gendaful
  • 5,522
  • 11
  • 57
  • 76

17 Answers17

492

function getComboA(selectObject) {
  var value = selectObject.value;  
  console.log(value);
}
<select id="comboA" onchange="getComboA(this)">
  <option value="">Select combo</option>
  <option value="Value1">Text1</option>
  <option value="Value2">Text2</option>
  <option value="Value3">Text3</option>
</select>

The above example gets you the selected value of combo box on OnChange event.

A. Meshu
  • 4,053
  • 2
  • 20
  • 34
Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56
  • Thanks, this has worked for me. Basically I want to show the same combobox at different place,so i gave 2 different ids to 2 combobox.Is there anyway, that i can show the same combobox at different place. Any help will be greatly appreciated. – Gendaful Feb 17 '11 at 15:50
  • 14
    A more succinct way to retrieve the value inside `getComboA()` is `var value = sel.value;` – Yony Sep 13 '12 at 01:37
  • 4
    The change event fires only if the select box loses focus. Is there a way to fire the event immediately after a value changes? – doABarrelRoll721 Feb 19 '16 at 18:42
  • 3
    use this.value instead and it will work =) sending this is sending the whole select element – Colin Rickels Oct 28 '16 at 12:58
  • For my case, code is working on Firefox but not on Chrome. – avijit Jan 10 '20 at 21:00
74

Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:

function myFunction(chosen) {
  console.log(chosen);
}
<select onChange="myFunction(this.options[this.selectedIndex].value)">
  <option value="1">Text 1</option>
  <option value="2">Text 2</option>
</select>
A. Meshu
  • 4,053
  • 2
  • 20
  • 34
  • 1
    This was exactly what I needed. Already had a javascript function that changed color pic's when clicking color swatches. But had a request for it to work on the PayPal dropdown select options as well. Used this but instead of using 'value' (since I needed it for Paypal) I added a 'label' to each option with the variable names I used to change the pics. Worked perfectly! Thanks!! – FlashNoob468 Sep 17 '14 at 18:00
  • 7
    This is nice. Another simpler an valid option is: – Daniel Silva Sep 09 '19 at 14:19
  • 1
    Useful to access other attributes of the selected option. – Cees Timmerman Mar 20 '20 at 11:49
35

For how to do it in jQuery:

<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>

<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
  alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>

You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.

the
  • 21,007
  • 11
  • 68
  • 101
aiham
  • 3,614
  • 28
  • 32
  • 2
    I tried this, but change function is not getting called even if I put in document.ready method. My code is htmlData.push(' – Gendaful Feb 17 '11 at 15:32
  • @Gendaful: `htmlData.push($(' – Johannes Sep 26 '17 at 13:04
22

JavaScript Solution

<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
 document.getElementById("comboA").onchange = function(){
    var value = document.getElementById("comboA").value;
 };
</script>

or

<script>
 document.getElementById("comboA").onchange = function(evt){
    var value = evt.target.value;
 };
</script>

or

<script>
 document.getElementById("comboA").onchange = handleChange;

 function handleChange(evt){
    var value = evt.target.value;
 };
</script>
RobertKim
  • 231
  • 2
  • 4
6

I found @Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:

var changeitem = function (sel) {
  console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';

The normal behavior may be to say

newSelect.onchange = changeitem;

But this does not really allow you to specify that argument passed in, so instead you may do this:

newSelect.setAttribute('onchange', 'changeitem(this)');

And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Michael Plautz
  • 3,578
  • 4
  • 27
  • 40
  • 1
    Your evil `eval`-like string-to-code conversion is not necessary. Actually `newSelect.onchange = changeitem;` works fine if you rewrite changeitem as `var changeitem = function () {console.log(this.selectedIndex); };` (i.e. using `this` instead of a function argument). Or, leave `changeitem` as is and write `newSelect.onchange = function () {changeitem(this); };`. – Steve Byrnes Mar 02 '13 at 15:45
  • 1
    newSelect.setAttribute('onchange', 'changeitem(this)'); - cheers for that – Eggcellentos Jan 25 '18 at 12:12
5

jQuery solution

How do I get the text value of a selected option

Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:

$( "#myselect" ).val();
// => 1

The second is the text value of the select.
For example, using the following select box:

<select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>
</select>

If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:

$( "#myselect option:selected" ).text();
// => "Mr"  

See also

Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
5

This is helped for me.

For select:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

For radio/checkbox:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});
ilgam
  • 4,092
  • 1
  • 35
  • 28
3

You can try bellow code

<select onchange="myfunction($(this).val())" id="myId">
    </select>
3

Html template:

<select class="staff-select">
   <option value="">All</option>
   <option value="196">Ivan</option>
   <option value="195">Jon</option>
</select>

Js code:

const $staffSelect = document.querySelector('.staff-select')

$staffSelect.onchange = function () {
  console.log(this.value)
}
kostikovmu
  • 411
  • 5
  • 6
3

You can send only value with 'this.value'

function getComboA(selectObjectValue) {
   console.log(selectObjectValue);
}

<select id="comboA" onchange="getComboA(this.value)">
   <option value="">Select combo</option>
   <option value="Value1">Text1</option>
   <option value="Value2">Text2</option>
   <option value="Value3">Text3</option>
</select>
2

Just in case someone is looking for a React solution without having to download addition dependancies you could write:

<select onChange={this.changed(this)}>
   <option value="Apple">Apple</option>
   <option value="Android">Android</option>                
</select>

changed(){
  return e => {
    console.log(e.target.value)
  }
}

Make sure to bind the changed() function in the constructor like:

this.changed = this.changed.bind(this);
RawBData
  • 207
  • 4
  • 4
1

this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.

<html>
    <head>
        <title>Register</title>
    </head>
    <body>
    <script>
        function show(){
            var option = document.getElementById("category").value;
            if(option == "Student")
                  {
                        document.getElementById("enroll1").style.display="block";
                  }
            if(option == "Parents")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
            if(option == "Guardians")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
        }
    </script>
            <form action="#" method="post">
                <table>
                    <tr>
                        <td><label>Name </label></td>
                        <td><input type="text" id="name" size=20 maxlength=20 value=""></td>
                    </tr>
                    <tr style="display:block;" id="enroll1">
                        <td><label>Enrollment No. </label></td>
                        <td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Email </label></td>
                        <td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Mobile No. </label></td>
                        <td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Address</label></td>
                        <td><textarea rows="2" cols="20"></textarea></td>
                    </tr>
                    <tr >
                        <td><label>Category</label></td>
                        <td><select id="category" onchange="show()">    <!--onchange show methos is call-->
                                <option value="Student">Student</option>
                                <option value="Parents">Parents</option>
                                <option value="Guardians">Guardians</option>
                            </select>
                        </td>
                    </tr>
                </table><br/>
            <input type="submit" value="Sign Up">
        </form>
    </body>
</html>
Piyush
  • 1,528
  • 2
  • 24
  • 39
1

function setMyValue(v) {
  console.log(v);
}
<select onchange="setMyValue(this.value)">
  <option value="a">1</option>
  <option value="b">2</option>
  <option value="c">3</option>
</select>
wcb1
  • 665
  • 1
  • 7
  • 6
0

This worked for me onchange = setLocation($(this).val())

Here.

    @Html.DropDownList("Demo", 
new SelectList(ViewBag.locs, "Value", "Text"), 
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });
sandip
  • 533
  • 9
  • 29
Deepak Singla
  • 116
  • 1
  • 5
0

Simply:

function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve_other() {
  alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve() {  alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
  <p>RETRIEVING TEXT IN OPTION OF SELECT </p>
  <form name="myForm" action="">
    <P>Select:
      <select id="SMS_recipient">
        <options value='+15121234567'>Andrew</option>
          <options value='+15121234568'>Klaus</option>
      </select>
    </p>
    <p>
      <!-- Note: Despite the script engine complaining about it the code works!-->
      <input type="button" onclick="retrieve()" value="Try it" />
      <input type="button" onclick="retrieve_other()" value="Try Form" />
    </p>
  </form>
</HTML>
</BODY>

Output: Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value

MAXE
  • 4,978
  • 2
  • 45
  • 61
Klaus
  • 1
  • 1
0
 //html code
   <select onchange="get(this)">
      <option value="a">1</option>
      <option value="b">2</option>
      <option value="c">3</option>
    </select>

//javscript code
   function get(select) {
      let value = select.value;  
      console.log(value);
    }
    
Omar Saade
  • 320
  • 2
  • 8
  • Please edit your answer and add a little textual explanation why and how it works and how it differs from the other answer. – ahuemmer Apr 07 '22 at 11:54
0

I would think the preferred way to attach the event handler now (instead of onchange= attribute) is

document.querySelector('whatever').addEventListener('change', (event) => {
   const theValue = event.target.value;
})
grantwparks
  • 1,124
  • 9
  • 13