Switch to different button on click - javascript

I want code to switch the buttons. If I pressed button1 first time, it must show button2 and vice versa.
<input type="submit" value="asc" name="button1" id="but1">
<input type="submit" value="desc" name="button2" id="but3">

One solution without the need for JQuery would be this one:
<input type="button" value="asc" name="button1" id="but1" onClick="document.getElementById('but3').style.display='';this.style.display='none';">
<input type="button" value="desc" name="button2" id="but3" style="display:none;" onClick="document.getElementById('but1').style.display='';this.style.display='none';">
You can also do it this way if you want to use the visibility:
<input type="button" value="asc" name="button1" id="but1" onClick="document.getElementById('but3').style.visibility='visible';this.style.visibility='hidden';">
<input type="button" value="desc" name="button2" id="but3" style="visibility:hidden;" onClick="document.getElementById('but1').style.visibility='visible';this.style.visibility='hidden';">
Using visibility preserves the buttons position. I changed the type from submit to button just out of demonstration reasons.
You can look at both JSFIDDLE demos of these solutions here and here.

Not sure what you're trying to achieve, but you can use:
$('input[type="submit"]').click(function() {
$(this).hide().siblings('input[type="submit"]').show();
});
Fiddle Demo

Simply Use .toggle() in jQuery
$('input[type="submit"]').click(function() {
$('input[type="submit"]').toggle();
});
Fiddle

I'm betting your .toggle-radio-switch elements are siblings. Remove .parent() from your code. It isn't needed since .radio-switch-slider is contained directly in .toggle-radio-switch
$(this).find('.radio-switch-slider')

document.getElementById('but1').addEventListener('click', function() {
document.getElementById('but1').style.visibility = 'hidden';
document.getElementById('but3').style.visibility = 'visible'; }, false);
document.getElementById('but3').addEventListener('click', function() {
document.getElementById('but3').style.visibility = 'hidden';
document.getElementById('but1').style.visibility = 'visible'; }, false);
If you want to hide button and its placeholder completely, use style.display = 'none' and style.display = 'block'. If you put both buttons in div container with default static positioning, then both buttons will appear at the same position in container.

By default when page will load put following code so that your second button will be hide.
$(document).ready(function(e){
$('#but3').hide();
});
After that Put code that were
$('input[type="submit"]').click(function() {
$(this).hide().siblings('input[type="submit"]').show();
});

Try using the following functions:
$(element)click(callback) will handle the click of the element
$(element).show() will show the element
$(element).hide() will hide the element
so a semple code is:
//first hidden the second button
$('#but3').css('display','none')
// handle click of first button
$('#but1').click(function(){
$(this).hide()
$('#but3').show()
});
// handle click of second button
$('#but3').click(function(){
$(this).hide()
$('#but1').show()
});
Here is an example: http://jsfiddle.net/L7zux/1/

You can try the code below:
$('input[type="submit"]').click(function(){
var valueOfButton = $(this).val();
if(valueOfButton == 'asc')
{
$('input[value="asc"]').show();
$('input[value="desc"]').hide();
}
else
{
$('input[value="desc"]').show();
$('input[value="asc"]').hide();
}
});

Related

How to change a global variable inside jQuery selectors?

I'm developing a website, which is using jQuery.Inside this code I need to change the value of a variable inside a Jquery selector and get the changed value after it.Is it possible to do that?How can I achieve this?If possible, could show me a snippet/example code?
I've tried declaring the variable global, but without success too.
var index;
$(document).ready( function(){
$("#myButton1").click(function(){ //selector number 1
index = 1;
});
$("#myButton2").click(function(){//selector number 2
index = 2;
});
//after, i need the value of the index for another selector
//look this next selector is fired at the same time as the previous one!
$("button[id^=myButton"+index+"]").click( function(){ //selector number 3
...
}
}
How can I make the selector number 1 or 2 fire after the selector number 3?Is it possible?
Javascript executes code asynchronously. In other words, whole code executes at the "same time." So first, it will execute var index;. Since the jQuery .click is waiting for you to click the button, it will skip both of the .click functions and move on to the alert. Since index is undefined, it will say index=undefined. To fix that, move the alert's inside the .click function so that the alert will execute after you click the button.
var index;
$("#button1").click(function() {
index = 1;
alert("index = " + index);
});
$("#button2").click(function() {
index = 2;
alert("index = " + index);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1"></button>
<button id="button2"></button>
Or you could do it this way:
var index = 0;
$("#button1").click(function() {
index = 1;
});
$("#button2").click(function() {
index = 2;
});
setTimeout(function() {
alert("index = " + index);
}, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1"></button>
<button id="button2"></button>
The above method basically executes the alert after 5 seconds, so you can change the value of index as many times as you want in those 5 seconds. The default value is 0, but if you click the first button within those 5 seconds, the value of index changes to 1. Same for the second button.
The things that happen when you click one of the buttons are those you define inside the click-handler function (see here):
$("#button1").click(function(){
window.index = 1; // only this line!!!
});
Your call to alert() resides inside the ready-funtion and is therefore only called when the page is loaded. You need to put the alert inside the click handlers to call it "on click". Doing so, all three versions should work. Should look like this:
$("#button1").click(function(){
index = 1;
alert(index);
});
After your edit:
Same thing here: the selector string after you comment is created at the time of the page load, before any button is clicked. and never again after that.
At that moment, it evaluates to "button[id^=myButtonundefined]" because index has no defined value yet. T## is function therfore will be executed whenever you click a button whose ID starts with myButtonundefined - probably never.
Everything you want to achieve, for which you need the value of index you need to execute inside the click-handler function. e.g.:
$(document).ready( function(){
$("#button1").click(function(){
$("button[id^=myButton1]").click( function(){
...
});
});
$("#button2").click(function(){
$("button[id^=myButton2]").click( function(){
...
});
});
}
or you could try the following approach, which installs a click-handler on all myButton...'s and therein checks if the corresponding button... has been clicked before:
var index;
$(document).ready( function(){
$("#button1").click(function(){
index = 1;
});
$("#button2").click(function(){
index = 2;
});
//after, i need the value of the index for another selector:
$("button[id^=myButton]").click( function(){
if (this.id == 'myButton'+index) {
...
}
}
}
How to change a global variable inside jQuery selectors?
Don't use a global variable in this instance. You have a chance of a variable collision with any other code (jQuery or any other script you use). You can simply place index inside your document ready and use it in your example code and it will work without any chance of collision.
$(document).ready( function(){
var index;
$("#button1").click(function(){
index = 1;
});
$("#button2").click(function(){
index = 2;
});
//after, i need the value of the index for another selector:
$("button[id^=myButton"+index+"]").click( function(){
});
$('.js-getcurrentvalue').on('click', function() {
$('#currentvalue').val(index);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-getcurrentvalue" value="Get Current Value of Index"/><input type="text" id="currentvalue" /><br/>
<input type="button" id="button1" value="button1" /><br/>
<input type="button" id="button2" value="button1" /><br/>
But at the same time, the selector $("button[id^=myButton"+index+"]").click( function(){ }); fires.So, both are executed at the same time.I need that the second selector execute always after the first selector.Do u know how can I accomplish this?
This is not the original question you asked. Please read what an XY Problem is so your future questions can be answer correctly.
Highly recommended reading: Decouple your HTML, CSS and Javascript.
First we need to understand that each of these statements that attach an event handler onto an element all run before the event handler can be executed. So in my previous example the following events are registered:
$("#button1").click()
$("#button2").click()
$("button[id^=myButton]").click();
$('.js-getcurrentvalue').on('click')
You'll notice that I've done what any compiler would do and reduce the variable into it's actual value. At the time the event handler is attached, index has no value. Since this isn't what you want, you could write it like:
$("button").click(function() {
var $this = $(this);
var id = $this.prop(id);
if ($this.is("[id^=myButton"+index+"]") {
// do something as index changes
}
});
But it's really ugly and introduces an abstraction of a value to used to compare. It's also very tightly coupled, that is we have to place an event on any object we want to change index and we have to write more code for each button. Yikes. Instead we can use classes and the data-attribute with data() to simplify and make this more robust.
$(document).ready( function(){
var selector;
$(".js-enable-button").on('click', function(){
selector = $(this).data('selector');
});
$('.js-enable-me').on('click', function() {
var $this = $(this);
if ($this.is(selector)) {
alert($this.val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button1" />
<input type="button" class="js-enable-me" id="button1" value="Am I working?" /><br/>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button2" />
<input type="button" class="js-enable-me" id="button2" value="Or am I working?" /><br/>
Now the code is not limited to an Id. It's also not limited to a single selector. You could go crazy and just by adding only html the following continues to work for all elements. Notice I've added no additional code.
$(document).ready( function(){
var selector;
$(".js-enable-button").on('click', function(){
selector = $(this).data('selector');
});
$('.js-enable-me').on('click', function() {
var $this = $(this);
if ($this.is(selector)) {
alert($this.val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button1" />
<input type="button" class="js-enable-me" id="button1" value="Am I working?" /><br/>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button2" />
<input type="button" class="js-enable-me" id="button2" value="Or am I working?" /><br/>
<br/>
<input type="button" class="js-enable-button" value="I enable the three below me using id" data-selector="#id1,#id2,#id3" /></br>
<input type="button" class="js-enable-me" id="id1" value="id1" /><br/>
<input type="button" class="js-enable-me" id="id2" value="id2" /><br/>
<input type="button" class="js-enable-me" id="id3" value="id3" /><br/>
<br/>
<input type="button" class="js-enable-button" value="I enable the three below me using a class" data-selector=".enable" /></br>
<input type="button" class="js-enable-me enable" value="I'm .enable 1" /><br/>
<input type="button" class="js-enable-me enable" value="I'm .enable 2" /><br/>
<input type="button" class="js-enable-me enable" value="I'm .enable 3" /><br/>

Toggle Disabled attribute and show/hide at same time in jQuery

I'm trying to use jQuery.Validate on a multi-part form that requires showing and hiding some content and disabling the inputs that are not in view. Basically, if the user clicks on the button to toggle the additional input, it then shows so that they can enter data. But until it shows I need to keep it disabled so that jquery.validate will ignore it. Thus far I found a simple script that will toggle the disabled attribute and I can show/hide the input as needed but I need them to work together. Is there a simple way to have the input show/hide while toggling the attribute as well?
Here is a fiddle that shows what I have right now and it works but I have to click the #toggleDisabled button twice the first time:
JS Fiddle
Here is the function logic I am using:
(function($) {
$.fn.toggleDisabled = function() {
return this.each(function() {
var $this = $(this);
if ($this.attr('disabled')) $this.removeAttr('disabled').show();
else $this.attr('disabled', 'disabled').hide();
});
};
})(jQuery);
$(function() {
$('#toggleButton').click(function() {
$('#toggleInput').toggleDisabled();
});
});
And here is the simple HTML:
<form id="myform">
<input type="text" name="field1" /> <br/>
<br /> <input type="text" id="toggleInput" name="toggleInputName" style="display:none" />
<input type="button" id="toggleButton" value="Toggle Disabled" />
<input type="submit" />
</form>
Use .prop() instead of .attr()
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.prop('disabled')) {
$this.prop('disabled', false).show();
} else {
$this.prop('disabled', true).hide();
}
});
};
DEMO, You can try shorter form here
Also go through .prop() vs .attr()

how to find the last dynamic button clicked

I have created a dynamic buttons each button is the same:
<input type="button" id="editBtn" value="Edit" style="float: right" />//each button has its id ofcourse
When one button is pressed it shows a table.
I am looking for a way to 'click last button'/'hide the table' if an other button on page is clicked.
Using Jquery, is it possible ? or is there a better way to do it?
If u want to display content using button(hide/show)
You can accomplish this using jquery toogle function
$(document).ready(function()
{
$("#button").click(function()
{
$("#table").toggle();
});
});
link to fiddle
Simply hide all siblings of the selected table...
So for example, if you have (Pseudo code)
<input type="button" id="editBtn1" value="Edit" onclick="showTable(1)" />
<input type="button" id="editBtn2" value="Edit" onclick="showTable(2)" />
<input type="button" id="editBtn3" value="Edit" onclick="showTable(3)" />
<table id="table1">...</table>
<table id="table2">...</table>
<table id="table3">...</table>
JS would be :
function showTable(tableid) {
$("#table" + tableid).show().siblings().hide();
}
But of course, this is all very hard coded & hence an avoidable practice.
Or as discussed in comments :
function showTable() {
var tableId = $(this).index();
$("table").hide().eq(tableId).show();
}
I think this is what you want: http://jsfiddle.net/BY27P/9/
This will remember the tables you have viewed and let you view all previous ones using basic JavaScript array push/pop.
Here is the JavaScript (view fiddle for full code):
var viewedTableHistory = [];
hideAllTables=function(){
$('table[id^="table"]').hide(); //hide all tables
}
loadTable=function(id){
viewedTableHistory.push(id);
$('#history').text(viewedTableHistory);
hideAllTables();
showCurrentTable();
};
hideCurrentTable=function()
{
$('#table'+viewedTableHistory[viewedTableHistory.length-1]).hide();
};
showCurrentTable=function()
{
$('#table'+viewedTableHistory[viewedTableHistory.length-1]).show();
};
viewPrevTable=function()
{
hideAllTables();
viewedTableHistory.pop();
$('#history').text(viewedTableHistory);
if(viewedTableHistory.length===0) alert('You are back to the beginning.');
showCurrentTable();
};
I think I solved your problem try this fiddle ...
See output on below fiddle
Js fiddle
Style:
.tbl{
display:none;
}
Jquery:
$(".btn").click(function(){
var $this = $(this).next("table");
$( this ).next("table").removeClass("tbl");
$(".btn").next("table").not($this).addClass("tbl");
});
Html:
<div class="tble">
<input type="button" value="Button1" class="btn"/>
<table class="tbl"><tr><td>test1</td></tr></table>
</div>
<div class="tble">
<input type="button" value="Button2" class="btn" />
<table class="tbl"><tr><td>test2</td></tr></table>
</div>

Change button class and value for each click

I just made a timer with control, but in the control button i need some help.
Initially there have a button with START value. have to change the class and value to "STOP" for the 1st click and for the 2nd click change the class & value to "RESUME".
DEFAULT. <input class="start" type="button" value="START" />
1st click. <input class="stop" type="button" value="STOP" />
2nd click. <input class="resume" type="button" value="RESUME" />
3rd click. <input class="stop" type="button" value="STOP" />
4th click. <input class="resume" type="button" value="RESUME" />
Can you help me in this? and forgive my bad English.
FYI: i am using JQUERY MOBILE.
I haven't worked in JQuery mobile but this should be the way
JQuery
$(document).ready(function(){
$('input').click(function(){
if($(this).hasClass("start")){
$(this).removeClass("start");
$(this).addClass("stop");
$(this).val("STOP");
}else if($(this).hasClass("resume")){
$(this).removeClass("resume");
$(this).addClass("stop");
$(this).val("STOP");
}else if($(this).hasClass("stop")){
$(this).removeClass("stop");
$(this).addClass("resume");
$(this).val("RESUME");
}
});
})
for reference http://jsfiddle.net/zGMWR/1/
hope it helps
P.S. please put specific selector in jquery for your button.
Your initial value 'start' is irrelevant here as it only appears the very first time. So a simpler solution would be:
$(':button').on('click', function(){
$(this).removeClass('start stop resume');
if (this.value !== 'STOP') {
this.value = 'STOP';
$(this).addClass('stop');
} else {
this.value = 'RESUME';
$(this).addClass('resume');
}
});
An even shorter version would be:
$(':button').on('click', function(){
this.value = this.value !== 'STOP' ? 'STOP' : 'RESUME';
$(this).removeClass('start stop resume')
.addClass(this.value.toLowerCase());
});
Side info: answer from PSK: 376 Bytes; first answer here: 223 Bytes; second answer: 174 Bytes
Of Course you can wrap it in a $(document).ready(function(){ function if necessary
See http://jsfiddle.net/zGMWR/2/ and http://jsfiddle.net/zGMWR/3/ how it works
For a more specific selector and using event delegation you could use:
$('form').on('click', ':button', function(){...
or give the button an even more specific class name such as play-button

How to display one div and hide all others

I want to display a div on each button click and also want to hide the other all divs how I can do it.
HTML
<div id=a style="display:none">1</diV>
<div id=b style="display:none">2</diV>
<div id=c style="display:none">3</diV>
<div id=d style="display:none" >4</diV>
<input type=button value=1 id=w>
<input type=button value=2 id=x>
<input type=button value=3 id=y>
<input type=button value=4 id=z>
jQuery
$​('#w').live('click', function () {
$('#a').css('display', 'block');
});
$('#x').live('click', function () {
$('#b').css('display', 'block');
});
$('#y').live('click', function () {
$('#c').css('display', 'block');
});
$('#z').live('click', function () {
$('#d').css('display', 'block');
});
​ http://jsfiddle.net/6UcDR/
In your JSFiddle, you are using jQuery 1.7.2. If you are using this version in your real app, you should not be using $.live(), but use $.on() instead - the former is deprecated in favour of the latter.
The simplest and cleanest way to solve your problem would be to wrap both your buttons and divs in containers, and use $.index() to associate a button with a div:
<div class="showThese">
<div id="a" style="display:none">1</div>
<div id="b" style="display:none">2</div>
<div id="c" style="display:none">3</div>
<div id="d" style="display:none" >4</div>
</div>
<div class="buttons">
<input type="button" value="1" id="w">
<input type="button" value="2" id="x">
<input type="button" value="3" id="y">
<input type="button" value="4" id="z">
</div>
Note that your attributes must be quoted, as in the above HTML.
Then, in JavaScript, you only need to bind one delegated event to the buttons container. I'll use $.on() in this case:
$('div.buttons').on('click', 'input', function() {
var divs = $('div.showThese').children();
divs.eq($(this).index()).show().siblings().hide();
});
Here is a demo.
The above method does away with having to use IDs and other attributes, however you will need to be careful if you want other elements in the containers, as $.index() will begin to fail if you do.
Just start by hiding all other div's, then showing the one you want to be shown.
$​('#w').live('click', function(){
$('div').hide();
$('#a').show();
});
If understand you correctly, it should be just setting the display:none for the divs before showing your specific div.
$('#w').live('click', function(){
$('div').css('display','none');
$('#a').css('display','block');
});
$('#x').live('click', function(){
$('div').css('display','none');
$('#b').css('display','block');
});
$('#y').live('click', function(){
$('div').css('display','none');
$('#c').css('display','block');
});
$('#z').live('click', function(){
$('div').css('display','none');
$('#d').css('display','block');
});
​
live is deprecated, use on
$​('input').on('click', function(){
var index = $(this).index();
$('div').hide().eq(index).show();
});
example from jQuery.com:
function notify() { alert("clicked"); }
$("button").on("click", notify);
Check the demo http://jsfiddle.net/6UcDR/2/ Is this the thing that you want to achieve.
Try this jQuery-
$​('#w').click(function(){
$('#a').show()
$('#b,#c,#d').hide()
});
$('#x').click(function(){
$('#b').show();
$('#a,#c,#d').hide()
});
$('#y').click(function(){
$('#c').show();
$('#b,#a,#d').hide()
});
$('#z').click(function(){
$('#d').show();
$('#b,#c,#d').hide()
});
Add a class to all the divs u want to show or hide
eg:
<div id=a class="hide" style="display:none">1</diV>
And then add the following statement to each onclick function
$('.hide').css('display','none'); /* Replace .hide with whatever class name u have chosen*/
To see the answer in action: http://jsfiddle.net/6UcDR/1/

Categories