Home > Mobile >  My Javascript in webflow only works in first div. What am I doing wrong? (Radio buttons)
My Javascript in webflow only works in first div. What am I doing wrong? (Radio buttons)

Time:06-05

So I am creating this price-calculator for my Danish website in Webflow.

I wrote the JS as $('element').on('change', function() {..}) and it actually works. But only on the first Div.

I figured if I put in all the HTML code it would just be too much, so I made a short version with the relevant code.

$(document).ready(function() {

  var total;

    $('.mulighed').on('change', function() {

      total  = $("[type='radio']:checked").val();
      $('#total').html('Kr. '   $("[type='radio']:checked").val());

  });

});
.mulighed{margin: 25px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div class='row'>
    <input type='radio' class='mulighed' value='5'></input>
    <input type='radio' class='mulighed' value='10'></input>
    <input type='radio' class='mulighed' value='15'></input>
  </div>
  <div class='row'>
    <input type='radio' class='mulighed' value='150'></input>
    <input type='radio' class='mulighed' value='50'></input>
    <input type='radio' class='mulighed' value='100'></input>
  </div>
  <div class='row'>
    <input type='radio' class='mulighed' value='1000'></input>
    <input type='radio' class='mulighed' value='1500'></input>
    <input type='radio' class='mulighed' value='500'></input>
  </div>
  <p id='total'>0</p>
</form>

CodePudding user response:

You need to convert the value to an integer first, $(this) refers to the element the change event is acting on.

$(document).ready(function() {

var total=0;

  $('.mulighed').on('change', function() {
    total  = parseInt($(this).val());
    $('#total').html('Kr. '  total);
});
});

UPDATE: The following code allows you to subtract as well.

$(document).ready(function() {
var total=0;
$('input').on('click', function(e) {
  //e.preventDefault();
  if(!$(this).data("log")){
    $(this).prop("checked", true)
    $(this).data("log",true)
    total  = parseInt($(this).val());
    $('#total').html('Kr. '  total);
  }
  else{
    $(this).prop('checked', false);
    $(this).data("log",false)
    total -= parseInt($(this).val());
    $('#total').html('Kr. '  total);
  }
});
});
  • Related