Search code examples
javascriptradiobuttonlist

How to assign radio buttons a value in javascript


What I need to do is turn the 4 different values (when clicked) on the page into a number that I can use to calculate the output in the chart.

http://jsfiddle.net/nlem33/eyGMu/7/

var min_value = 0,
  max_value = 10,
  units = 0,
  price = 0;
var sliderHandler = function (event, ui) {
  var newdata = [],
    newdata2 = []
    data = [],
    sum = 0;
  if(this.id === 'slider1') {
    $('#slider1_value').html(ui.value);
    units = ui.value;
  } else {
    $('#slider2_value').html('$' + ui.value);
    price = ui.value;
  }
  for(var i = 0; i < 12; i++) {
    data.push(units * price);
    for(var j = 0; j < i; j++)
    sum += data[j];
    newdata.push(229 * units * i);
    newdata2.push(sum);
  }
  console.log(newdata);
  chart.series[0].setData(newdata2);
  chart.series[1].setData(newdata);
}

Solution

  • Add a variable called selected and use this event handler:

    var selected = 1;
    $(document).ready(function() {
        $(".product").click(function(){
            selected = this.id.replace("product", "");
            alert(selected);
        });
    });
    

    See the updated fiddle. Then you can use the selected variable anywhere.

    In order to use the value of a radio button rather than the number in its id, use the following code instead:

    var selected = 1;
    $(document).ready(function() {
        $("input[name=chooseProduct]").change(function(){
            selected = $(this).val();
            alert(selected);
        });
    });
    

    See next updated fiddle for that example as well.