[英]issue with change function on select option in Jquery
I have a little select form. 我有一点选择形式。 When I change options using JQUERY, new suitable price appears inside
.prices
. 当我使用JQUERY更改选项时,
.prices
出现新的合适价格。 AN old price is 100 $. 旧的价格是100美元。 if user is student or pupil, I want make him discount -10 $.
如果用户是学生或学生,我想让他折扣-10 $。 So when user choose option student or pupil price is changed from 100 to 90$.
因此,当用户选择选项时,学生或学生的价格从100变为90 $。 But when user choose option again to pupil it must not be change the price, but it changes it to 80 $.
但是当用户再次向学生选择选项时,它不能改变价格,而是将其改为80 $。 Again when choose option student, price was changed to 70. I exactly want that if user choose option: student or pupil, there will be -10 $ discount.
再次选择期权学生时,价格变为70.我确实希望如果用户选择选项:学生或学生,将有-10美元的折扣。
you can ask why I used each function
? 你可以问我为什么使用
each function
? The option: other
is selected and first time page shows price 110$. 选项:
other
被选中,第一次页面显示价格110 $。 each function fixed this problem. 每个功能都解决了这个问题 I have also JS fiddle, you can check it.
我也有JS小提琴,你可以检查一下。 Sorry for my English Language.
抱歉我的英语。
HTML HTML
<select name="status" id="status">
<option value="1">Student</option>
<option value="2">Pupil</option>
<option value="3" selected>Other</option>
</select>
<div class="price">
<span class="prices">100</span> $
</div>
JQUERY JQUERY
$( "#status" ).change(function () {
var price2 = ($(".prices").text());
$('.prices').text('');
var value = $( "#status option:selected" ).val();
if(value=="3")
{
new_price2 = +price2 + +10;
$('.prices').append(new_price2);
}
else
{
new_price2 = price2 - 10;
$('.prices').append(new_price2);
}
})
.change();
$('#status option').each(function() {
if(this.selected)
{
var price2 = ($(".prices").html());
$('.prices').html('');
new_price2 = price2 - 10;
$('.prices').append(new_price2);
}
});
You only need the change
handler in your jQuery code. 您只需要jQuery代码中的
change
处理程序。 Also, you need to keep a static base price value so that you can do all calculations on that instead of keeping a running total of all changes. 此外,您需要保留静态基本价格值,以便您可以对其进行所有计算,而不是保持所有更改的运行总计。 Try this:
尝试这个:
$("#status").change(function () {
var price2 = $(this).data('base-price');
if ($("option:selected", this).val() == "3") {
new_price2 = price2;
} else {
new_price2 = price2 - 10;
}
$('.prices').text(new_price2);
}).change();
Try this: 尝试这个:
$( "#status" ).change(function () {
var price2 = ($(".prices").text());
$('.prices').text('');
var value = $( "#status option:selected" ).val();
if(value=="3"){
new_price2 = price2;
}
else{
new_price2 = price2 - 10;
}
$('.prices').html(new_price2);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.