Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何为jquery中没有值的选项设置属性selected true_Javascript_Jquery_Ruby On Rails - Fatal编程技术网

Javascript 如何为jquery中没有值的选项设置属性selected true

Javascript 如何为jquery中没有值的选项设置属性selected true,javascript,jquery,ruby-on-rails,Javascript,Jquery,Ruby On Rails,我有一个包含所有用户名的选择框。我想通过在选择框中选择(全部)选项,在一个位置列出所有用户。我试着做了以下几点 查看 = 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(

我有一个包含所有用户名的选择框。我想通过在选择框中选择(全部)选项,在一个位置列出所有用户。我试着做了以下几点

查看

= 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';
 }
});
当我选择全部选项时,我被重定向到正确的页面,但在选择框中,我看不到(全部)选项高亮显示。相反,我看到第一个选项将selected属性设置为true

当我像其他任何选项一样单击(全部)选项时,我希望在选择框中看到要选择的(全部)选项。有人能帮我吗。

两件事

首先,您没有在代码中的选项上设置属性。您的代码正在选择上设置属性。您需要找到“全部”选项并将其设置为“选定”

其次,正如已经指出的,选择此选项的JavaScript甚至没有在正确的页面上运行。在我看来,每次您转到
/users/absences/all
,您都希望选择“all”选项,因此您可以将
selected
放在html选项中。不需要是JavaScript

<select id="user_select">
  <option value="all" selected>All</option>
  <option value="1">Jon Doe</option>
</select>
或者,如果您的“全部”选项中没有值,但该选项首先出现:

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

您正在发送更改事件的重定向。。因此,您需要在新页面(而不是当前页面)中处理该情况。该行从不执行:“$(this).attr('selected',true)”bcoz ur重定向到页面。那么我如何处理该情况。我应该在哪里设置attr为真?我的荣幸!还要注意我的编辑,选择的
应使用
.prop()
方法,而不是
.attr()
$(function() {
  $('#user_select option:first').prop('selected', true);
});