Dominique Deschatre
Dominique Deschatre

Reputation: 119

How to pass an array id into jquery selector?

I have an element with an array id id="x[]" that vary depending on the number of elements that I have on a database. It's basically a x button to delete a certain table row in the database.

<div align="center" id="x[]" class="x">
<a href="#"><img src="x 2.png" alt=""></a></div>

Problem is, I don't know how to pass this id into the jQuery selector. I want to change the form action to delete the row and create an hidden input to get the paramater I need from another field with an array id id="codsinmov[]" with the same index as x[]. What I have so far is:

$(document).ready(function(){
    for(var i=0; i<x.length; i++) {
    $('#x[i]').click(function(){
        var $hiddenInput = $('<input/>',{type:'hidden',id:codsinmovesse, name:codsinmovesse});
        $hiddenInput.val($('#codsinmov[i]').val());
        $hiddenInput.appendTo('#tabelaeditavel');
        $('#form').get(0).setAttribute('action', 'deletemoviment.php');
        $('#form').submit();
    });
    }
});

But it doesn't work.. So, any ideas? Sorry, I'm a beginner at jQuery. Thank you very much!

Upvotes: 3

Views: 1909

Answers (2)

noa-dev
noa-dev

Reputation: 3641

If you want to add an eventListener to ALL elements you can simply do it like that

var $myButtons = $('.buttons');

That way the whole list of Elements are stored behind the variable $myButtons.

Now you can proceed as following:

$myButtons.on("click", function(event){
  console.log(this); // this will print out the clicked element
});

This way every element with the class .buttons is clickable and accessable.

If you want to dynamically select a single element with jquery depending on some value you have to exclude your [i] from the string

for example like that $('element:nth-child('+[i]+')');

Upvotes: 0

Roli Agrawal
Roli Agrawal

Reputation: 2466

you can use

$("div[id^='x['").click(function(){
    // write code here })

So this will execute on click of those ids of div which start from x. So as per my understanding You need not to use for loop here rather use 'this' keyword and do what you want.

I hope it will help you.

Upvotes: 1

Related Questions