views:

38

answers:

3

Hi.

I'm trying to write a order form that shows the value of the selected items automatically. The backend is already complete, and on the front end each field, all radio / checkbox, look like this:

<input type="radio" name="shirt-size" value="shirt_size_m[18]" />

'18' being the price, everything else being irrelevant to the front end price calculation. I cannot change the naming convention, so I need to get the value between the brackets on all the <input>s on the page (or below the parent ID), add them together (on update), and append the value to another ID. Jquery is already in use on the site if that makes thongs easier.

I just need to be pointed in the right direction as my JS experience is limited to examples and minor customizations :)

+2  A: 

Try using a simple regular expression with Javascript's replace, to replace all non-numeric characters with the empty string:

var str = "shirt_size_m[18]";
var theNumber = parseInt(str.replace(/[^0-9]/g, ''));
alert(theNumber);

Demo: http://jsfiddle.net/XvTaY/1/

karim79
If it is at all possible there could be a leading 0, use parseInt(str.replace(/[^0-9]/g, ''), 10) . The second argument to parseInt is essentially the number system to use. If it's left out, and there's a leading 0, parseInt will interpret it at hex (base 16)
Ryan Kinal
A: 

u can use:

var v;
v = $('#input-identifier').val();

v = v.split("[");
v = v[1];
v = v.split("]");
v = v[0];

// now v has the number

Ha11owed
+1  A: 

You could try something like this:

function calculate_sum(form_id) {
  var $form = $(form_id);
  var sum = 0;
  $checkbox_and_radios = $form.find('input[type=checkbox], input[type=radio]').each(function(){
    sum += parseInt($(this).val().match(/^[^\[]+\[(\d+)\]$/)[1]);
  });
  return sum;
}

$(function(){
  $("#id_of_the_form").find('input[type=checkbox], input[type=radio]').change(function(){
    var sum = calculate_sum("#form_id");
    // I don't know the type of your element containing
    // the sum, so I put multiple solutions here:
    // some input element
    $('#another_id').val(sum);
    // or another element
    $('#another_id').html(sum);
    // I'm assuming you don't really mean append
    // If you're sure you want to append: (but then the old value won't be deleted)
    $('#another_id').append(sum);
  });
});
jigfox