[英]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.