简体   繁体   中英

How to set attribute selected true for option with no value in jquery

I am having a select box with all users names. I want to list all users in one place by selecting (All) option in the select box. I have tried by doing the following

View

= select_tag :user_id, options_from_collection_for_select(User.all, "id", "name", @user.id),:prompt => "(All)", class: "no-padding user_select"

Js

$(".user_select").on("change", function() {
 if ($(this).val() == "") {
   window.location = '/users/absences/all';
   $(this).attr('selected', true);
 } else {
   window.location = '/users/' + this.value + '/absences';
 }
});

When i select the all option i am redirected to the correct page but in the select box i cant see the (ALL) option highlighted. Instead i see the first option having the selected attribute to true.

I want to see the (All) option to be selected in the select box when i click on it like any other option. Can anyone help me in doing so.

Two things.

First, you're not setting an attribute on an option in your code. Your code is setting an attribute on a select. You need to find the 'All' option and set that to selected.

Secondly, as has been pointed out, the JavaScript that selects this option isn't even running on the right page. It seems to me that every time you go to /users/absences/all , you'd want the 'All' option to be selected, so you can just put selected in the html option. Doesn't need to be JavaScript.

<select id="user_select">
  <option value="all" selected>All</option>
  <option value="1">Jon Doe</option>
</select>

But if you DID want to select that option with JavaScript for some weird reason, you could just do that on DOM ready:

$(function() {
  $('#user_select option[value=all]').prop('selected', true);
});

Or, if you can't have a value in your 'All' option, but that option appears first:

$(function() {
  $('#user_select option:first').prop('selected', true);
});

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