jQuery code not running when putting it on an if statement

94 views Asked by At

I'm trying to execute a jQuery script to change the data-url attribute based on which radio button is clicked/selected.

But my code won't work when I put it inside the if statement to check which radio button is active. It will successfully replace the data-url attribute though when executing without an if statement.

$('input[name="radio1"]').on('change', function() {
  if ($(this).val() == 'yearly') {
    var a = $('#samcart').data('url');
    $('#samcart').attr("data-url", "www.urlhere.com");
  } else if ($(this).val() == 'quarterly') {
    var a = $('#samcart').data('url');
    $('#samcart').attr("data-url", "www.url2here.com");
  } else {
    var a = $('#samcart').data('url');
    $('#samcart').attr("data-url", "www.url3here.com");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="samcart" class='samcart-popup-container' style='margin:auto;width:200px;align:center;' data-id='123' data-url='empty'>
  <div class='samcart-popup-button' type='button' class='btn btn-default css3button'>
    Join
  </div>

1

There are 1 answers

1
Ivan Buttinoni On

EDITED It's seem your code is good, I do not substantial changes, see the jsfille below:

https://jsfiddle.net/7tL6dfft/16/

HTML

<form action='#' method='get'>
<input type="radio" name="radio1" id="yearly" value="yearly"><label class="yearly-label four col" for="yearly">I have some text here</label>
<input type="radio" name="radio1" id="quarterly" value="quarterly"><label class="yearly-label four col" for="yearly">quarterly</label>
<input type="radio" name="radio1" id="weekly" value="weekly"><label class="yearly-label four col" for="yearly">weekly</label>

</form>
<a id="samcart" href='#' data-url='http://exmaple.com'>sam cart url</a>

JS

$(function(){
console.log("start");

$('input[type=radio][name=radio1]').on('change', function() {
  console.log("event",$(this).val());
  if ($(this).val() == 'yearly') {

    $('#samcart').data("url", "www.urlhere.com");
    $('#samcart').html("www.urlhere.com");
    var a = $('#samcart').data('url');
  } else if ($(this).val() == 'quarterly') {

    $('#samcart').data("url", "www.url2here.com");
    $('#samcart').html("www.url2here.com");
    var a = $('#samcart').data('url');
  } else {

    $('#samcart').data("url", "www.url3here.com");
    $('#samcart').html("www.url3here.com");
    var a = $('#samcart').data('url');
  }
  alert("new data-url: "+a);
});
})

May be you were mislead by

  • your debug, you take the "var a" before change the value
  • your browser, sometimes the change of attrs is not show by developer tool
  • the position of the js, you set your JS before the code in the loading chain, see $(function(){})