Simulate click with javascript with no element ID - javascript

<button
type="button"
class="blue"
data-events="click:onAddNote"
data-events-target="cpoe-LabResultDetailView"
>
Add Note
</button>
I'm trying to simulate / prompt a click of this button when I press a shortcut key sequence. However, I haven't been successful with anything other than through the class "blue", which works but also activates something else. How do I target the "data-events" or "data-events-target"?
Is there a way to something similar to:
$("click:onAddNote").trigger("click");

You can use querySelector and select the button with its attributes
var button = document.querySelector('[data-events="click:onAddNote"]');
button.onclick = ()=>console.log('Clicked');
button.click()
<button
type="button"
class="blue"
data-events="click:onAddNote"
data-events-target="cpoe-LabResultDetailView"
>
Add Note
</button>

Why not just this?
const button = docuemnt.querySelector('button')
button.click()

There are many ways to select the <button> element.
Method-1
In the example below, the click event is fired by selecting the first <button> element with the .blue class style applied.
let button = document.getElementsByClassName('blue');
button[0].addEventListener('click', function() {
console.log("clicked");
});
<button type="button" class="blue">Add Note</button>
Method-2
The click event of the <button> element with the .blue class style applied using jQuery can be rendered as follows:
$(".blue").on('click', function(event) {
console.log("clicked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="blue" data-events="click:onAddNote" data-events-target="cpoe-LabResultDetailView">Add Note</button>

Targeting the "data-events" attribute is simple, like this ...
$('button[data-events="click:onAddNote"]').on('click', function(){
console.log('clicked!');
});
<button
type="button"
class="blue"
data-events="click:onAddNote"
data-events-target="cpoe-LabResultDetailView"
>
Add Note
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
See the jquery documentation for more information on running handlers -- Here

Related

How to add class to the clicked button and remove a class to the previously clicked button

How will I add a class to the clicked button and remove a class to the previously clicked button. I want to have a single active button only per click
My html looks like this
<div class="nav-button">
<button id="btn-all">All</button>
<button id="btn-chicken">Chicken</button>
<button id="btn-pizza">Pizza</button>
<button id="btn-pasta">Pasta</button>
<button id="btn-drinks">Drinks</button>
</div>
And my jquery looks like this
$('.nav-button button').on('click', function(){
$(this).addClass("active")
})
I dont want to select the buttons one by one because this group of button is dynamic. I just only use the html example above to show my buttons in html
You can simply first remove the class from all buttons:
$("div.nav-button button").removeClass('active');
So you can do:
$('.nav-button button').on('click', function(){
$("div.nav-button button").removeClass('active');
$(this).addClass("active");
})
.active {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav-button">
<button id="btn-all">All</button>
<button id="btn-chicken">Chicken</button>
<button id="btn-pizza">Pizza</button>
<button id="btn-pasta">Pasta</button>
<button id="btn-drinks">Drinks</button>
</div>

One function - many buttons

I have in HTML a button with id="button1".
We have JavaScript function:
$('#button1').click(function() { ... } );
It works well.
But what if we have 100 buttons with different IDs?
I can duplicate 100x function. However, this is not very elegant and good solution.
How to easily and effectively solve a problem for many buttons?
The function performed is the same for all buttons.
Add a class bind to this:
$(document).ready(function(){
//dot (.) selector binds to classes
$('.boundButton').click(function(){
//clicked button
var $this = $(this);
alert($this.attr('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" class="boundButton">1</button>
<button id="2" class="boundButton">2</button>
<button id="3" class="boundButton">3</button>
You need to use a class instead of ID. For example, your JS code could look like:
$('.button-class').click(function() { ... } );
and your HTML might look like
<button name='example' class='button-class' id='exampleID'>Button Text</button>
Here is the basic example:
$(document).ready(function () {
$(".btn").on("click", function(){ //attach click event to all buttons with class "btn"
console.log($(this).attr("id")); //$(this) refers to the button clicked
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>

Jquery change status of button on click

I have 6 Buttons, I gave each button a Default Status of false, if the user clicks on a button that corresponding Status is switching to true. Now if I Switch a button all other button Statuses shall switch to false.
Something like this worked but what is a good way to Code this for many Buttons, I do not want to repeat myself that much:
toolOneStatus = false
$('#btn-tool-one').click(function() {
toolOneStatus = true;
toolTwoStatus = false; ....
}
You can use .data() for this. Check snippet below...
$('button').click(function(){
alert('status ' + $(this).data('status'));
if($(this).data('status')=="false"){
//do this
} else {
//do this
}
$(this).data('status','true')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" data-status="false">Button1</button>
<button type="button" data-status="false">Button2</button>
<button type="button" data-status="false">Button3</button>
<button type="button" data-status="false">Button4</button>
<button type="button" data-status="false">Button5</button>
<button type="button" data-status="false">Button6</button>
You can use a single click function and identify the button by a data-no attribute.
This sample adds a blue color to the active button while all others remain gray. The activeButton variable represents the number of the active button.
var activeButton = 0;
$('.mybtns').click(function() {
activeButton = $(this).data('no');
console.log('active='+activeButton);
$('.mybtns').css('background-color','rgb(221, 221, 221)');
$(this).css('background-color','lightblue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybtns" data-no="1">Test1</button>
<button class="mybtns" data-no="2">Test2</button>
<button class="mybtns" data-no="3">Test3</button>
<button class="mybtns" data-no="4">Test4</button>
<button class="mybtns" data-no="5">Test5</button>
<button class="mybtns" data-no="6">Test6</button>
<button class="mybtns" data-no="7">Test7</button>
To loop through each of the buttons and execute some code for each, you can use the aptly named .each() function available in jquery. You can find the documentation for it here - each()
Whenever a button is clicked, .each() executes the function for all the elements with class=buttons and set the status=false. Inside the function you can use the $(this) selector to select the object of the current iteration. Finally outside the loop, the button which triggered the event, is given status=true.
$('button').click(function() {
$(".buttons").each(function(index) {
// Looping through each element having class "buttons"
$(this).data("status", "false"); //Setting every button to false.
$(this).next().html($(this).data("status"));
});
$(this).data("status", "true"); // Outside the loop, setting status true for the button which triggered the click event.
$(this).next().html($(this).data("status"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttons" id="button1" data-status="false">Button1</button><span id="p1"></span>
<button type="button" class="buttons" id="button2" data-status="false">Button2</button><span id="p2"></span>
<button type="button" class="buttons" id="button3" data-status="false">Button3</button><span id="p3"></span>
<button type="button" class="buttons" id="button4" data-status="false">Button4</button><span id="p4"></span>

JQuery Detect Which File Upload Button Clicked [duplicate]

How to detect which dynamic button is clicked?
Note: The #dCalc Element is added dynamically...
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<input id="firstNumber" type="text" maxlength="3" />
<input id="secondNumber" type="text" maxlength="3" />
<input id="btn1" type="button" value="Add" />
<input id="btn2" type="button" value="Subtract" />
<input id="btn3" type="button" value="Multiply" />
<input id="btn4" type="button" value="Divide" />
</div>
</div>
$("input").click(function(e){
var idClicked = e.target.id;
});
$(function() {
$('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});
Since the block is added dynamically you could try:
jQuery( document).delegate( "#dCalc input[type='button']", "click",
function(e){
var inputId = this.id;
console.log( inputId );
}
);
demo http://jsfiddle.net/yDNWc/
jQuery can be bound to an individual input/button, or to all of the buttons in your form. Once a button is clicked, it will return the object of that button clicked. From there you can check attributes such as value...
$('#dCalc input[type="button"]').click(function(e) {
// 'this' Returns the button clicked:
// <input id="btn1" type="button" value="Add">
// You can bling this to get the jQuery object of the button clicked
// e.g.: $(this).attr('id'); to get the ID: #btn1
console.log(this);
// Returns the click event object of the button clicked.
console.log(e);
});
Detect event on dynamically created elements
Two examples, jQuery and vanilla JavaScript ahead:
jQuery
Use the .on() method with delegated events, which follows this syntax:
$("staticParentSelector").on("eventName", "dynamicChildSelector", handlerFn);
Example:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
$("#dBlock").on("click", '[type="button"]', (evt) => {
const staticParent = evt.delegateTarget; // This is #dBlock
const dynamicChild = evt.currentTarget; // This is the dynamic child
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
JavaScript
The same in vanilla JavaScript can be achieved like the following, with the difference in that JS has no notion of delegateTarget (which is a jQuery property on their proprietary Event object) therefore the slight modification:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
document.querySelector("#dBlock").addEventListener("click", (evt) => {
const staticParent = evt.currentTarget; // This is #dBlock
const dynamicChild = evt.target.closest('[type="button"]'); // This is the dynamic child
if (!dynamicChild) return; // Do nothing (no designated dynamic child is clicked)
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
as you can see neither of the above implementations stick solely on the Event.target Element per-se, for the reason that if we had i.e. an icon inside the buttons (like: <button id="add" type="button">Add <i class="icon-plus"></i></button>) and if a click landed on the icon directly, the Event.target would end up being the icon, not the Button Element - and we might miss to retrieve the needed data, like the specific button ID etc, resulting in a broken app logic.

HTML + JS How to change/unchange text onclick

I would like to write a JS that changes text on a button when clicked (to 'SHOW'), but when another button is clicked then the previously clicked button will change its text from 'SHOW' to initial text (eg 'A')
Scenario:
1. click on button A -> 'A' changes to 'SHOW'
2. click on button B -> 'B' changes to 'SHOW' but also 'SHOW'(from button A) changes back to 'A'
<button id="button1" value="A">A</button>
<button id="button2" value="B">B</button>
<button id="button3" value="C">C</button>
Above you will find example buttons i have in html file.
In JS file i have:
$("button1").on('click', function () {
$('.btn_click').removeClass('btn_click');//this is a css class that changes bg color
$(this).addClass('btn_click');
$(this).text('SHOW');
});
previously i used class selector not id one, but still could not accomplish what i wanted. The add and remove CSS works really ok
I think this is what you are looking for:
$("button").click(function() {
var clicked_button = $(this);
$("button").each(function() {
if($(this).is(clicked_button)) {
$(this).text('SHOW');
}
else {
$(this).text($(this).attr('value'))
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1" value="A">A</button>
<button id="button2" value="B">B</button>
<button id="button3" value="C">C</button>
Check working example here https://jsfiddle.net/prxd81vk/
You already have your solution, because when you add a class to the last pressed button, you can use it to change the text back:
$("button").on('click', function () {
$('.btn_click')
.text($('.btn_click').val())
.removeClass('btn_click');//this is a css class that changes bgcolor
$(this).addClass('btn_click');
$(this).text('SHOW');
});
You must use $("#button1") to properly select the button by id. This onClick is not actually associated to any of the buttons.
You need to keep track of the old text of the button and revert back to it when another button is pressed.
Example:
$("button").on('click', function () {
$('.btn_click').removeClass('btn_click');//this is a css class that changes bg color
$("[data-old-text]").each(function () {
$(this).text($(this).attr("data-old-text"));
$(this).removeAttr("data-old-text");
});
$(this).addClass('btn_click');
$(this).attr("data-old-text", $(this).text());
$(this).text('SHOW');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button1">A</button>
<button id="button2">B</button>
<button id="button3">C</button>
Use this :
Button 1 click :
$('#button1').click(function () {
$('#button1').text('Show');
});
Buttton 2 click :
$('#button2').click(function () {
$('#button2').text('show');
$('#button1').text('old value');
});
I would change targeting elements from id to class attribute.
<button class="button" value="A">A</button>
<button class="button" value="B">B</button>
<button class="button" value="C">C</button>
The script would then first clear the 'btn_click' class from any other buttons, and then apply the 'active' class to the button that was clicked.
$("button").on('click', function () {
$('.button').removeClass('btn_click');//this is a css class that changes bg color
$(this).addClass('btn_click');
$(this).text('SHOW');
To select element by ID you must use $("#button1").
Try like this:
$("#button1").on('click', function () {
$('.btn_click').removeClass('btn_click');//this is a css class that changes bg color
$(this).addClass('btn_click');
$(this).text('SHOW');
});
And after that add whatever you want to do with other two buttons (set A,B,C).
You can try this code..
<script>
$(document).ready(function()
{
$('#button1').click(function()
{
$('.btn_click').removeClass('btn_click');//this is a css class that changes bg color
$(this).addClass('btn_click');
$(this).text('Show');
$('#button2').text('B');
});
$('#button2').click(function()
{
$('#button1').text('A');
$(this).text('Show');
});
});
</script>

Categories

Resources