Problem with change function in select option in jQuery

I have a slightly chosen form. When I change the parameters using JQUERY, .pricesa new suitable price appears in . The old price is $ 100. if the user is a student or student, I want to give him a discount of -10 $. Therefore, when the user selects an option, the student or student price changes from $ 100 to $ 90. But when the user again chooses the option for the student, he should not change the price, but he changes it to $ 80. Again, when you select a student option, the price has been changed to 70. I definitely want that if the user chooses an option: student or student, there will be a discount of -10 $.

you may ask why i used each function? The option is selected: otherand the first page shows the price of $ 110. each function fixed this problem. I have a JS script, you can check it out. Sorry for my English.

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

});
+4
source share
2 answers

You only need a handler changein your jQuery code. In addition, you need to maintain a static base price so that you can do all the calculations on this, and not support the total number of all changes. Try the following:

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

Script example

+2
source

Try the following:

$( "#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 is here.

0
source

All Articles