忽略select选项jQuery的值

时间:2014-10-31 11:16:34

标签: javascript jquery

这可能很简单,但我想知道如果它等于某个值,如何忽略option 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变量的原因是帖子的参数在服务器端为我做了一个SQL查询。

4 个答案:

答案 0 :(得分:1)

添加条件以在执行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,
    });
});

答案 1 :(得分:1)

你可以这样做:

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
    }
});

答案 2 :(得分:1)

如果您希望避免发送动物类型,如果值为&#34;&#34;:

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 功能之外访问]。

答案 3 :(得分:1)

试试这个:

$('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,
 });
});
相关问题