0

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>
0

5 Answers 5

1

Just select the buttons by their value attribute:

$(document).ready(function(){

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

});
Sign up to request clarification or add additional context in comments.

1 Comment

it's this.id, or $(this).attr('id') - not this.attr('id')
0

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>

Comments

0

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.

2 Comments

.delegate is obsolete in jQuery 1.7+
@Alnitak - Added on implementation also in case OP is using latest jQuery.
0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.