1

The following code works fine as below, but I can't write it as a loop structure. I need a loop because 26, 27, 28 are values of a Smarty variable in a template file (so 26, 27, 28 has to be replaced with JavaScript variable defined based on a Smarty variable).

<script type="text/javascript">
  $(document).ready(function(){

    var name = "product_data";

    $("#button_cart_26").click(function () {
      $('input:radio[name="'+name+'"]')[0].checked = true;
    });

    $("#button_cart_27").click(function () {
      $('input:radio[name="'+name+'"]')[1].checked = true;
    });

    $("#button_cart_28").click(function () {
      $('input:radio[name="'+name+'"]')[2].checked = true;
    });

  });
</script>

I've tried, for example something like this:

<script type="text/javascript">
  $(document).ready(function(){

    var name = "product_data";

    var index;
    var a = [26, 27, 28];
    for (index = 0; index < a.length; ++index) {
        //alert("#button_cart_"+a[index]);      //alert is OK

        $("#button_cart_"+a[index]).click(function () {
          $('input:radio[name="'+name+'"]')[index].checked = true;
        });
    }   

  });
</script>

Can you help, please?

Emit
  • 33
  • 1
  • 6
  • I thought I had an easy answer, but it turned out it was a brain fart. Can you tell us what exactly is not working and of there are any error messages in the console? – Constantin Groß Feb 11 '17 at 22:48
  • With the loop structure example, I didn't get the same result as with the "non-loop" code. More exactly, when click the HTML button with id = "#button_cart_27", the corresponding radio button, remains unchecked. gaetanoM's answer solve the problem. – Emit Feb 11 '17 at 23:42

1 Answers1

2

Your issue is the index variable. Because it is inside a for loop and used after, on click event. A possible solution can be based on IIFE: Immediately Invoked Function Expression in order to preserve the index value.

The snippet:

var name = "product_data";

var index;
var a = [26, 27, 28];
for (index = 0; index < a.length; ++index) {
  (function(index) {
    $("#button_cart_" + a[index]).click(function () {
      $('input:radio[name="' + name + '"]')[index].checked = true;
    });
  })(index);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form>
    <input type="radio" name="product_data">
    <input type="radio" name="product_data">
    <input type="radio" name="product_data">
</form>

<button type="button" id="button_cart_26">Click Me 26</button>
<button type="button" id="button_cart_27">Click Me 27</button>
<button type="button" id="button_cart_28">Click Me 28</button>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61