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.
Related
I'm trying to Use a combination of JS and Jquery here to select the input text (a few elements previous), when the button is clicked.
I know how to do this just using JS but i want to understand how to do this using jQuery. I get the error message in console: TypeError: ele.setSelectionRange is not a function. Which I take it means that it is not defining the Input Value the way I need it to.
I'm not using ID or Class here to identify the input.
Can someone help me here? Thanks
JS
$(document).ready(function () {
$('.jimmy').click(function(e){
e.preventDefault;
jimsFunction(this);
});
});
function jimsFunction(input) {
let ele = $(input).parent().siblings(':first-child').children();
ele.select();
ele.setSelectionRange(0, 99999);
navigator.clipboard.writeText(ele.value);
alert("Copied: " + ele.value);
}
HTML
<div class="colbody">
<div>
<input type="text" value="www.brave.com" readonly>
</div>
<div>
View
</div>
<div>
<button type="button" class="jimmy">Copy URL</button>
</div>
</div>
setSelectionRange(0, 99999) is not a method on jQuery object. Use it on DOM element.
So try: [0]
Example:
$('.jimmy').click(function(e) {
e.preventDefault;
jimsFunction(this);
});
function jimsFunction(input) {
let ele = $(input).parent().siblings(':first-child').children();
ele[0].select();
ele[0].setSelectionRange(0, 99999);
navigator.clipboard.writeText(ele[0].value);
alert("Copied: " + ele[0].value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colbody">
<div>
<input type="text" value="www.brave.com" readonly>
</div>
<div>
View
</div>
<div>
<button type="button" class="jimmy">Copy URL</button>
</div>
</div>
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>
How do you change the name of text within a div that your selector is inside of? In other words, I'd like to click on a button and change the text of the text above the button (within the same div).
For example, in my html, there is a button and a title above it. Once the button is clicked, I'd like the title above it to change to the id of the button.
This problem is similar to this question, but I'm having difficulty changing the text within the div that the selector is in.
Below is my attempt to grab the id of the button, and change the text within the div container.
Javascript (my attempt) (codepen here):
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id')
$('#title').find($(this)).html(desired_name);
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p id="title">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name1">NAME</button>
</div>
<div>
<p id="title">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name2">NAME</button>
</div>
Have you tried $(this).siblings("p")
This will select the <p> above the button
Have you tried jquery .prev()
https://api.jquery.com/prev/
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id')
$(this).prev().html(desired_name);
});
You can use the jQuery method siblings() to select the <p> element inside your <div> container.
However I recommend using a class as a unique selector inside your container.
$('.btn.btn-default').on('click', function() {
$(this).siblings(".desired-name").text($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="desired-name">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name1">NAME</button>
</div>
<div>
<p class="desired-name">Temporary Button Title That Should be 'true_name1'</p>
<button class="btn btn-default" id="true_name2">NAME</button>
</div>
Change the ID's to classes for starters. Then target them like this:
$('.btn.btn-default').on('click', function() {
var desired_name = $(this).attr('id');
$(this).prev(".title").text(desired_name);
});
I have the following form fields:
<div id="filename-url-container">
<div class="form-inline form-group">
<input name="filename[]" class="form-control" placeholder="Filename" type="text">
<div class="input-group">
<input name="url[]" class="form-control" placeholder="URL" type="text">
<span class="input-group-btn">
<button class="btn btn-default btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
</div>
I want to grab the first child each time the button is pressed and append it to the bottom of the filename-url-container div without the values of the original cloned fields.
I tried to get this to work but it's not appending correctly:
$('#filename-url-container').on('click', '.btn-add', function (e) {
e.preventDefault();
var formGroup= $('#filename-url-container :first-child');
$('#filename-url-container').append(formGroup);
console.log(controlForm);
});
You should .clone the elements before appending them - as written your code would simply take the existing elements and try to move them to exactly the same place.
You also need to constrain your selector, else it will pick every :first-child element within the container, not just the one that's the immediate child:
$('#filename-url-container').on('click', '.btn-add', function (e) {
var formGroup= $('#filename-url-container > :first-child').clone(true);
formGroup.find('input').val(''); // erase values
$('#filename-url-container').append(formGroup);
});
demo at http://jsfiddle.net/alnitak/dvqgnga0/
$('#filename-url-container').on('click', '.btn-add', function (e) {
e.preventDefault();
var formGroup= $('#filename-url-container div:first-child').html();
$('#filename-url-container').append(formGroup);
console.log(formGroup);
});
You need to append html, not object it self.
http://jsfiddle.net/npdh2v3L/
I don't think you are using :first-child correctly. :first-child refers to the first child of the type to it's left. Other than that you just need to get rid of those values. Additionally, I'm not seeing a need to Event.preventDefault() since you are not using a submit button.
$('#filename-url-container .btn-add').click(function(){
var clone = $('#filename-url-container .form-group:first-child').clone(true);
clone.find('input').val('');
$('#filename-url-container').append(clone);
});
I am using button tag <button value="1">1</button>
Basically I want when this button is pressed, the value of the button is set into editable div.
<div contentEditable='true'; >Value from button</div>
Is that possible with client side script?
Try the below code: (EDIT Modified as user has subsequently indicated that he will use this to create a calculator)
We are doing the following:
Assign an onclick function to the button. This will be called whenever the button is clicked.
An ID is added to both the button tag and the div tag to access them using the getElementById method in JavaScript.
this.value will pass the value of the button that is currently clicked to the function.
Inside the JavaScript, we get the value of the button and set it to the innerHTML of the required div. Note: Since += is used, it would take the current contents of the div and append the button's value to it (like, if 1 is pressed followed by 2, the div would have 12 as its content).
HTML
<button value="1" id='btn1' onclick='setBtnValue(this.value);'>1</button>
<button value="2" id='btn2' onclick='setBtnValue(this.value);'>2</button>
<div contentEditable='true' id='div1'></div>
Javascript
function setBtnValue(btnVal){
document.getElementById('div1').innerHTML += btnVal;
}
Demo
you can use getElementById method.
<button value="1" onclick="function1(this)">1</button>
<div contentEditable='true' id='edit'>value from button</div>
<script type='text/javascript'>
function function1(obj){
document.getElementById("edit").innerHTML=obj.value;
}
</script>
Yes this is possible but you have to assign the id.
<button onclick="put()" id="but" value="1">1</button>
<div id="pol" >Value from button</div>
Now with function use
function put()
{
document.getElementById("pol").innerHTML = document.getElementById("but").value;
}
DEMO
HTML:
<button value="1" class="button">1</button>
<button value="2" class="button">2</button>
<div contentEditable="true" id="element"></div>
JS:
var buttons = document.getElementsByClassName('button');
var div = document.getElementById('element');
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function(event) {
div.innerHTML = event.target.value;
});
}
Working example.