user1010101
user1010101

Reputation: 1658

How to get user input based on radio button selection?

I have a simple program where I give the option to select certain materials. I have one variable declared in my program called cost. So depending on which materials the user selects, the variable should be assigned a different value. For instance.

if('#radio-choice-1) is selected{
    var cost = 5;
}
else if('#radio-choice-2') is selected{
    var cost = 10;

 }

There are 2 material choices. Both have different $ value for example so say if you pick material A then cost is one value and if you pick material B then cost value is another value.

This is a FIDDLE I created to make things easier.

Upvotes: 2

Views: 919

Answers (2)

Dryden Long
Dryden Long

Reputation: 10180

You're going to want to use a combination of is() and :checked to do this. Something like this should work for you:

if($('#radio-choice-2').is(':checked')) { 
    var cost = 10;
}
else {
    var cost = 5;
}

Now, this assumes you only have two options for cost, 5 and 10.

Upvotes: 0

Jeremy Danyow
Jeremy Danyow

Reputation: 26406

in your html you have:

<fieldset data-role="controlgroup">
    <input type="radio" name="radio-choice" id="radio-choice-1" value="choice-1">
    <label for="radio-choice-1">SS316L</label>
    <input type="radio" name="radio-choice" id="radio-choice-2" value="choice-2">
    <label for="radio-choice-2">HDPE</label>
</fieldset>

you could put the cost in the value attribute like this:

<fieldset data-role="controlgroup">
    <input type="radio" name="radio-choice" id="radio-choice-1" value="5.00">
    <label for="radio-choice-1">SS316L</label>
    <input type="radio" name="radio-choice" id="radio-choice-2" value="8.25">
    <label for="radio-choice-2">HDPE</label>
</fieldset>

and use jquery to grab the cost of the selected item like this:

var cost = $('input[name=radio-choice]:checked').val();

here's a working example of this technique: http://jsfiddle.net/RhnvU/

Upvotes: 3

Related Questions