在页面加载时使用jQuery获取单选按钮的默认值
本文关键字:获取 jQuery 单选按钮 默认值 加载 | 更新日期: 2023-09-27 18:14:54
我将两个单选按钮设置为默认值(第一个选择值单选按钮是加载时的默认值),如下所示:
var listing_type;
var shipping_location;
$(":radio[name='type'][value='1']").attr('checked', 'checked');
$(":radio[name='shipping'][value='1']").attr('checked', 'checked');
当用户单击单选按钮中的某些值时,这些值被捕获,如下所示:
$('input:radio[name=type]').click(function () {
listing_type = $(this).val();
});
$('input:radio[name=shipping]').click(function () {
shipping_location = $(this).val();
});
这第二部分的代码工作得很好,当用户点击一些单选按钮,值被传递到我的MVC动作只是正确的。
然而,如果用户不点击单选按钮上的任何东西(即让它们默认为页面加载时),然后点击"搜索"按钮,我就无法捕获值…
在我的MVC动作的值总是空出于某种原因,即使他们不应该是。这是我传递值的方式,这是来自Action:
的c#代码 $.post("/Search/Index", { keywords: $('.txtSearch').val(), type: /* listing_type */ <=> $('input[name=type]:checked').val(), location: $('input[name=shipping]:checked').val() <=> /*shipping_location*/ }, StartLoading())
.done(function (data) {
StopLoading();
var brands = $('<table />').append(data).find('#tableProducts').html();
$('#tableProducts').html(brands);
$('#tableProducts thead').show();
});
}
这是Action:
public ActionResult Index(string keywords, string type, string location)
{
// If the user doesn't interacts with the radio buttons and just enters the search term (ie. keywords) the type and location variables are null).
if ((keywords != null && keywords != "") && (type != null && type != "") && (location != null && location!=""))
{
// do something here....
}
return View();
}
现在我的问题是:
如果用户不与单选按钮交互,我如何传递默认值(即传递我在页面加载时设置的默认值)?
试一试:
$('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
$('input:radio[name="shipping"]').filter('[value="1"]').attr('checked', true);