How to know which button is clicked - javascript

In my page I have many edit buttons each name starts with "edit" and then some id. I want to know any of my edit buttons is clicked or not.
In details, I have form. In form I have many edit buttons which name starts with "edit" , delete buttons which name starts with "delete" and 1 add button. All are submit buttons. form onsubmit I call JavaScript function in which I want if the button is edit confirm("some text") else submit form.
How can I do that in JavaScript?
I think give all these buttons same id and then getElementById but then how con I change?

This is simple using jQuery:
$(':button').click(function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
});
Try it out:
http://jsfiddle.net/7YEay/
UPDATE based on feedback in comments
This is untested/pseudo code:
$(':submit').click(function(event) {
var buttonName = $(this).attr('name');
if (buttonName.indexOf('edit') >= 0) {
//confirm("some text") logic...
}
event.preventDefault();
});
This documentation may be helpful too: http://api.jquery.com/submit/

function MyOnSubmit(e){
e = e || window.event;
// srcElement for IE, target for w3c
var target = e.target || e.srcElement;
if (target.id.indexOf("edit") > -1){
// an edit button fired the submit event
}
}
although i advice you research further to find a better way to handle edit and delete buttons (like making them links with href=editpage.jsp?id=23)

I'm pretty sure you just answered this yourself...
Each starts with "edit", and ends with a unique ID?
So... $(button).attr("id") would give you that. Store it in a variable? Not sure what you're trying to do..

bind click event on all button:
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
if (button.addEventListener) {
button.addEventListener('click', handler, false);
}
else {
button.attachEvent('onclick', handler);
}
}
in your event handler, get the Event object, and then get the target:
function handler(e) {
e = e || window.event;
// srcElement for IE, target for w3c
var target = e.target || e.srcElement;
var id = target.name.substring(4);
/* your code rely on id */
}

I think you might not have phrased your question correctly. If you are using jquery, locating the button is as easy as $('#id'), and if you want to store any information on that button, you can either add an attribute or use jquery.data function.
$('#id').attr("pressed", "true");
Or
$('#id').data('pressed', 'true');

Related

clear click queue from jQuery

I have a click event that triggers other click events that adds an element to the DOM.
EDIT: But when I click it a second time two elements get added and third time two elements get added. When I check the jQuery queue it confirms that I have added an event to the queue that fires every time.
What I try to accomplish is to add a click event to two dropdownlists by clicking another element.
$(".step-1 a").on("click", function(e){
e.preventDefault();
var userValue = $(this).attr('id');
$(".template-image").removeClass("selected");
$(this).children(":first").addClass("selected");
$("#page_template option ").each(function(){
var t = $(this);
var cValue = t.attr("value");
if(t.attr("selected") === "selected"){
t.removeAttr("selected");
}
if(t.attr("value") === userValue ){
t.prop("selected", "selected");
$('#page_template').trigger('change');
var template = t.attr("value");
switch (template)
{
case "default":
$(".step-2").slideDown("fast");
$(".step-2").addClass("show");
break;
default:
$(".step-2").removeClass("show");
$(".step-2").slideUp("fast");
break;
}
}
});
});
$('.step-2 img').on("click", function(e){
e.preventDefault();
var userinput = $(this).attr('id');
$('.flexible-footer .acf-fc-add').each(function(){
var text = $(this).text();
if(text === "Add columns"){
$(this).trigger('click');
$('.flexible-footer .acf-fc-popup ul li a').each(function(){
var column = $(this).attr('data-layout');
if (column === userinput) {
$(this).trigger('click');
$(this).finish();
console.log($(this).queue());
}
});
}
});
It sounds like you're assigning click events multiple times on the same elements. A simple solution to this problem is to use the jQuery function off() to remove the old click-event before adding a new one. Or make sure you're only adding the click event to new element that doesn't already have them. You can do it like this:
$('img.or-whatever').off('click').on('click', function(ev){...});
Or maybe use namespaces for increased readability:
$('img.or-whatever').off('click.custom-namespace').on('click.custom-namespace', function(ev){...});
It might not be the correct answer to your question, but it might be a solution.
Edit:
If you just want to clear the event queue, you could try clearQueue().

X-Editable: stop propagation on "click to edit"

I have an editable element inside a div which itself is clickable. Whenever I click the x-editable anchor element, the click bubbles up the DOM and triggers a click on the parent div. How can I prevent that? I know it's possible to stop this with jQuery's stopPropagation() but where would I call this method?
Here's the JSFiddle with the problem: http://jsfiddle.net/4RZvV/ . To replicate click on the editable values and you'll see that the containing div will catch a click event. This also happens when I click anywhere on the x-editable popup and I'd like to prevent that as well.
EDIT after lightswitch05 answer
I have multiple dynamic DIVs which should be selectable so I couldn't use a global variable. I added an attribute to the .editable-click anchors which get's changed instead.
editable-active is used to know if the popup is open or not
editable-activateable is used instead to know if that .editable-click anchor should be treated like it is
$(document).on('shown', "a.editable-click[editable-activateable]", function(e, reason) {
return $(this).attr("editable-active", true);
});
$(document).on('hidden', "a.editable-click[editable-activateable]", function(e, reason) {
return $(this).removeAttr("editable-active");
});
The check is pretty much like you've described it
$(document).on("click", ".version", function() {
$this = $(this)
// Check that the xeditable popup is not open
if($this.find("a[editable-active]").length === 0) { // means that editable popup is not open so we can do the stuff
// ... do stuff ...
}
})
For the click on the links, simply catch the click event and stop it:
$("a.editable-click").click(function(e){
e.stopPropagation();
});
The clicks within X-editable are a bit trickier. One way is to save a flag on weather the X-editable window is open or not, and only take action if X-editable is closed
var editableActive = false;
$("a.editable-click").on('shown', function(e, reason) {
editableActive = true;
});
$("a.editable-click").on('hidden', function(e, reason) {
editableActive = false;
});
$("div.version").click(function(e) {
var $this;
$this = $(this);
if(editableActive === false){
if ($this.hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
}
});
Fixed Fiddle
It's not pretty, but we solved this problem with something like:
$('.some-class').click(function(event) {
if(event.target.tagName === "A" || event.target.tagName === "INPUT" || event.target.tagName === "BUTTON"){
return;
}
We're still looking for a solution that doesn't require a specific list of tagNames that are okay to click on.

How to display a confirmation dialog when clicking an <a> link?

I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.
Link
If the user clicks “Yes”, the link should load, if “No” nothing will happen.
I know how to do that in forms, using onclick running a function that returns true or false. But how do I do this with an <a> link?
Inline event handler
In the most simple way, you can use the confirm() function in an inline onclick handler.
Link
Advanced event handling
But normally you would like to separate your HTML and Javascript, so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.
Link
...
<script type="text/javascript">
var elems = document.getElementsByClassName('confirmation');
var confirmIt = function (e) {
if (!confirm('Are you sure?')) e.preventDefault();
};
for (var i = 0, l = elems.length; i < l; i++) {
elems[i].addEventListener('click', confirmIt, false);
}
</script>
This example will only work in modern browsers (for older IEs you can use attachEvent(), returnValue and provide an implementation for getElementsByClassName() or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.
jQuery
I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery:
Link
...
<!-- Include jQuery - see http://jquery.com -->
<script type="text/javascript">
$('.confirmation').on('click', function () {
return confirm('Are you sure?');
});
</script>
You can also try this:
<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
Link Text
</a>
I'd suggest avoiding in-line JavaScript:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
var check = confirm("Are you sure you want to leave?");
if (check == true) {
return true;
}
else {
return false;
}
};
}​
JS Fiddle demo.
The above updated to reduce space, though maintaining clarity/function:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
return confirm("Are you sure you want to leave?");
};
}
JS Fiddle demo.
A somewhat belated update, to use addEventListener() (as suggested, by bažmegakapa, in the comments below):
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].addEventListener('click', reallySure);
}
JS Fiddle demo.
The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
function actionToFunction (event) {
switch (event.target.tagName.toLowerCase()) {
case 'a' :
reallySure(event);
break;
default:
break;
}
}
document.body.addEventListener('click', actionToFunction);
JS Fiddle demo.
Because the event-handling is attached to the body element, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction) to determine what to do with that click. If the clicked element is a link, and therefore has a tagName of a, the click-handling is passed to the reallySure() function.
References:
addEventListener().
Conditional ('ternary') operator.
confirm().
getElementsByTagName().
onclick.
if () {}.
Confirm OK, then goto URL (uses onclick())
jAplus
You can do it, without writing JavaScript code
<head>
<script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
Link
...
</body>
Demo page
This method is slightly different than either of the above answers if you attach your event handler using addEventListener (or attachEvent).
function myClickHandler(evt) {
var allowLink = confirm('Continue with link?');
if (!allowLink) {
evt.returnValue = false; //for older Internet Explorer
if (evt.preventDefault) {
evt.preventDefault();
}
return false;
}
}
You can attach this handler with either:
document.getElementById('mylinkid').addEventListener('click', myClickHandler, false);
Or for older versions of internet explorer:
document.getElementById('mylinkid').attachEvent('onclick', myClickHandler);
Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:
document.body.onclick = function( e ) {
// Cross-browser handling
var evt = e || window.event,
target = evt.target || evt.srcElement;
// If the element clicked is an anchor
if ( target.nodeName === 'A' ) {
// Add the confirm box
return confirm( 'Are you sure?' );
}
};
This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.
USING PHP, HTML AND JAVASCRIPT for prompting
Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.
<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>
the reason i used php code in the middle is because i cant use it from the beginning..
the code below doesnt work for me:-
echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";
and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.
Most browsers don't display the custom message passed to confirm().
With this method, you can show a popup with a custom message if your user changed the value of any <input> field.
You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:
$(document).ready(function() {
let unsaved = false;
// detect changes in all input fields and set the 'unsaved' flag
$(":input").change(() => unsaved = true);
// trigger popup on click
$('.dangerous-link').click(function() {
if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {
return; // user didn't confirm
}
// either there are no unsaved changes or the user confirmed
window.location.href = $(this).data('destination');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Nuclear code here" />
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">
Launch nuke!
</a>
Try changing the input value in the example to get a preview of how it works.

Click HTML except one element, without using jQuery

I show us the code:
(function (){
var element = document.getElementById('bar'), hideElement = document.getElementById('foo'),
var html = document.getElementsByTagName('html')[0];
tool.onclick = function() {
hideElement.style.display = 'block';
html.onclick = function() {
hideElement.style.display = 'none';
}
}
})();
This piece of code work's fine, but, after clicking html, I can not reopen the hidden element.
I want to click the html element and give display:none to hideElement, then to click the element id="bar", give to the hidden element display:block, but instead of click the element foo, click the html element. What I can do?
Oh, i need help WITHOUT JQUERY, thanks :)
EDIT: something like that : click on body except some other tag not working , but without JQuery,
I'm not sure it's going to answer your question, but here it is: how to handle an event on the body except one element:
document.documentElement.onclick = function(e) {
var evt = e || window.event, // IE...
target = evt.target || evt.srcElement // IE again...
// There, "target" is the element clicked. See where I'm going?
if (target.id !== "foo") {
// Do w/e you want if the page was clicked, except for "foo"
}
}
This is the concept of "event bubbling". You can listen to one element and all its children at once, and get the target as specified in the code up there.
First, you don't appear to be defining tool anywhere that I can see.
Second, you forgot .style in hideElement.display (should be hideElement.style.display).
Third, document.getElementsByTagName('html')[0] is redundant. Just use document.documentElement instead.
Change
html.onclick = function() {
hideElement.display = 'none';
}
to
html.onclick = function() {
hideElement.style.display = 'none';
}

how to fix this IE6 input bug

var check = function(){
return false;
}
var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";
submit.onclick = check;
_submitSpan.appendChild(submit);
i created a form and append a input button, but i found it can't work in IE6, when click the button, the form auto submitted. can anybody help me.thank you.
Instead of explicitly setting the onclick attribute, try binding dynamically to the nodes' onclick event instead. Or perhaps you should be looking at the onsubmit event of the form.
function bindEvent(target, event, handler) {
if (typeof target.addEventListener != 'undefined') {
target.addEventListener(event, handler, false);
} else if (typeof target.attachEvent != 'undefined') {
target.attachEvent('on' + event, handler);
}
}
function check(e) {
// Cancel W3 DOM events
if (typeof e.preventDefault != 'undefined') {
e.preventDefault();
}
// Cancel for old IE event model
e.returnValue = false;
return false;
}
var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";
_submitSpan.appendChild(submit);
// Bind click event to submit button...
bindEvent(submit, 'click', check);
// ...or perhaps you want to bind submit event to form
bindEvent(submit.form, 'submit', check);
It might be an idea to hook into a 3rd party lib to handle event inconsistencies et al, YUI does a fine job, as does jquery.
For IE you might have to use the addAttribute method instead of .onclick()
submit.addAttribute('onclick', check);
From W3C HTML 4.01 Specs:
image
Creates a graphical submit button. The value of the src attribute specifies the URI of the >image that will decorate the button. For accessibility reasons, authors should provide >alternate text for the image via the alt attribute.
Do not use an <input type="image"> like a checkbox. The best way to make an image-checkbox is something like:
<label for="input">
<input id="input" style="display:none;" type="checkbox">
<img src="img.gif" alt="Check">
</label>
The label will treat the image as a checkbox, and automatically check the hidden checkbox if the image is clicked.

Categories

Resources