简体   繁体   中英

Passing multiple values from a radio button group

I'm curious what is the best practice when passing values from a group of radio buttons. Especially if a radio button can have multiple values.

In my example, let's say someone is looking to get two types of food at a party, 1) Cake and 2) Cake and Waffles.

HTML:

<input id="Cake" name="food" type="radio" value="true">
<input id="Both" name="food" type="radio" value="true,false" checked="checked">

JavaScript(jQuery):

var testString = $('input[name=food]:checked').val();

For the last value - "true,false" I'm splitting up the string to get an array of strings - although in the end I really just need the actual boolean values - true, false. This means that I would have to write another function just to parse through the strings and convert them to boolean values.

In the end, is it worth it to pass the two values "true, false" or should I maybe consider just saying "all" because in the end I would still have to clean up the values anyway? In the latter case convert "all" to an array of true, false and pass that to backend javascript functions.

Well, you can either do the "all" technique, or you can convert the array of strings like so:

var output = $.map(arrayOfStringsHere, function(item, index) {
    return Boolean(item);
});

// output should == array of booleans

Give that a go. Or even go with the suggestion of checkboxes. Might be nicer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM