gpt4 book ai didi

javascript - 使用 jQuery 获取页面加载时单选按钮的默认值

转载 作者:行者123 更新时间:2023-12-03 05:48:39 25 4
gpt4 key购买 nike

我有两个单选按钮,我将其设置为默认值(第一个选定值单选按钮是加载时的默认值),如下所示:

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

这就是操作:

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

关于javascript - 使用 jQuery 获取页面加载时单选按钮的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40241862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com