How to capture clicked button in js functions? - javascript

I have to buttons like this:
<input type='submit' id='submit' class='processAnimation'>
<input type='reset' id='reset' class='processAnimation'>
Now I have two js function. First function is called when ajax request is started and seconf function is called when ajax request is completed.
this.showLoading = function () {
backupsource = $('.processAnimation').attr('class');
$('.processAnimation').removeAttr('class').addClass('disabled-btn processAnimation');
$('.processAnimation').attr( 'backupsource', backupsource );
}
this.hideLoading = function () {
backupsource = $('.processAnimation').attr('backupsource');
if( backupsource != undefined ) {
$('.processAnimation').removeAttr('class').addClass( backupsource );
$('.processAnimation').removeAttr('backupsource');
}
}
EDIT: Above two functions are working and moving flower replaced clicked button. When request is complete then button is back. Problem is that when I click one button it replace all buttons(class=procesAnimation) with moving flower.
Thanks

Since you haven't posted your click event binding I am going to take a quick guess and say that your selector is not set right or conflicts with another element. try something like this:
$('input').click(function(){
switch( $(this).attr('id') ){
case 'submit' :
ShowLoading();
break;
case 'reset' :
HideLoading();
break;
}
});
and change the syntax of how you initialize the two functions to the following:
function ShowLoading(){
//do your show loading procedure here
};
function HideLoading(){
//do your hide loading procedure here
};

This is using the code u have currently
$('.processAnimation').click(function (){
if($(this).attr('type')=='submit'){
//submit has been clicked
}else{
//reset has been clicked
}
});
but it looks like you should really be using ID's rather than class's

if you have jQuery it is simple
$('#submit').click(showLoading)
$('#reset').click(hideLoading)
Just two different binding of events.
or did I miss something? :)

Related

Getting result of Confirm dialog on Cancel Button in jQuery event hander

On one side I have a form with submit/cancel buttons and the cancel has an onclick event (to do some cleanup) that is wrapped in a standard confirm dialog. All standard stuff.
But then I have a second script (and it MUST be a second script) that may only sometimes be loaded, that needs to add more tasks if the form is cancelled. So - I can listen for the onclick...
$( "#cancelBtn" ).on( "click", function(a) {
// do more stuff...
});
but I only want to 'do more stuff' if the confirm around the onclick is OK. I am probably missing something stupidly simple but I have been at this all day and am about to give up! Can anyone point me in the right direction?
Update: I can not change the form onclick code - it has to stay separate and as it now is.... so the confirm has to stay where it is.
Do it like this:
$( "#cancelBtn" ).on( "click", function(a) {
if (confirm('Are you sure you want to cancel?')) { // Standard confirmation message.
// Pressed OK.
// do more stuff...
} else {
// Pressed Cancel.
}
});
Hope this helps.
EDIT: Since you can't change the script performing form duty, a solution would be to overwrite the confirm()-function:
var _confirm = window.confirm;
window.confirm = function() {
//catch result
var confirmed = _confirm.apply(window,arguments);
if (confirmed) {
//confirm ok, do some tasks
} else {
//confirm cancelled, do some cleanup
}
//pass result on to the caller
return confirmed;
};
http://jsfiddle.net/sofcuoab/
put the tasks in the second script in
function doMoreStuff(){
//more tasks
}
and call it in your confirm-clause like this
if (typeof doMoreStuff === "function") {
doMoreStuff();
}
or like this
try {
doMoreStuff();
}
catch(err) {
//no second script loaded
}

Bypass onclick event and after excuting some code resume onclick

I have the below html button which have onclick event
<button onclick="alert('button');" type="button">Button</button>
and the following js:
$('button').on('click', function(){
alert('jquery');
});
After executing some js code by jQuery/Javascript, i want to continue with the button onclick handler e.g: jquery alert first and than button alert.
i tried so many things like "remove attr and append it after executing my code and trigger click (it stuck in loop, we know why :) )" and "off" click. but no luck.
is it possible via jQuery/javascript?
any suggestion much appreciated
Thanks
A little bit tricky. http://jsfiddle.net/tarabyte/t4eAL/
$(function() {
var button = $('#button'),
onclick = button.attr('onclick'); //get onclick value;
onclick = new Function(onclick); //manually convert it to a function (unsafe)
button.attr('onclick', null); //clear onclick
button.click(function() { //bind your own handler
alert('jquery');
onclick.call(this); //call original function
})
});
Though there is a better way to pass params. You can use data attributes.
<button data-param="<%= paramValue %>"...
You can do it this way:
http://jsfiddle.net/8a2FE/
<button type="button" data-jspval="anything">Button</button>
$('button').on('click', function () {
var $this = $(this), //store this so we only need to get it once
dataVal = $this.data('jspval'); //get the value from the data attribute
//this bit will fire from the second click and each additional click
if ($this.hasClass('fired')) {
alert('jquery'+ dataVal);
}
//this will fire on the first click only
else {
alert('button');
$this.addClass('fired'); //this is what will add the class to stop this bit running again
}
});
Create a separate javascript function that contains what you want to do when the button is clicked (i.e. removing the onclick attribute and adding replacement code in its own function).
Then call that function at the end of
$('button').on('click', function(){
alert('jquery');
});
So you'll be left with something like this
function buttonFunction()
{
//Do stuff here
}
$('button').on('click', function()
{
alert('jquery');
buttonFunction();
});
<button type="button">Button</button>

jQuery button takes value from input and do an action - how does it works?

I've got a small piece of code here
<label for="pass">Password</label>
<input type="text" id="pass" value="QWERTY">
<button for="pass">Submit!</button>
and jquery action
$("button").click(function(){
var value=$("input[id=pass]").attr("value");
if (value==="QWERTY"){
alert("Good!");
};
and it doesnt work. Do you know how to fix it?
Try this.
$("button").click(function(){
var value=$("input#pass").val();
if ( value === "QWERTY"){
alert("Good!");
}
});
jQuery has it's own built in function for fetching values from input fields.
You should prevent the default action from triggering when the button is clicked (otherwise the form will be submitted, and the JS will not execute). You should also use val() when accessing an input's value.
You should also wrap your code inside the DOMReady handler, to ensure that the DOM is accessible when your script is run.
Here's an updated version of your code:
$(function() {
$("button").click(function(e) {
e.preventDefault();
var the_value = $("#pass").val();
if(value == "QWERTY")
{
alert("Good!");
}
};
});
Try this : It's more optimized...
$("button").click(function(e){
e.preventDefault();
var value=$("#pass")[0].value;
if (value==="QWERTY"){
alert("Good!");
};
You can also remove the "for" attribute on the button, it's non correct ;)
Your code should work if you don't forget the }); at last and have put the code into dom ready callback function. The demo.
And you could write it like below:
$("button").click(function(){
if ($('#pass').val()==="QWERTY"){
alert("Good!");
};
});
I think you just have a syntax error. You need to make sure you close your function curly brace and your click close paren.
$("document").ready(function () {
$("button").click(function () {
var value = $("input[id=pass]").attr("value");
if (value === "QWERTY") {
alert("Good!");
}
});
});
Example:
http://jsfiddle.net/pandaPowder/5VjeD/3/

Why alert popup a few times after a click event?

On a page there are couple of Add buttons (li .plus).
When you click on a Add button and assume json.success is false, it will then popup via $.colorbox plugin
The popup pull the data from href:"/Handle/Postcode/?val" + Val
There is a submit button (#submitButton) from the popup, when I click on the submit button, it keep popup alert box a few times, I dont understand why that happen? how to fix it?
$("li .plus").click(function(event) {
event.preventDefault();
var Val;
Val = $('#id').val()
$.getJSON(Address +"/Handle/Add", {
Val:Val
}, function(json) {
if (json.success == "false" && json.error == "NoArea") {
$.colorbox({
width:"450px",
transition:"none",
opacity:"0.4",
href:"/Handle/Postcode/?val" + Val
});
$("#submitButton").live('click', function() {
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
//Why does it popup a few times?
});
}
if (json.success == "true") {
Backet();
}
});
});
Thats an easy one, because you are using the .live() function to bind your click handler. If that code gets executed more than one time your binding happens more than one time.
You can either try to track the state of the binding and only apply it if it doesn't exist, or you can call your click function in the html with the onClick attr.
Edit: Just to clarify I meant something along the lines of -
HTML
<button id='submitButton' onclick="displayAreaCode();">Submit</button>
JS
function displayAreaCode(){
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
}

Change onclick action with a Javascript function

I have a button:
<button id="a" onclick="Foo()">Button A</button>
When I click this button the first time, I want it to execute Foo (which it does correctly):
function Foo() {
document.getElementById("a").onclick = Bar();
}
What I want to happen when I click the button the first time is to change the onclick function from Foo() to Bar(). Thus far, I've only been able to achieve an infinite loop or no change at all. Bar() would look something like this:
function Bar() {
document.getElementById("a").onclick = Foo();
}
Thus, clicking this button is just alternating which function gets called. How can I get this to work? Alternatively, what's a better way to show/hide the full text of a post? It originally starts shorted, and I provide a button to "see the full text." But when I click that button I want users to be able to click the button again to have the long version of the text go away.
Here's the full code, if it helps:
function ShowError(id) {
document.getElementById(id).className = document.getElementById(id).className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Text").className = document.getElementById(id+"Text").className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Button").innerHTML = "HIDE FULL ERROR";
document.getElementById(id+"Button").onclick = HideError(id);
}
function HideError(id) {
document.getElementById(id).className += " height_limited";
document.getElementById(id+"Text").className += " height_limited";
document.getElementById(id+"Button").innerHTML = "SHOW FULL ERROR";
document.getElementById(id+"Button").onclick = "ShowError(id)";
}
Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.
document.getElementById("a").onclick = Bar;
Looking at your other code you probably want to do something like this:
document.getElementById(id+"Button").onclick = function() { HideError(id); }
var Foo = function(){
document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}
var Boo = function(){
alert("test");
}
Do not invoke the method when assigning the new onclick handler.
Simply remove the parenthesis:
document.getElementById("a").onclick = Foo;
UPDATE (due to new information):
document.getElementById("a").onclick = function () { Foo(param); };
Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).
document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );
I recommend this approach:
Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:
HTML:
<button id="a" onclick="toggleError(this)">Button A</button>
JavaScript:
function toggleError(button) {
if ( button.className === 'visible' ) {
// HIDE ERROR
button.className = '';
} else {
// SHOW ERROR
button.className = 'visible';
}
}
Live demo: http://jsfiddle.net/simevidas/hPQP9/
You could try changing the button attribute like this:
element.setAttribute( "onClick", "javascript: Boo();" );
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.
So, at first button1 would be display:block and button2 would be display:none. Then when you click button1 it would switch button2 to be display:block and button1 to be display:none.
For anyone, like me, trying to set a query string on the action and wondering why it's not working-
You cannot set a query string for a GET form submission, but I have found you can for a POST.
For a GET submission you must set the values in hidden inputs e.g.
an action of: "/handleformsubmission?foo=bar"
would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />
This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:
var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);
See this question for more info
submitting a GET form with query string params and hidden params disappear

Categories

Resources