Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery select drop down change event - select a default

How would I still allow my change event to happen for my drop down while selecting a default value?

Select value 1 as default, but also have the change function work..

<select id='statsGraphingSelect'>
    <option value='1' selected="selected">1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
</select>       

$("#statsGraphingSelect").change(function() {
    if ($("#statsGraphingSelect option[value='1']").attr('selected')) {//something happens here }
    if ($("#statsGraphingSelect option[value='2']").attr('selected')) {//something happens here }
    if ($("#statsGraphingSelect option[value='3']").attr('selected')) {//something happens here }
    if ($("#statsGraphingSelect option[value='4']").attr('selected')) {//something happens here }
}
like image 443
user1040259 Avatar asked Dec 04 '22 18:12

user1040259


1 Answers

i dont know what are you trying to achieve, you can try

$("#statsGraphingSelect").change(function() {
var n = $(this).val();
 switch(n)
 {
 case '1':
   execute code block 1
   break;
 case '2':
   execute code block 2
   break;

 }
});

now with your given markup if you trigger change in the ready handler like

$(function(){
 $("#statsGraphingSelect").change();
});

the case 1 will be executed

DEMO

like image 98
Rafay Avatar answered Jan 05 '23 21:01

Rafay