sum and multiply series of input and select fields in form with jquery
I have one form which has several input and select fields. I need to multiply value from each corresponding select field with input filed and sum it all up. sel1*inp2 + sel2*inp2+....
<form id="myForm" >
<select id="sel1" >
<option value="1" >1</option>
<option value="1" >2</option>
<option value="1" >3</option>
<option value="1" >4</option>
</select>
<input type="hidden" value="200" id="inp1"/>
<select id="sel2" >
<option value="1" >1</option>
<option value="1" >2</option>
<option value="1" >3</option>
<option value="1" >4</option>
</select>
<input type="hidden" value="300" id="inp2"/>
<select id="sel3" >
<option value="1" >1</option>
<option value="1" >2</option>
<option value="1" >3</option>
<option value="1" >4</option>
</select>
<input type="hidden" value="600" id="inp3"/>
<input type="text" id="total" name="sum"/>
</form>
I've been using sometnihg like this
$('#myForm select').each(
function(i){
$(this).attr('id','kol'+i);
$(this).change( function(){
var total = parseFloat(0);
$('#myForm select').each(
开发者_StackOverflow社区 function(j){
total += parseFloat(this.value) * parseFloat($('#myForm :hidden').eq(j+1).val());
}
);
$("#total").attr("value",total);
});
}
);
This works on Firefox but not on any other browser.
Using this.value
on the select element is not consistent across browsers. You are better of using jQuery's method to extract the value from the select element.
See here in jQuery FAQ for details (basically, it says use select.val()
).
Secondly, why are you changing the id of the selects and not assigning them in the html directly? Changing of IDs is also not consistent across browsers and could affect the way elements are accessed from the dom. I don't see what you are gaining from that.
Finally, if performance is important, then don't grab the hidden value with ('#narudzba :hidden').eq(j+1)
. Since those hidden fields have an id with a digit at the end, it is easy for you to access them directly (You have the parameter j
and you know which select you are working on). An alternative is to use jQuery.next()
and simply navigate to the hidden field.
精彩评论