简体   繁体   中英

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 . AN old price is 100 $. if user is student or pupil, I want make him discount -10 $. So when user choose option student or pupil price is changed from 100 to 90$. But when user choose option again to pupil it must not be change the price, but it changes it to 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.

you can ask why I used each function ? The option: other is selected and first time page shows price 110$. each function fixed this problem. I have also JS fiddle, you can check it. Sorry for my English Language.

DEMO

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

$( "#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. 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();

Example fiddle

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);
})

DEMO here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM