Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery call function with each item in selection

I am trying to call a function using each object found in jQuery selection

<a href="#" class="can-click" data-code="a">a</a>
<a href="#" class="can-click" data-code="b">b</a>
<a href="#" class="can-click" data-code="c">c</a>
<a href="#" class="can-click" data-code="d">d</a>

Each a element has a data-code value:

<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>

Each p element has a data-value:

$(document).ready(function () {
    $(".can-click").click(function () {
    var code = $(this).data("code");
        $("output").each(Display(code));
    });
});

What I want is that when you click on the anchor a you will get an alert showing you the data-code from the anchor clicked and the data-value for each p, with the code attached I want 3 alerts to pop up.

function Display(code) {

    var p = $(this);
    var value = p.data("value");
        alert(code + " " + value);
}

Here is a link to the code in jsfiddle: http://jsfiddle.net/mikeu/XFd4n/

like image 255
Mike U Avatar asked May 20 '13 04:05

Mike U


1 Answers

You have to use . for class-selectors and pass this object when you are calling Display function like,

$(document).ready(function() {
  $(".can-click").click(function(e) {
    e.preventDefault();
    var code = $(this).data("code");
    $(".output").each(function() { // use . for class selectors
      Display(code, this); // pass this from here
    });
  });
});

function Display(code, ths) { // ths = this, current output element
  var p = $(ths), // use ths instead of this
    value = p.data("value");
  console.log(code + " " + value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="can-click" data-code="a">a</a>
<a href="#" class="can-click" data-code="b">b</a>
<a href="#" class="can-click" data-code="c">c</a>
<a href="#" class="can-click" data-code="d">d</a>
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>
like image 83
Rohan Kumar Avatar answered Oct 18 '22 11:10

Rohan Kumar