JQuery assign events to buttons - javascript

I have 50 dynamically generated HTML buttons as follows:
<input type="button" id="btn1" name="myButton" value="Click Me" />
<input type="button" id="btn2" name="myButton" value="Click Me" />
:
:
:
<input type="button" id="btn50" name="myButton" value="Click Me" />
Which is the best way to assign click event to all buttons using jQuery?
By using id or by using name attribute ?

Event listeners cost memory. You have to think carefully about how you should implement the listeners.
1. The straightforward way:
Do not use this
If the behaviour for each button is the same, use a class:
$(".btn").click(function() {
// Do something
});
If behaviour for each button is different, assign events to different #IDs
$("#btn1").click(function {
// Do something
});
2. Use .on():
jQuery 1.7 introduced .on() method that wraps all listeners to 1 method.
$("button").on("click", function() {
// Do something
});
However, we are still binding many listeners on the page.
3. Use a wrapper (use this!):
Wrap your buttons with a div and create one listener for it.
$("#wrapper").on("click", "button", function() {
// Do something
});
Useful resources:
Performance comparison
.on()

Best way would be to delegate to the surrounding container, that way you only have one listener rather than 50. Use .on()
https://api.jquery.com/on/
If you must assign to each button, figure out a way to write only one selector, like this:
$('button').click(function(){});
Note your selector may need to be more specific to target just these 50 buttons, as #Drewness points out in the comments.

if you have all the buttons inside of a container and you want the same function for all add the click handler to the container
DEMO
$("#container").on("click", function(e){
if(e.target.type =="button")
{
alert(e.target.id);
}
});
<div id="container">
<input type="button" id="test1" value="button1"/>
<input type="button" id="test2" value="button2"/>
<input type="button" id="test3" value="button3"/>
<input type="button" id="test4" value="button4"/>
<input type="button" id="test5" value="button5"/>
<input type="button" id="test6" value="button6"/>
something
<input type="text"/>
</div>

This would be an easy way to wrap it all up into one 'on' event and do something based on the button id;
<button id='button1'>button 1</button>
<button id='button2'>button 2</button>
<button id='button3'>button 3</button>
var mybuttons = $('#button1');
for(i=1;i<3;i++){
mybuttons = mybuttons.add($('#button'+i));
}
console.log(mybuttons);
mybuttons.on('click', function(){
var myid = $(this).attr("id");
console.log(myid);
//use a switch or do whatever you want with the button based on the id;
});
here's a fiddle http://jsfiddle.net/gisheri/CW474/1/

I would apply it to the parent element of the buttons. So if all of the buttons were in <div id="myButtons">:
$('#myButtons').on('click', 'button' function () {
// Do stuff...
});
The key is to be specific enough that you do not have to specify each selector but not too lose as there may be other buttons, etc. on the page that you do not want to include.
Updated code to include delegation.

I think it will be better if you use a common class name for all and handle click event by that class name.
$('.classname').click(function(){
//`enter code here`
});
Or you can handle event by tag name:
$('button').click(function(){
//'enter code here'
});
This method might effect the function of other buttons which are not included in the group of 50 buttons.

Try
$(".btn").click(function() {
// Do something
});

You can use following code:
$("#btn1").on("click",function(){
// Your code
});
$("#btn2").on("click",function(){
// Your code
});
and so on...

Related

.on or .click function works only once with same name form elements

I have a form in a php loop, and if there are 3 elements in the database, there are 3 forms with same name. Those forms do contain a button with the same name. So everything likes like this:
<form id="test">
<button id="testbutton"></button>
</form>
<form id="test">
<button id="testbutton"></button>
</form>
<form id="test">
<button id="testbutton"></button>
</form>
The problem appears when I try to call .on or .click function from javascript. It works only once.
This is the JS code:
$(document).ready(function () {
$('#testbutton').on("click", function() {
function();
});
});
The button fades out certain div's which have different names.
ID's Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements.
Give your elements a class instead :
<form>
<button class="testbutton"></button>
</form>
<form>
<button class="testbutton"></button>
</form>
<form>
<button class="testbutton"></button>
</form>
Now your selector can use the class:
$('form').on("click", ".testbutton", function(){ // event will bubble up to form
please try to bind event on button type rather than id like this
$(':button').on("click", function(){
// do other stuff
});
Please check here in fiddle
I have solved my problem with this sentence:
$(this).closest("form").find("input[name=testfield]").val()
It is a bit complicated to explain the problem, but the solution is here. Button click finds the closest form and closest value of the field required. So, my problem is gone, but thanks for all the help, you have helped me to clear out some doubts! :)

How to re-disable (disable) the text box on clicking a button or a link?

I have a script that enables the disabled text box when clicking on a button. But, I just don't know how to re-disable the text box again.
The coding is below.
HTML:
<div class="input-group">
<label for="some-tbox" class="input-group-addon">Label:</label>
<input id="some-tbox" type="text" class="input-box" value="some value" disabled>
<span class="input-group-btn">
<button class="enable" type="button">button</button>
</span>
</div>
JS:
$(".enable").click(function(){
$(this).parent().parent().children(".input-box").removeAttr("disabled");
$(this).toggleClass("disable");
$(this).toggleClass("enable");
});
$(".disable").click(function(){
$(this).toggleClass("enable");
$(this).toggleClass("disable");
$(this).parent().parent().children(".input-box").attr("disabled", "disabled");
});
And I have made a fiddle out of it. But, It's not working. Here is the link.
Instead of messing with adding and removing classes, just toggle the disabled property with:
$(".enable").click(function() {
$(this).closest('.input-group').find('input').prop('disabled', !$(this).closest('.input-group').find('input').prop('disabled'))
});
jsFiddle example
The problem is this line $(".disable").click(function(){ ...})
You are binding a click event handler to a class named disabled which was not available initially during page load, it appears dynamically later.
You need to delegate the event handler to some parent which always exist and then handle the event there, in this case you can do this:
$(".input-group").on('click', '.disable', function(){
$(this).toggleClass("enable");
$(this).toggleClass("disable");
$(this).parent().parent().children(".input-box").attr("disabled", "disabled");
});
jQuery's on function
You cann't bind an element ".disable" that don't exist , In that case you can rebind it when you changed it's class. Code behind may help you:
$(".enable").on("click",enabledClick)
function enabledClick (argument) {
$(".enable").parent().parent().children(".input-box").removeAttr("disabled");
$(".enable").toggleClass("disable");
$(".enable").toggleClass("enable");
$(".disable").on("click",disabledClick)
}
function disabledClick (argument) {
$(".disable").parent().parent().children(".input-box").attr("disabled", "");
$(".disable").toggleClass("enable");
$(".disable").toggleClass("disable");
$(".enable").on("click",enabledClick)
}

how to click a button using jQuery?

Here is the DOM :
<div class="form-actions">
<button class="btn btn-primary" type="submit">Save device</button>
</div>
I want to use Jquery to select the button and click on it?
I tried using : jQuery(".btn btn-primary").click()
which is not working
You are trying to select an element with both classes, therefore your selector should be .btn.btn-primary.
$('.btn.btn-primary').click();
You were trying to select a element with class .btn-primary that was a descendant of a .btn element.
Your selector is incorrect; because both classes are on the same element you need to separate them by . with no spaces:
jQuery(".btn.btn-primary").click()
You could use the jQuery trigger() method to trigger the behaviour of an existing event handler.
https://api.jquery.com/trigger/
example:
<button id='testButton'>Test</button>
<script>
$(function(){
$('#testButton').on('click' , function(){
alert("I've been clicked!");
});
//now on another event, in this case window resize, you could trigger
//the behaviour of clicking the testButton?
$( window ).resize(function() {
$('#testButton').trigger( "click" );
});
});
</script>
See the following:
https://api.jquery.com/trigger/
Use $(".btn-primary").trigger("click");
Hope that helps
Just incase you did not learn yet, you can always define an Id for the button and use it this way:
<div class="form-actions">
<button id="mybutton" class="btn btn-primary" type="submit">Save device</button>
</div>
$('#mybutton').click(function(){
//your code goes here
});
$( window ).load(function() {
$(".btn-primary").trigger('click');
});

jQuery input button click event listener

Brand new to jQuery.
I was trying to set up an event listener for the following control on my page which when clicked would display an alert:
<input type="button" id="filter" name="filter" value="Filter" />
But it didn't work.
$("#filter").button().click(function(){...});
How do you create an event listener for a input button control with jQuery?
First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:
$("#filter").click(function(){
alert('clicked!');
});
Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
So even if the order is this it will work:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
<input type="button" id="filter" name="filter" value="Filter" />
DEMO
$("#filter").click(function(){
//Put your code here
});
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})

How do I create a text box with a submit button that performs a callback on click to a javascript function using js or jQuery?

I'm new to javascript and am having a hard time finding the answer to this. Any help is appreciated.
If you had the following HTML:
<input type="text" />
<input id="button" type="button" value="Click Me" />
You can bind a function to be executed when a click event fires on that button like this:
$(function() {
$('#button').click(function() {
// Do logic here
});
});
Creating it all on the fly
You can insert the previous HTML into your document using jQuery. First select another element in the DOM which locates where you wish to insert the HTML:
$('#someElement')
Then you can use any of the jQuery insertion methods in order to inject some HTML of your own:
$('#someElement')
.append('<input type="text" />')
.append('<input id="button" type="button" value="Click Me" />');
Now that your elements are in the DOM, you can select them and bind a callback to the click event in the normal way:
$('#button').click(function() {
// Do logic here
});
the html :
<textarea id="txt"></textarea><input type="button" id="button">submit</input>
and the js:
var d = document.getElementById('button');// identifying the button
function myFunction(){
var text = document.getElementById('txt').value;//getting the user's input
// and whatever you want to do with the user's input
}
d.addEventListener('click',myFunction,false);//attaching myFunction to be called on the button click`
If you use jQuery, the syntax is a bit simpler :
$('#button').click(myFunction);
// or
$('#button').click(function(){
var text = $('#txt').val();
//and again your logic here
});

Categories

Resources