How do I get the value of drop down list on page load

放肆的年华 提交于 2019-12-04 04:15:37

问题


Using jQuery, how can I get the selected item's value in a select when the page loads? I can do it onChange etc but cant figure out the way on page load.

Here's my code:

<select name="symb" id="symb">
  <option value="1#10#6">Basic Personal</option>
  <option selected="selected" value="2#20#6">Basic Family</option>
  <option value="7#90#12">Advanced Personal</option>
  <option value="8#120#12">Advanced Family</option>
  <option value="9#130#12">Optimum Personal</option>
  <option value="10#170#12">Optimum Family</option>
</select>

This is the script I'm using for getting the option value onchange:

$(document).ready(function() {
    $("#symb").change(function() {
          var val = $(this).symbCost(0);
    })

   $.fn.symbCost = function(pos) {
        var total = parseInt($("option:selected").val().split('#')[pos]);
        return total;
    }
});

回答1:


$(document).ready(function() {
    alert($("#symb").val());
});



回答2:


Working Demo http://jsfiddle.net/YXbDd/3/ or http://jsfiddle.net/YXbDd/4/

API: http://api.jquery.com/ready/ > Specify a function to execute when the DOM is fully loaded.

I am not sure what pos context is in your case but this should do the stick.

$("#symb").val().split('#')[0]

Rest as demo and code, hope it helps,

code

$(document).ready(function() {
    alert("when the page load ==> " + $("#symb").val().split('#')[0]);
    $("#symb").change(function() {
          var val = $(this).symbCost(0);
    })

   $.fn.symbCost = function(pos) {
        var total = parseInt($("option:selected").val().split('#')[pos]);
        alert(total);
        return total;
    }
});​

or

$(document).ready(function() {
    alert("when the page load ==> " + $("#symb option:selected").val().split('#')[0]);
    $("#symb").change(function() {
          var val = $(this).symbCost(0);
    })

   $.fn.symbCost = function(pos) {
        var total = parseInt($("option:selected").val().split('#')[pos]);
        alert(total);
        return total;
    }
});​



回答3:


$(document).ready(function() {
    alert($("#dropdownid").val());
});



回答4:


The best solution and siple:

$(document).ready(function() {
$.fn.symbCost = function(pos) {
var total = parseInt($(this).val().split('#')[pos]);
    return total;
}   
$("#symb").change(function() {
    var val = $(this).symbCost(0);
}).triggerHandler('change');

});

Or this

$(document).ready(function() {
$.fn.symbCost = function(pos) {
    var total = parseInt($(this).val().split('#')[pos]);
    return total;
}
$("#symb").change(function() {
    var val = $(this).symbCost(0);
}).symbCost(0);

});



来源:https://stackoverflow.com/questions/11222007/how-do-i-get-the-value-of-drop-down-list-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!