开发者

javascript selected value

开发者 https://www.devze.com 2023-02-19 06:12 出处:网络
<div id=\"selected_options\"> <select onchange=\"test()\" id=\"selected_options\"> <option value=\"0\" selected>-Select-</option>
            <div id="selected_options">
            <select onchange="test()" id="selected_options">
            <option value="0" selected>-Select-</option>
            <option value="1">Communication</option>
            <option value="2">Hardware</option>
            </select>
    </div>

i had written a function for selected value , but when i'm doing al开发者_Python百科ert of selected value it showing up undefined , the function is

      function test() {
                    var get_id = document.getElementById('selected_options');
                    var result = get_id.options[get_id.selectedIndex].value;
                    alert(result);
                      }

any one please tell me what is the error?


You also have two id's with selected_options. As this JSFiddle would alert:

<div id="selected_options">
    <select onchange="test()" id="selected_opt">
        <option value="0" selected>-Select-</option>
        <option value="1">Communication</option>
        <option value="2">Hardware</option>
    </select>
</div>

function test() {
    var get_id = document.getElementById('selected_opt');
    console.log(get_id);
    var result = get_id.options[get_id.selectedIndex].value;
    alert(result);
}


The error is here:

get_id.options[get_id.selectedIndex].value;

It should be

get_id.value

And it will show up the selected value :)


get_id[get_id.selectedIndex].value; "options" not required.


To get the currently selected value you can do:

function test() {
    var get_id = document.getElementById('selected_options');
    var result = get_id.value;
    alert(result);
}


It's probably because your div and select tags have the same id.


use jQuery its much easier:

var result = $('#selected_options option:selected').val();

and use ids only once


the problem in your code is the same id => 'selected_options' for both div and combobox.

ids are meant for unique element representation in a page.

you can check its live example here:
http://outsourcingnepal.com/projects/kool.htm

code:

<script>
function test() {
        var get_id = document.getElementById('selected_options');
    var result = get_id.options[get_id.selectedIndex].value;
    alert(result);
}
</script>
<h1>Outsourcing Nepal</h1>
<a href="http://www.outsourcingnepal.com">Home</a>
<div id="selected_options1">
    <select onchange="test()" id="selected_options">
            <option value="0" selected>-Select-</option>
            <option value="1">Communication</option>
            <option value="2">Hardware</option>
    </select>
</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消