jQuery collects 2 points of data, even though only one is assigned
Quick question on the .data()
in jQuery: My variable "valone" reaches into a dropdown menu within some HTML for the "data-whatever" value in the dropdown and then plugs it into the jQuery equation. But it also seems to be getting the "option value" value from the dropdown and includes it into the math somehow, even though I don't specify it to do so...
var valone = $('#os0 option:selected').data('whatever');
Am I missing something in this .data()
function? Or do I have something extra that is not necessary?
(I have the complete jQuery and HTML below.)
jQuery
$(document).ready(function(){
var valone = $('#os0 option:selected').data('whatever');
var valtwo = $('#os1').val();
var valthree = $('#os2').val();
var total = ((valone * 1) * (valtwo * 1) * (valthree * 1));
$('.calc').each(function(){
if($(this).val() != '')
{
total += parseInt($(this).val());
}
});
HTML
<select style="width: 190px;" class="calc"
name="os0" id="os0" type="text">
<option value="250" data-whatever="5">250
</o开发者_如何学运维ption>
<option value="500" data-whatever="6">500 </option>
<option value="1000" data-whatever="7">1000
</option>
<option value="2000" data-whatever="8">2000
</option>
<option value="5000" data-whatever="9">5000
</option>
</select>
Any help or advice would be greatly appreciated!
.data
is retrieving the correct value. The problem occurs with this piece:
$('.calc').each(function(){
if($(this).val() != '')
{
total += parseInt($(this).val());
}
});
The variable total
is computed above this point is what you expect. .each
is iterating over each select
element again and adding the selected value to the total.
In answer to your question, you are missing nothing. Data stores one thing, the value set to it, either the hardcoded value in the element attribute, or the one set via jquery. What is the point in doing valone * 1, why not just valone? you are over complicating it. It should be
var total = valone * valtwo * valthree;
or
var total = (valone * valtwo) * valthree`; //valone will be multiplied with valtwo first before multiplying that total with valthree
Depending on what you are calculating.
精彩评论