How to return value after event click - javascript

I try make simple case with 2 button like this.
$(document).ready(function(){
function tes(){
var result;
$("#wrapper").html('<button id="btn2">Button 2</button>');
$("#btn2").click(function(){
result = "How to passing this value?, After button 2 clicked"
})
return result;
}
$("#btn1").click(function(){
alert(tes());
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<div id="wrapper"></div>
How to pass value of variable result after button2 click, where element for button2 exists after button1 click?

Ok as you've no problem using jQuery. I think this is what you want
var result = '';
function tes(){
document.getElementById("wrapper").innerHTML = '<button id="btn2">Button 2</button>';
result = "How to passing this value?, After button 2 clicked"
}
var button = document.getElementById("btn1");
button.onclick = function(){
tes();
}
$(document).on('click', '#btn2', function(){
alert(result)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<div id="wrapper"></div>
Ps. You're trying to bind events on dynamically created elements and the way you're doing in your code is not the proper way. You can do that $(document).on('click', 'DOM_Element', function(){}). Just to let you know so you should have an idea when working on JS in future

Related

How to prevent click event on second times on a button

I have few buttons, when I click on those buttons some divs are creating automatically, but here I need to prevent to create any div when I click on next time on the same button on which I already clicked.
Code is below
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="details">
<button id="append">button1</button>
<button id="append">button2</button>
<button id="append">button3</button>
<div id="parent"></div>
</div>
SCRIPT
(function(){
var count = 0;
$('button').click(function(){
$('#parent').append('<div id="first'+count+'">text</div>');
count++;
});
});
Use the .one() method. This binds a handler that only runs once for each element.
$(function() {
var count = 0;
$('button').one("click", function() {
$('#parent').append('<div id="first' + count + '">text</div>');
count++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="details">
<button id="append">button1</button> <button id="append">button2</button> <button id="append">button3</button>
<div id="parent"></div>
</div>
Basic idea is creating click flag.
Flag is set to true once clicked and set to false if action is finished.
The action should be performed only if flag is false.
Like this:
(function(){
var count = 0;
var flag = false;
$('button').click(function(){
if(flag) return false; // Disable when action is on
// Action starts
flag = true;
$('#parent').append('<div id="first'+count+'">text</div>');
count++;
// Action ends
flag = false;
});
});
Here are three possible solutions:
Disable the button that was clicked by adding $(this).attr('disabled',true); inside anonymous click function.
Adding a data-enabled attribute to the buttons and checking it. Your HTML for a button becomes like this: <button id="append" data-enabled="true">button1</button> and then you add this to the anonymous click function:
(function(){
var count = 0;
$('button').click(function(){
if ( $(this).data('enabled') == 'false' ) return;
else
{
$(this).data('enabled', 'false');
$('#parent').append('<div id="first'+count+'">text</div>');
count++;
}
});
});
Create an array that with the button as keys and their enabled/disabled boolean value as their value and refer to that in the anonymous click function.
1- Your code needs a $ in first of your js to calling it after document.ready: $(function(){...}), or adding () at end of it for calling Immediately ((function(){...})();).
2- You can use off to remove a listener from an element.
other things is ok in your code. please look at result:
$(function(){
var count = 0;
$('button').click(function(){
$('#parent').append('<div id="first'+count+'">text</div>');
count++;
$(this).off("click");//One of benefits of this way is: you can add some conditions for removing this event. > if(...) $(this).off("click");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="details">
<button id="append">button1</button> <button id="append">button2</button> <button id="append">button3</button>
<div id="parent"></div>
</div>
Just unbind it after first click.
$(function(){
var count = 0;
$('button').click(function(){
count = Number($(this).data('click')||0);
if(count>0){
$(this).unbind("click");
}
count = count+1;
$(this).data('click',count);
$('#parent').append('<div id="first'+count+'">text</div>');
});
});

Create a Button in Javascript

Hey i want to create a button like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="click-me" id="myButton" onclick="myFunction()">
</body>
</html>
but i want to create from javascript, and i'm doing something really wrong cause my button does not seem
var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.onclick("myFunction()");
Div.appendChild(MyButton); //i have others things working in this "Div" only this button doesn't appear
You've a misuse of onclick in the posted code, if you check the console you could notice the following message :
"Uncaught TypeError: MyButton.onclick is not a function"
To attach the click event using the onclick it should be :
MyButton.onclick = myFunction;
Else it will be better to attach the event using addEventListener() instead like :
MyButton.addEventListener("click", myFunction);
Hope this helps.
var Div = document.getElementById("my_div");
var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.addEventListener("click", myFunction);
Div.appendChild(MyButton);
function myFunction(){
alert('test');
}
<div id="my_div"></div>
You are doing it wrong because Button does not exists(but MyButton exists).
Instead of :
var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.onclick("myFunction()");
Div.appendChild(MyButton);
Use addEventListener to add click event to the button; And change Div.appendChild(button); to Div.appendChild(MyButton);
function myFunction(){
alert("here");
}
var Div = document.getElementById('div');
var MyButton = document.createElement("button");
MyButton.id = "Mybuttonid";
MyButton.innerHTML ="CLICK ME"
MyButton.className = "MyButtonclass";
MyButton.addEventListener("click", myFunction, false);
Div.appendChild(MyButton); //i have others think working in this "Div" only this button doesn't appear
<div id="div">
</div>
In both HTML and Javascript, you are declaring your onclick function the wrong way. Instead of
<input type="button" value="click-me" id="myButton" onclick"myFunction()">
it should be
<input type="button" value="click-me" id="myButton" onclick="myFunction()">
Which means that this piece of code in Javascript here:
MyButton.onclick("myFunction()");
Should be
MyButton.onclick = function(){ myFunction() };
By doing this and solving the typo that other users mentioned, it should work just fine.

Get element from which onclick function is called

I have a button with a onclick attribute which is pointing to the function test().
<button onclick="test()">Button 1</button>
<button onclick="test()">Button 2</button>
<button onclick="test()">Button 3</button>
Function test():
function test()
{
var button_name = this.html;
console.log("Im button "+ button_name);
}
How can I get informations about the clicked button?
e.g. How can i read the html?
jsfiddle: https://jsfiddle.net/c2sc9j9e/
Pass the this reference to the function, then read textContent property the text content of the node.
HTML
<button onclick="test(this)">Button 1</button>
Script
function test(clickedElement){
var button_name = clickedElement.textContent;
}
Fiddle
Four options:
Pass this into the function.
<button onclick="test(this)">Button 1</button>
and then use that argument in the function.
Hook up the handlers with addEventListener or jQuery's on, and then use this within the handler.
var buttons = document.querySelectorAll("selector-for-the-buttons");
Array.prototype.forEach.call(buttons, function(btn) {
btn.addEventListener("click", handler, false);
});
function handler() {
// Use `this` here
}
jQuery version:
$("selector-for-the-buttons").on("click", function() {
// Use `this` here
});
Hook up a single handler on a container these buttons are in, and use the target property of the event object to determine which was clicked (but note that if you use other elements within button, you'll need to loop up to the button first).
document.querySelector("selector-for-the-container").addEventListener("click", function(e) {
// Use `e.target` here
}, false);
jQuery version that handles the possibility of nested elements within the button for you:
$("selector-for-the-container").on("click", "button", function() {
// Use `this` here (note this is different from the DOM version above)
});
I came across an other extremely simple way to do it in Vanilla JS so I post it here for reference:
function whoami () {
var caller = event.target;
alert("I'm " + caller.textContent);
}
<button onclick="whoami()">Button 1</button>
<button onclick="whoami()">Button 2</button>
<button onclick="whoami()">Button 3</button>
I'm not sure about the browser support for it but it works at least on Safari, Firefox and Blink based browsers.
function test(button)
{
var button_name = button.getAttribute('name');
console.log("Im button "+ button_name);
}
<button onclick="test(this)" name="button1">Button 1</button>
<button onclick="test(this)" name="button2">Button 2</button>
<button onclick="test(this)" name="button3">Button 3</button>
If you want to use Jquery, then you can call the $(this) object in the function.
you must pass "this" to function
<button onclick="test(this)">1</button>
<button onclick="test(this)">2</button>
<button onclick="test(this)">3</button>
<script>
function test(t)
{
console.log(t);
}
</script>
Here is your solution jsfiddle , using jquery.
<button onclick="test(this)">1</button>
<button onclick="test(this)">2</button>
<button onclick="test(this)">3</button>
<script>
function test(button)
{
var button_name = $(button).html();
alert("Im button "+ button_name);
}
</script>
just add id to each button and pass it to your test function
and here is working jsfiddle
<button onclick="test(this.id)" id="button1">1</button>
<button onclick="test(this.id)" id="button2">2</button>
<button onclick="test(this.id)" id="button3">3</button>
<script>
function test(id)
{
var button_name = id;
alert("Im button name is : "+ button_name);
console.log("Im button name is :"+ button_name);
}
</script>
What you want is the event that triggers the click, and you do that by specifying the function call as MyFunction(event). For example:
<ul>
<li onclick="MyFunction(event)">Red</li>
<li onclick="MyFunction(event)">Orange</li>
<li onclick="MyFunction(event)">Yellow</li>
</ul>
and then your Javascript function can be:
function MyFunction(ev) {
// Now you have access to everything in the event
//- including the triggering element
var element = ev.srcElement;
}
By leaving out the (event) parameter in the specification of the onclick function call you don't get it.

How to create multiple jquery functions with one function? [duplicate]

This question already has an answer here:
Consolidate Click Functions
(1 answer)
Closed 6 years ago.
I have the below jquery functions which you can find in this code pen that I would like to simplify.
I'd like to write the below javascript more concisely by writing a function that creates all the below functions, since the only difference are the following strings: name1, name2, name3, etc.
Javascript
$('#name1').on('click', function(){
document.getElementById("name1").innerHTML = "name1";
});
$('#name2').on('click', function(){
document.getElementById("name2").innerHTML = "name2";
});
$('#name3').on('click', function(){
document.getElementById("name3").innerHTML = "name3";
});
$('#name4').on('click', function(){
document.getElementById("name4").innerHTML = "name4";
});
$('#name5').on('click', function(){
document.getElementById("name5").innerHTML = "name5";
});
$('#name6').on('click', function(){
document.getElementById("name6").innerHTML = "name6";
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button type="button" id="name1">NAME</button>
<button type="button" id="name2">NAME</button>
<button type="button" id="name3">NAME</button>
<button type="button" id="name4">NAME</button>
<button type="button" id="name5">NAME</button>
<button type="button" id="name6">NAME</button>
I think this is the simplest solution:
$('button').on('click', function() {
$(this).html($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="name1">NAME</button>
<button type="button" id="name2">NAME</button>
<button type="button" id="name3">NAME</button>
<button type="button" id="name4">NAME</button>
<button type="button" id="name5">NAME</button>
<button type="button" id="name6">NAME</button>
If you want this to work on specific buttons you can use $('#name1,#name2,#name3...').on.
If they all have specific class you can use $('.specific-class').on.
If they all exists inside some specific element you can use $('div#id1 button').on
And so on...
You're targeting every button on the page, so the selector can be simpler:
$('button').on('click', function(){
//
});
And you're setting the "currently clicked element" to the value of its id, which can be more general:
$('button').on('click', function(){
this.innerText = this.id;
});
Note: If this selector is overly simple (you don't want to target every button on the page), you can still use the original list of id values as a single selector. Perhaps something like:
$('button[id^="name"]').on('click', function(){
this.innerText = this.id;
});
Or even:
$('#name1, #name2, #name3, #name4, #name5, #name6').on('click', function(){
this.innerText = this.id;
});
Sometimes it's also appropriate to assign click handlers to a single parent element, especially if there could be many matching elements. Something like this:
$(document).on('click', '#name1, #name2, #name3, #name4, #name5, #name6', function(){
this.innerText = this.id;
});
The difference here is that instead of assigning the handler function to each matching element, only one handler function is assigned to the document and the selector for the target button elements is evaluated on the fly when executing that handler.
Condense your jQuery to this:
$('button[id^="name"]').on('click', function(){
var thisID = $(this).attr("id"),
thisNum = thisID.replace("name", "");
document.getElementById("name" + thisNum).innerHTML = "name" + thisNum;
});
An alternative, pure jQuery solution would be this:
$('button[id^="name"]').on('click', function(){
var t = $(this),
thisID = t.attr("id");
t.html("name" + thisID.replace("name", ""));
});

Remove button and assign on click

I'm working on coding javascript and I'm kind of a noob here. This is my code:
<button onclick="test()">Click Me!</button>
<script>
function test()
{
var btn = document.createElement("BUTTON");
var name = document.createTextNode("Button");
btn.appendChild(name);
document.body.appendChild(btn);
btn.onclick = ex();
}
ex()
{
}
</script>
I want to do two things, and I can't seem to find a solution. I want to:
use the function "ex" to remove the button that says "Click Me!"
assign btn.onclick to the button I just created.
Can anyone help me with this?
EDIT: Although all you guys are trying to help me, I'm not sure you guys are quite understanding the question fully. So, expanding on the first request:
I want to use the function "ex" to delete the button "Click Me!" I want this button to be deleted from the page, and no longer visible.
Second:
I want the btn.click in the function "test" to only be assigned to the button created in the function "test." I've noticed that when you click "Click Me!" it runs the function "ex."
try this one
<script>
function test() {
var btn=document.getElementsByTagName('button')[0];
btn.attributes[0].value="ex()";
btn.innerText="second function";
}
function ex() {
console.log("ex executer");
}
</script>
<button onclick="test()">
click me!
</button>
<button onclick="test()">
Click Me!
</button>
<script>
function test(){
var btn = document.createElement("BUTTON")
var name = document.createTextNode("Button")
btn.appendChild(name);
document.body.appendChild(btn);
btn.onclick = ex;//() remove. btn.onclick is a handler i.e. a function object,
// not the result your ex() returns.
}
function ex(){//add function
this.style.color = 'red'; // makes text of the button red
// **ONLY if button IS clicked**
}
</script>

Categories