忽略选择选项jQuery的值

ignore value of select option jQuery

本文关键字:jQuery 的值 选项 选择      更新时间:2023-09-26

这可能很简单,但我想知道如果option select的值等于某个值,如何忽略它,例如,我有这个select

<select>
  <option value="">All</option>
  <option value=".Dog">Dog</option>
  <option value=".Cat">Cat</option>
</select>
$('select').on('change', function() {
 var animal_type = $('option:selected').text();
});

因此,如果选择了"全部",我不想为animal_type变量分配任何内容,这样在下面的ajax中,animal_type后将被忽略,并且不会作为参数发送

 $.ajax({
  type: 'POST',
  url: '/public/rehomed',
   data: {
     animal_type: animal_type, #so if ALL selected this should not be passed through
     rehomed: false,
  }
 });

我之所以想从ajax帖子中删除animal_type变量,是因为帖子的参数在rails中为我在服务器端进行SQL查询。

在执行AJAX之前,添加一个条件来检查所选选项的值。

$('select').on('change', function() {
    var animal_type = $('option:selected').text();
    var data_send = {animal_type: animal_type, rehomed: false,};
    if(animal_type != "All"){ 
      data_send = {rehomed: false,};
    }
    $.ajax({
        type: 'POST',
        url: '/public/rehomed',
        data: data_send,
    });
});

您可以这样做:

var animal_type = $('option:selected').text() == "All" ? null : $('option:selected').text();

或者你可以这样修改html:

<select>
  <option value="-1">All</option>
  <option value=".Dog">Dog</option>
  <option value=".Cat">Cat</option>
</select>

和js:

$('select').on('change', function() {
    var animal_type = $(this).val();  // get value
    if (animal_type != -1)   // if All is not selected send selected option text
    {
    animal_type = $(this).text();
    }
    else
    {
     animal_type = null;     // in case All selected set it null
    }
});

试试这个:

$('select').on('change', function() {
 var animal_type = $('option:selected').val();
 var sending_data;
if(animal_type == '')
   sending_data = {rehomed: false}
}
else
{
  sending_data = {animal_type: animal_type, rehomed:false}
}
   $.ajax({
  type: 'POST',
  url: '/public/rehomed',
   data: sending_data,
 });
});

如果您想避免发送动物类型,则值为":

var myData  =  { rehomed: false};
if (animal_type != "All") {
     myData.animal_type = animal_type;
}
$.ajax({
  type: 'POST',
  url: '/public/rehomed',
   data: myData
});

注意您有

$('select').on('change', function() {
 var animal_type = $('option:selected').text();
});

因此,animal_type似乎有一个本地作用域[在onchange函数之外无法访问]。