javascript foreach onclick

3.1k views Asked by At
<? foreach($words as $word): ?>
<li>
    <button onClick="reply_click()">Show</button>
    <h4><?php echo $word['Word']['en_words'] ?></h4>
</li>
<? endforeach; ?>
<script>
function reply_click() {
    $("h4").toggle("slow");
}
</script>

When I click 'button' - shows all, in every foreach, but must show in only one. Where I must used 'this' that this script work?

5

There are 5 answers

0
Grundy On BEST ANSWER

Yet another variant pass this to function

<button onclick="reply_click(this)">Show</button>

<script>

function reply_click(btn) {
    $(btn).next("h4").toggle("slow");
}
</script>
1
raso On

If you are using jQuery, depending on the situation you can select the heading inside the click handler function like one of the solutions below;

$(this).next("h4");

$(this).closest("h4");

$(this).siblings("h4");

Documentation

0
Nimeshka Srimal On

Use next() - https://api.jquery.com/next/

Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

<button onClick="reply_click(this)">Show</button>

<script>
function reply_click(e) {
    $(e).next("h4").toggle("slow");
}
</script>

If you want to avoid the inline click handler, you can add a class to your button and change the script to this.

<button class="toggleChild">Show</button>
<script>
$(".toggleChild").on("click", function(){
    $(this).next("h4").toggle("slow");
});
</script>
5
Tushar On

Don't use inline handlers.

Better Approach:

$('ul').on('click', 'button', function() {
    $(this).next('h4').show();
});
1
Radonirina Maminiaina On

You can try this:

<li>
    <button onClick="reply_click(this.nextElementSibling)">Show</button>
    <h4><?php echo $word['Word']['en_words'] ?></h4>
</li>

function reply_click(el) {
    $(el).toggle("slow");
}

The NonDocumentTypeChildNode.nextElementSibling read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.

Source

Thank you @Grundy