November 10, 201511 yr Glad to be here again! Today for two hours can't solve task with checkbox. Code working (sum values) only if input radio and input checkbox is checked. If i check only one input radio or only on input checkbox i get an error. Please, give me idea how i can make my code work if i check only one input. I need to put value in div. And at the same time i need to sum values if i check both radio button and checkbox <form class="contact form-inline signup" name="contact" role="form" id="signupForm"> <input type="radio" name="sits_count" id="optionsRadios1" value="20544"> <label class="sits" for="optionsRadios1">Одноместное (20544 руб.)</label> <br> <input type="radio" name="sits_count" id="optionsRadios2" value="13992"> <label class="sits" for="optionsRadios2">Двухместное (13992 руб.)</label> <br> <input style="margin-left:19%" type="radio" name="sits_count" id="optionsRadios3" value="11760"> <label class="sits" for="optionsRadios3">Трехместное (11760 руб.)</label> <br> <input style="margin-left:19%" type="checkbox" class="messageCheckbox" name="avia-transfer" id="avia-transfer" value="11000"> <label class="sits" for="avia-transfer">авиаперелет, трансфер, страховка (11000 руб.)</label> </form> <div class="sum"></div> var sumCheckbox, sum, wholeSum = $('.sum'), sumRadio, sumRubles; $('.signup input').on('change', function () { sumRadio = parseInt($('input[name="sits_count"]:checked').val()); if ($('input[type=radio]:checked')) { sum = sumRadio; } if (($('input[type=checkbox]:checked')) && ($('input[type=radio]:checked'))) { sumCheckbox = parseInt($('input[name="avia-transfer"]:checked').val()); sum = sumCheckbox + sumRadio; } sumRubles = '<b>' + "Сумма:" + '</b>' + " " + sum + " " + "руб."; wholeSum.html(sumRubles); }); Fiddle Edited November 10, 201511 yr by fleur
November 11, 201511 yr The problem is that both your conditionals always return true, you can test this by logging something to the console in your second if statement.So sum will always equal sumCheckbox + sumRadio, however if you only check one type of input the other will return NaN which is why you're getting the error.You'd need to check the length property on the jQuery objects, or use $('input[type=checkbox]).is(':checked')....or you could just get rid of the conditionals altogether and just use a default value of 0. $('.signup input').on('change', function () { var sumRadio = parseInt($('input[name="sits_count"]:checked').val()) || 0; var sumCheckbox = parseInt($('input[name="avia-transfer"]:checked').val()) || 0; var sum = sumCheckbox + sumRadio; $('.sum').html('<b>Сумма:</b> ' + sum + ' руб.'); });
November 13, 201511 yr Author Wynn, thank you in advance for help! I see, that i have to put default values - 0. It's exactly what i want, thank you
Create an account or sign in to comment