Mike U
Mike U

Reputation: 3061

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/

Upvotes: 11

Views: 17716

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

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>

Upvotes: 10

PSL
PSL

Reputation: 123739

Try this:-

You need to pass in function reference to the obj.each callback. obj.each(Display(code)) is wrong, it should be obj.each(Display) ; but since here you want to pass in the variable, you can invoke it inside an anonymous function.

Demo

 $(".output").each(function(){ 
                Display(code, this)});
        });

Script

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


function Display(code,$this) {

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

Upvotes: 5

Related Questions