User987 User987 - 5 months ago 29
C# Question

Getting default value of radio button upon page load using jQuery

I have two radio buttons whom I set to default (first selected value radio button is the default one upon load) like following:

var listing_type;
var shipping_location;
$(":radio[name='type'][value='1']").attr('checked', 'checked');
$(":radio[name='shipping'][value='1']").attr('checked', 'checked');

When the user clicks on some of the values from radio buttons, the values are caught like following:

$('input:radio[name=type]').click(function () {
listing_type = $(this).val();
$('input:radio[name=shipping]').click(function () {
shipping_location = $(this).val();

This 2nd part of the code works just fine, when the user clicks on some of the radio buttons, values are passed into my MVC Action just correctly.

However, I'm unable to catch the value if the user doesn't clicks anything on the radio buttons (i.e. leaves them as default as they are upon page load) and clicks "Search" Button...

The values in my MVC Action are always null for some reason, even though they aren't supposed to be. Here is how I'm passing the values and the here is the C# code from the Action:

$.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) {
var brands = $('<table />').append(data).find('#tableProducts').html();
$('#tableProducts thead').show();

And this is the 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();

So now my question is:

How can I pass the default values from the radio buttons if the user doesn't interacts with them (i.e. passing the default values I've set upon page load)???


Give this a try:

$('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
$('input:radio[name="shipping"]').filter('[value="1"]').attr('checked', true);