hermann
hermann

Reputation: 6295

Getting the value of a select box after another select box has been changed

I am trying to implement a leap-year dropdown DOB picker.

So I have three select boxes in this order :

<select id='selectYear' >
//php to populate this list
</select>

<select id='selectMonth'>
//php to populate this list
</select>

<select id='selectDate' >
//php to populate this list
</select>

What I want to do is add an onChange even to the month DDL where it gets the selected value as well as the selected value of the selectYear DDL so I can then populate the selectDate DDL.

How do I get the value of the selectYear DDL so I can send it as a parameter?

Upvotes: 0

Views: 334

Answers (5)

FrontEnd Expert
FrontEnd Expert

Reputation: 5813

You can do like that:---

<select id='selectYear' >
        //php to populate this list
        </select>

        <select id='selectMonth'>
        //php to populate this list
        </select>

        <select id='selectDate' >
        //php to populate this list
        </select>

Your script :--

      jQuery('#selectYear, #selectMonth, #selectDate').change(function() {
                var selectYear = '';
                var selectMonth = '';
                var selectDate = '';
            var selectYear= jQuery('#selectYear').val();
            var selectMonth= jQuery('#selectMonth').val();
            var selectDate= jQuery('#selectDate').val();
var format= selectYear + selectMonth + selectDate;
alert(format);
            });

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

Do you mean:

<select id='selectMonth' onchange="doSometing(this.value);">
....
</select>

function doSometing(selectedMonth) {
    var year = document.getElementById("selectYear");
    var selectedYear = year.options[year.selectedIndex].value;
    console.log("My Selected Month:"+selectedMonth);
    console.log("My Selected year:"+selectedYear);
}

Upvotes: 1

rizzz86
rizzz86

Reputation: 3990

If you are using a simple javascript then you can use "selectedIndex" property of an element:

Find example on this link: http://www.w3schools.com/jsref/prop_select_selectedindex.asp

Upvotes: 0

Nealv
Nealv

Reputation: 6884

If you are using JQuery:

$("#selectMonth").change( function() {
  //This is the value of the selectlist
  val = $(this).val();
});

Upvotes: 0

Alexander Pavlov
Alexander Pavlov

Reputation: 32296

A good link on the topic. In brief:

var element = document.getElementById("selectYear");
var value = element.selectedIndex < 0 ? null : element.options[element.selectedIndex].value;

Upvotes: 0

Related Questions