[英]ignore value of select option 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
變量的原因是該帖子的參數在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
}
});
如果要避免發送動物類型(如果值為“”):
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函數之外無法訪問]。
嘗試這個:
$('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,
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.