Jetoox
Jetoox

Reputation: 1437

How to set buttons with dynamic ID's clickable jquery

I have form that goes like this:

<?php foreach($userID as id):?>

<input type="button" id="ok_<?php echo id?>" value="ok" />
<input type="button" id="cancel_<?php echo id?>" value="cancel" />

<?php endforeach;?>

<script>
$(document).ready(function(){

//how do i set the click events of these buttons, assuming i have 3 sets of the of the ok and cancel buttons.

});
</script>

Upvotes: 0

Views: 1541

Answers (5)

PHP Connect
PHP Connect

Reputation: 549

The simplest thing you can do is the better assign one class to your buttons then give the event

<?php foreach($userID as id):?>
<input class="event" type="button" id="ok_<?php echo id?>" value="ok" />
<input class="event" type="button" id="cancel_<?php echo id?>" value="cancel" />

<?php endforeach;?>

<script>
$(document).ready(function(){
     $(".event").click(function() {
           // click event code
     });  

});
</script>

Upvotes: 0

Daff
Daff

Reputation: 44215

Just select the buttons by their value attribute:

$(document).ready(function(){

    $('[value="ok"]').on('click', function(ev) {
        alert($(this).attr('id'));
    });

});

Upvotes: 1

iWantSimpleLife
iWantSimpleLife

Reputation: 1954

Why not set css classes to them. then attach the event to the class.

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69915

You can use delegate and attach only 1 handler for each of the type of buttons. It will take care of any number of buttons click event. Try this.

$(document).delegate('input[id=^"ok_"]', 'click', function(){
      //Write code here
}).delegate('input[id=^"cancel_"]', 'click', function(){
      //Write code here
});

.delegate() reference: http://api.jquery.com/delegate/

If you are using jQuery ver 1.7+ then you can use on with is similar to delegate except for the first 2 arguments interchanged.

$(document).delegate('click', 'input[id=^"ok_"]', function(){
      //Write code here
}).delegate('click', 'input[id=^"cancel_"]', function(){
      //Write code here
});

Note: In the above code it is always better to provide a container which will contain those elements instead of specifying document to reduce the scope.

Upvotes: 0

tftd
tftd

Reputation: 17032

I believe this is what you need:

<script type="text/javascript">
    $(document).ready(function(){
        $('input[id*=ok_]').bind('click', function(e){
            console.log($(this));
        });
        $('input[id*=cancel_]').bind('click', function(e){
            console.log($(this));
        });
    })
</script>

Upvotes: 0

Related Questions