开发者

Aquire a default value of a "select" HTML Input Element, via jQuery & JavaScript?

开发者 https://www.devze.com 2023-04-04 08:56 出处:网络
I\'m using a third-party jQuery plugin that gets the values, settings and preferences of a <select> element and replaces it with a custom widget.

I'm using a third-party jQuery plugin that gets the values, settings and preferences of a <select> element and replaces it with a custom widget.

How can I find out the d开发者_如何学运维efault value of a <select> element?


<option> elements have a property defined in DOM level 1 called defaultSelected. This property will be set to true for any <option> element that has the selected attribute defined in the HTML when the element is parsed.

It should be fairly simple to use filter to get any default selected options:

var def = $("select > option").filter(function () { 
    return this.defaultSelected; 
});

Working demo: http://jsfiddle.net/AndyE/9G3pR/

  • defaultSelected property (MSDN)


Use

$("select option:selected");

To get the currently (or default) selected item. To get it's value, use

$("select option:selected").val();

Or

$("select").val()

If you want to be shorter/faster.


To get the select's original value, you need to store it in the element's data using the .data() function, as this JSFiddle shows.

When you want to retrieve the value, simply call .data("originalValue") on the select element (second .each() of the JSFiddle.

$(document).ready(function() {
    $("select").each(function() {
        $(this).data("originalValue", $(this).val());
    });

    // Log data - will output "1"
    $("select").each(function() {
        console.log($(this).data("originalValue"));
    });
});

You need to run the first .each() call in the above code when your page loads to store the select box's original value. Do note that originalValue can be any identifier you like.


$('select option:selected').val();
0

精彩评论

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