1 回答
TA贡献1831条经验 获得超4个赞
您可以检查是否attr存在 on not inside 选项,因为您的第一个选项没有,attr这就是它给出的原因NaN,所以如果不存在,只需给出 value 0else attr value 。
演示代码:
var total = 0;
$('select').change(function() {
//get value from cpu slect box check if attr there else take value 0
var cpu_price = $(".cpu").find('option:selected').attr('cpuprice') ? $(".cpu").find('option:selected').attr('cpuprice') : 0
$('#cpuprice').val(cpu_price)
//get value from gpu slect box check if attr there else take value 0
var gpu_price = $(".gpu").find('option:selected').attr('gpuprice') ? $(".gpu").find('option:selected').attr('gpuprice') : 0
$('#tpuprice').val(gpu_price)
total = parseFloat(cpu_price) + parseFloat(gpu_price);
$('.totalprice').text('₱' + total);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border=" 1">
<thead>
<tr>
<th>Component</th>
<th>Item Name</th>
<th>Price </th>
</tr>
</thead>
<tbody>
<tr>
<td>CPU</td>
<td>
<select class="cpu">
<option>---select your CPU---</option>
<option cpuprice="1222">Soemthing</option>
<option cpuprice="1000">Soemthing1</option>
</select>
</td>
<td>
<output class="form-control prc" id="cpuprice" disabled value="" />
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>GPU</td>
<td>
<select class="gpu">
<option>---select your GPU---</option>
<option gpuprice="1200">Somehingg</option>
<option gpuprice="120">Somehingg1</option>
</select>
</td>
<td>
<output class="form-control prc" id="tpuprice" disabled value="" />
</td>
</tr>
</tbody>
</table>
<span class="totalprice">Total: </span>
添加回答
举报