简体   繁体   中英

Get the first html dropdown value using jquery to the text field

With my current code I am easily getting the html drop down values on change of the drop down using jquery but i am not getting default value which was selected in the drop down.

Here is what i tried jquery

$("document").ready(function () {
    $("#dropval").change(function () {
        var selectedValue = $(this).val();
        $("#data").val($(this).find("option:selected").attr("value"));
        alert($("#dropval option:selected").text());
    });
});

and i tried the below code alert($("#dropval option:selected").text()); i am not getting the alert js fiddle link

Some times simple stuff also not working :)

This takes the value on load:

<select name="drop" id="dropval">
    <option selected value="first">First</option>
    <option value="second">second</option>
</select>
<input type="text" id="data" />

$("document").ready(function () {
    $("#dropval").change(function () {
        var selectedValue = $(this).val();
        $("#data").val($("#dropval").find("option:selected").attr("value"));
        alert($("#dropval option:selected").text());
    });
    console.log($(this));
    $("#data").val($("#dropval").find("option:selected").attr("value"));
});

Option 2

JSFiddle

$("document").ready(function () {   
    $("#dropval").change(function () {
        var selectedValue = $(this).val();
        $("#data").val(selectedValue);
        alert($("#dropval option:selected").text());
    });
    $("#data").val($("#dropval").val());
});

take a look at this possibility - getting the value of the previous selected option by using the focus event:

$("document").ready(function () {
    $("#dropval")
        .focus(function(){
            $("#data").val($(this).find("option:selected").attr("value"));
        })
        .change(function () {
        var selectedValue = $(this).val();
        //alert($("#dropval option:selected").text());
    });
});

updated fiddle: http://jsfiddle.net/5bjrtfzc/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM