Getting selected value from drop down

(JQUERY)


Hi,
In this  article i discuss about how to get the selected value from dropdown and setting the default item in the dropdown using jquery.

View:-

@{
    ViewBag.Title = "selectElement";
}

<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" />

<h2>select Element</h2>


<label for="drp_fruits">Select fruit:- </label>
<select id="drp_fruits">
  <option value="Apple">Apple</option>
  <option value="Orange">Orange</option>
  <option value="Mango">Mango</option>
  <option value="Cucumber">Cucumber</option>
</select>

<br />
<br />
<input type="button" id="btn_selfruit" value="Get selected fruit" /> &nbsp;&nbsp;
<input type="button" id="btn_setselfruit" value="Select typed fruit" /> &nbsp;&nbsp;
<input type="text" id="txt_typedfruit" />


<script type="text/javascript">

    $(function () {
        $('#btn_selfruit').click(function () {
            var val = $('#drp_fruits option:selected').text();
            $(this).css('color', 'blue');
            $(this).css('text-decoration', 'underline');
            $(this).css('font-weight', 'bold');
            customDialog("Information", "Selected fruit is:- " + val);


        });


        $('#btn_setselfruit').click(function () {
            $(this).css('color', 'blue');
            $(this).css('text-decoration', 'underline');
            $(this).css('font-weight', 'bold');
            $('#drp_fruits option[value="' + $('#txt_typedfruit').val()  + '"]').attr("selected", true);
        });
    });

    //jquery custom dialog box to display  exception
    function customDialog(headerValue, message) {

        //remove the existing div
        var divs = $('body').find('div[id="div_customDialog"]');

        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_customDialog"></div>');

        $('#div_customDialog').html(message);

        $('#div_customDialog').dialog({
            draggable: true,
            modal: true,
            resizable: false,
            width: 'auto',
            title: headerValue,
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_customDialog').dialog('open');
    }

</script>


Controller:-

 public ActionResult selectElement()
        {
            return View();
        }

Image

Ratings


Average Rating: 0.00 by 0 users
Giri Prasad
1/30/2016
1/30/2016
Download PDF

Comments