How to make 1 button with changing ids do different things? - javascript

I have a button that when pressed besides doing something it changes its own id so when pressed again it does something different as if it is a different button. The problem is that after changing the id for the first time the prev button click function throws an error because the id doesn't exist anymore.
$("#button1").click(function() {
//do something
document.getElementById("#button1").id = "button2";
});
$("#button2").click(function() {
//do something different
document.getElementById("#button2").id = "button1";
});

You can accomplish this by using jQuery on, but like mentioned in comments, this might be a sign you need to change your approach. However, if you must do it this way, here is a solution using jQuery's 'on'.
http://jsfiddle.net/WetNoodles/ab5yn7eL/
$('#outerContainer').on('click', '#button1', function () {
alert('button 1 clicked!');
$(this).attr('id', 'button2');
});
$('#outerContainer').on('click', '#button2', function () {
alert('button 2 clicked!');
$(this).attr('id', 'button1');
});
Some additional notes - If you take smerny's approach, you will still need to use the 'on' function in order to bind events to changing attributes unless you have the onclick attribute set directly on the html tag. Kristian's approach would let you use the click functions like you are currently using.

Related

change attributes on button

I'm attempting to do a project in which I need to change attributes on a button. I have no code for you, but I still need help. Is there any way I can change a button that's already there so that the onclick attribute runs a different function from before? Thanks in advance.
I feel like all the answers so far miss the main point. Since you don't have any code examples, I'm guessing you'll find it hard to extrapolate out what everyone is saying.
So, one button, which when clicked, changes to another method, and when clicked again, changes back. I'm using the onclick attribute for simplicity, but as others have shown, using JavaScript .onclick or addEventListener is a better choice.
function function1(e) {
// Show where we're at
alert("function1 is running");
// Get which button was clicked from the event that is passed in, and set its onclick event
e.currentTarget.setAttribute("onclick", "function2(event)");
}
function function2(e) {
// Show where we're at
alert("function2 is running");
// Get which button was clicked from the event that is passed in, and set its onclick event
e.currentTarget.setAttribute("onclick", "function1(event)");
}
<button onclick="function1(event)">Click Me!</button>
You can of course change what function1 and function2 do, and add more changes (e.g. function 3 and 4), add logic for when to change, and so on.
use .onclick = function_name;
Demo :
document.getElementById('myButton').onclick = fun2;
function fun1() {
alert('I am from Function 1');
}
function fun2() {
alert('I am from Function 2');
}
<button id='myButton' onclick='fun1()'>Click me</button>
Yes, you can. There's only one thing to keep in mind:
An event on which you want the change to happen
Once you have identified that event, just bind it with JQuery's .attr() function to change any attribute.
Read more: http://api.jquery.com/attr/
Javascript Events: https://developer.mozilla.org/en-US/docs/Web/API/Event
Use jQuery like:
$("mybtn").click(function(){
$("#mybtn").attr({
"onclick" : "anotherFunction()",
});
});
Yes, it's possible. Check this fiddle: https://jsfiddle.net/gerardofurtado/ga3k7ssp/1/
I set a variable to 0 and this function for button 1:
bt1.onclick = function(){
i++;
myPar.innerHTML = i;
};
It increases the variable and displays the number.
But, clicking on button 2, it changes button 1 function:
bt1.onclick = function(){
i--;
myPar.innerHTML = i;
};
Now button 1 decreases the variable.
This other fiddle is similar, but using radio buttons, to show that you can set the original function of button 1 back: https://jsfiddle.net/gerardofurtado/8gbLq355/1/

Jquery lag on click function

I've got a table with different columns identified with different classes.
I've also a checkbox binded to every column.
I created a function which is called on the click of any checkbox. In this function I hide/show the column which is linked to this.
It doesn't have any javascript error, and the code is the following:
$(document).ready(function(){
$('ul input').click(function(){
//alert('yooo');
if ($(this).is(':checked')) {
//alert('checked');
$("td."+replaceAll(" ","_",$(this).val())).show();
$("th."+replaceAll(" ","_",$(this).val())).show();
//alert($("td").length);
}
else{
//alert('unselected');
$("td."+replaceAll(" ","_",$(this).val())).hide();
$("th."+replaceAll(" ","_",$(this).val())).hide();
}
});
});
However, after every click, the action has a lag (after many clicks it becomes tooooooo slow, many seconds).
I tried also with .css instead of hide-show, but it doesn't make any change.
I understood that the problem was linked only to checkbox, not on callback or on jquery function. I solved the problem simply by working with radio input, adding a "true" and a "false" radio input for every checkbox that was in the page.
Instead of running the jQuery selector on every click like below:
$("td."+replaceAll(" ","_",$(this).val()))
You could set up some sort of caching like:
var cache = {} //<-- declare this outside your click handler
//add the code below inside your click handler
className = replaceAll(" ","_",$(this).val())
if(!cache[className])
cache[className ] = $("td."+className + ", th."+className); //select all the elements once and store in the cache object
$el = cache[className];
if ($(this).is(':checked'))
$el.show();
else
$el.hide();

Prevent click on another button jquery

How to prevent click another button if first is clicked...
Example
http://jsfiddle.net/C5AVH/3/
$(function(){
$('.vote_like').one('click',function(){
$('.vote_dislike').removeClass('vote_dislike');
alert('Done!')
});
$('.vote_dislike').one('click',function(){
$('.vote_like').removeClass('vote_like');
alert('Done!');
});
});
Like -
Dislike
When you click Like button i want disable click on Dislike button and inversely...
im try with removing class but seems that not working...
$('.vote_like').removeClass('vote_like');
You can remove the click handler
$(function () {
$('.vote_like').one('click.like', function () {
$('.vote_dislike').off('click.like');
console.log('like!')
});
$('.vote_dislike').one('click.like', function () {
$('.vote_like').off('click.like');
console.log('dislike!');
});
});
Demo: Fiddle
Because you've attached the .one handler to each button, it will still be executed at most one time according to the jquery docs. To prevent the click you must remove the handler after one is clicked.
$('.vote_like').one('click',function(){
$('.vote_dislike').off();
alert('Done!')
});
$('.vote_dislike').one('click',function(){
$('.vote_like').off();
alert('Done!');
});
});
Like -
Dislike
But better yet, why not just attach the one handler to both elements and check which was clicked:
$(function(){
$('.vote_like,.vote_dislike').one('click',function(){
if($(this).is('.vote_like')){
//set data for like
}
else{
//set data for dislike
}
//make ajax call
});
Anchors don't have a way to disable them, so you'd either need to remove the anchor or set a boolean in your javascript to track if it's been clicked.
Or, you can convert them into actual button elements, play with the disabled state.
Or you can use jquery to add custom data attributes to the anchor to track if it's "disabled"
Demo
$(function(){
$('.vote_like, .vote_dislike').on('click',function(){
$(this).siblings('.vote_like, .vote_dislike').add($(this)).prop('disabled',true);
if ($(this).hasClass('vote_like')) {
/* Do like things */ alert('like');
}else{
/* Do dislike things */ alert('dislike');
}
});
});
Can use one handler for both buttons and remove click handler within it for both
var btns=$('.vote_like, .vote_dislike').on('click',function(e){
e.preventDefault();
var isLikeBtn=$(this).is('.vote_like');
/* remove click handler for both, remove class from other button */
btns.off('click').not(this).removeClass( isLikeBtn ? 'vote_dislike' : 'vote_like');
});
Since using off on both would be equivalent of using one

Toggling one thing with two different elements

In my previous question I asked about how can I toggle a textarea with a paragraph. I got the answer. Now I want to do the opposite of it. First I was showing the already hidden textarea + 2 buttons by a click of a hyperlink. Now on the click of one of the buttons I want to hide the text + 2 buttons and show the paragraph that was first already shown.
I have tried this JS so far but it's not working:
$(document).ready(function () {
$(".no_link").click(function (e) {
e.preventDefault();
});
$(".edit_offer").on('click', function () {
toggleEditPanel($(this));
});
$("#cancel_edits").on('click', function () {
$(this).closest("button").hide();
$(this).closest("textarea").hide();
$(this).closest("p.content").show();
});
});
function toggleEditPanel(link) {
link.parent().parent().parent().find("textarea").toggle();
link.parent().parent().parent().find("button").toggle();
link.parent().parent().parent().find("p.content").toggle();
}
But its not working. How can I solve this error?
If I am trying to call the function toggleEditPanel() again. Its not working then aswell.
You can find the markup in the fiddle. Here's the fiddle.
UPDATE 1:
Just came up with a solution. I can use the $.siblings() function to toggle the elements beside the button. Still, is there any better solution?
Here's the code that I came up with:
$("#cancel_edits").on('click', function () {
$(this).hide();
$(this).siblings("button").hide();
$(this).siblings("textarea").hide();
$(this).siblings("p.content").show();
});
UPDATE 2:
The problem in the above code is that if there are more than one panels like this then the code is not working. How can I solve that issue aswell?
You are using Id for selector $("#cancel_edits") .
Id selectors returns only first element , so if there are multiple pannel it will work only for first.
Instead give some class name and use it for selector. Further you can use chaining and caching in your code for better performance.
$(".cancel_edits").on('click', function () {
var elm=$(this);
elm.add(elm.siblings("button,textarea")).hide();
elm.siblings("p.content").show();
});
I would recommend referencing your elements by ID:
$("#cancel_edits").on('click', function () {
$('#save_edits').hide();
$('#edited_content').hide();
$(this).hide();
$("p.content").show();
});
JSFiddle
The great thing about using IDs is that you are guaranteed they are unique - no need to use closest() to find the element you want. If, however, you're using classes instead, closest() might be necessary or helpful.

Hiding button using jQuery

Can someone please tell me how I can hide this button after pressing it using jQuery?
<input type="button" name="Comanda" value="Comanda" id="Comanda" data-clicked="unclicked" />
Or this one:
<input type=submit name="Vizualizeaza" value="Vizualizeaza">
Try this:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
}
);
For doing everything else you can use something like this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$(".ClassNameOfShouldBeHiddenElements").hide();
}
);
For hidding any other elements based on their IDs, use this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$("#FirstElement").hide();
$("#SecondElement").hide();
$("#ThirdElement").hide();
}
);
You can use the .hide() function bound to a click handler:
$('#Comanda').click(function() {
$(this).hide();
});
jQuery offers the .hide() method for this purpose. Simply select the element of your choice and call this method afterward. For example:
$('#comanda').hide();
One can also determine how fast the transition runs by providing a duration parameter in miliseconds or string (possible values being 'fast', and 'slow'):
$('#comanda').hide('fast');
In case you want to do something just after the element hid, you must provide a callback as a parameter too:
$('#comanda').hide('fast', function() {
alert('It is hidden now!');
});
It depends on the jQuery selector that you use. Since id should be unique within the DOM, the first one would be simple:
$('#Comanda').hide();
The second one might require something more, depending on the other elements and how to uniquely identify it. If the name of that particular input is unique, then this would work:
$('input[name="Vizualizeaza"]').hide();

Categories

Resources