简体   繁体   中英

ignore value of select option jQuery

This is probably quite simple but I am wondering how to ignore value from an option select if it is equal to a certain value, for example I have this 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();
});

So if 'All' is selected I do not want to assign anything to the animal_type variable so that in the following ajax post animal_type is disregarded and not sent as a parameter

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

The reason I am thinking to remove the animal_type variable from the ajax post is the parameters of the post make an SQL query on the server side for me in rails.

Add a condition to check the value of the selected option before you do the 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,
    });
});

you can do something like this:

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

or you can modify html like this:

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

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

If you want to avoid sending the animal type if the value is "":

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

Note that you have

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

So it looks like the animal_type has a local scope [won't be accessible outside the onchange function].

Try this:

$('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,
 });
});

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