João Pedro Silva
João Pedro Silva

Reputation: 23

How call a Jquery function in the OnClick event?

I need to create a jquery function and call this function in the onClick(), but I need to use this function in a lot of buttons, so I can't use the button's id. how could i do this?

This is an idea of what I need.

Jquery:

ShowModalBT = function( nameModal ){
    $( "#"+nameModal ).modal("show");                               
};

HTML:

<input type='button' onClick='ShowModalBT("a")'>

Upvotes: 0

Views: 6492

Answers (6)

Prem Anand
Prem Anand

Reputation: 1496

Add a class to the Selector & trigger modal on a click event

$(document).on('click','.btn',function(){
$("#myModal").modal();
})

JSfiddle Example for Modal

Upvotes: 1

Niranjan Borawake
Niranjan Borawake

Reputation: 1638

It seems you want to open a different modal on different button clicks.

You could try it this way, just add modal id's as data-attributes to the buttons.

$('input[type="button"]').click(function (event) {
    var modalName = $(event.currentTarget).attr('data-modal-name');
    $('div').text('Opening modal '+ modalName);
    //$("#"+modalName).modal("show");       
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type='button' data-modal-name = "a" value="Open Modal A">
<input type='button' data-modal-name = "b"  value="Open Modal B">
<input type='button'data-modal-name = "c"  value="Open Modal C">

<div></div>

Upvotes: 1

OliverJ90
OliverJ90

Reputation: 1311

If it's the same function you're calling you could use the class of each button, something like:

<input type="button" class="modalButton">

$('.modalButton').click(function(){

   var id = $(this).attr('id');
   //do stuff with id 

});

Upvotes: 0

Jesper We
Jesper We

Reputation: 6087

Something along the lines of this:

<input type='button' class='triggerModal' id='a'>
<input type='button' class='triggerModal' id='b'>

Then in your script:

$('.triggerModal').click( ShowModalBT );

function ShowModalBT( event ) {
    var arg = $(event.target).attr('id');
    ....
}

Upvotes: 0

Tomasz
Tomasz

Reputation: 96

You can try to add a class to your input element and call it from jquery like:

<input type='button' class="xxx">

and then in jquery use

$('.xxx').on('click',function(){
    $(this).modal("show");  
});

Upvotes: 0

Jamie Barker
Jamie Barker

Reputation: 8246

With jQuery you can use any CSS selector, and then some. Just add a class to the buttons you want to have this functionality and write your code to suit. Example:

$('.MyButtons').on('click', function() {
   //Click Function Code Here
});

Upvotes: 2

Related Questions