开发者

select all options in select listbox by default -- javascript

I have a form which has a select list associated with the f开发者_开发技巧ield players.

To populate the listbox, user clicks on a button on the form to display a popup and from that popup select players' names and then click another button on the popup which closes the popup and displays the selected values in the listbox.

By default, i put selected="true" in the select tag so that when user saves the form, the values in the listbox are saved.

<select size=5 id="sub_player_ids" name="sub[player_ids][]"  multiple selected="true">

The above code selects all options in the selectbox and those options are highlighted in blue.

However it can happen that user deselects an option in the player's select box by error.

I would like all options in the select box to be selected by default - whether they are highlighted or not

Is there is a way to select all options in the select box by default when saving the form?

Thanks a lot for any suggestion provided.

Cheers


Do you know the values in the select? You can loop over the select and set each options selected to true.

for (var i = 0, children = select.childNodes, l = children.length; i < l; i++) {
    if (children[i].tagName === "OPTION") children[i].selected = true;
}

Fiddle is using the fact that Chrome/IE7+ should define window.select as the element found in the DOM by the ID select. If you run this in Firefox you'll need var select = document.getElementById('select');

http://jsfiddle.net/robert/VKF4E/


It's a one-liner if you're using jQuery.

$("#sub_player_ids option").attr("selected", "selected");

Explanation: the syntax in the JQuery Selector uses CSS style to identify the "SELECT" (listbox) using the '#id' pattern and then following it with "option" selects all of the options within the named element. the "attr" function will add an attribute to each element returned. In this case we are adding the "selected" attribute and setting the value to "selected"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜