Button text swapping on clicking any 2 buttons with JQuery - javascript

There are five buttons:
<button id="btn1">1</button>
<button id="btn2">2</button>
<button id="btn3">3</button>
<button id="btn4">4</button>
<button id="btn5">5</button>
What Have To Be Done:
When clicking on any two buttons, the texts should swap between those buttons.
For example: If we click on "#btn1" and then on "#btn3", the text of "#btn1" should become "3" and the text of "#btn3" should become "1".
The above mentioned process should work on every buttons like clicking on the first button and the fifth button and so on.
Question: How can we do this with JQuery?

Set a data-flag attribute to the button which has been clicked and remove when the corresponding toggle button is clicked.
$( "button" ).click( function(){
if ( $("button[data-flag]").length > 0 ) //already clicked a button
{
var id = $("button[data-flag]").attr( "data-flag" );
var text = $(this).text();
$(this).text( $( "#" + id ).text());
$( "#" + id ).text( text );
$("button[data-flag]").removeAttr( "data-flag" ); //remove this line if toggling shouldn't clear
}
else
{
$(this).attr( "data-flag", this.id );
}
});
Demo
$( "button" ).click( function(){
if ( $("button[data-flag]").length > 0 ) //already clicked a button
{
var id = $("button[data-flag]").attr( "data-flag" );
var text = $(this).text();
$(this).text( $( "#" + id ).text());
$( "#" + id ).text( text );
$("button[data-flag]").removeAttr( "data-flag" );
}
else
{
$(this).attr( "data-flag", this.id );
}
});
button[data-flag]
{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">1</button>
<button id="btn2">2</button>
<button id="btn3">3</button>
<button id="btn4">4</button>
<button id="btn5">5</button>

You could use a class to identify which button should be swapped. That way you could apply some css to visually identify the button too. Also, this uses existing properties, rather than creating new variables.
css:
.swap { color: green; }
javscript:
$('button').on('click', function() {
if ($('button.swap').length) {
$(this).val(this.textContent).text($('button.swap').val());
$('button.swap').text(this.value).removeClass('swap').val('');
} else {
$(this).addClass('swap').val(this.textContent);
}
});
https://jsfiddle.net/Lpy08krd/

Option 1 - This is if you want to create a pair which swaps and resets on each 2nd click.
https://jsfiddle.net/Hastig/4skgd2a6/
$('button').click(function() {
if (!($('button').hasClass('first'))) {
$(this).addClass('first');
} else {
let thisText = $(this).text();
$(this).text($('button.first').text());
$('button.first').text(thisText).removeClass('first');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
Option 2 - This option is if you want to swap on each click, no resetting between pairs.
https://jsfiddle.net/Hastig/vw304u2x/
var gLastText = '';
var gLastButton;
$('button').click(function() {
if (gLastText !== '') {
var thisText = $(this).text();
$(this).text(gLastText);
$('#' + gLastButton).text(thisText);
}
gLastText = $(this).text();
gLastButton = $(this).attr('id');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">1</button>
<button id="btn2">2</button>
<button id="btn3">3</button>
<button id="btn4">4</button>
<button id="btn5">5</button>

Related

How could this JavaScript function be simplified. I have 100 buttons controlling the show/hide display of 100 content areas

The abbreviated JS file below provides the same functionality for 100 buttons.
All buttons are identified by ID names such as #btn1, #btn2 etc.
The buttons trigger the hide/show of content contained within div tags labelled within corresponding class names such as .btn1, .btn2, etc.
For example, selecting #btn1 is tied to the content within content content content .
The process is to select a button, then whichever button is selected, hide the content within all the 100 DIVs and then show the selected button’s associated content.
In writing the JS file I have written out the whole function 100 times - listing each one of 100 buttons to be selected, all 100 div areas to be hidden, and then the one div area to be shown.
How could this be simplified into a smarter and more concise function?
// JavaScript Document
$(document).ready(function() {
$('#btn0').click(function() {
location.reload();
});
});
$(document).ready(function() {
$('#btn1').click(function() {
$('.btn0').hide();
$('.btn1').hide();
$('.btn2').hide();
$('.btn3').hide();
$('.btn4').hide();
$('.btn5').hide();
$('.btn6').hide();
$('.btn7').hide();
$('.btn8').hide();
$('.btn9').hide();
$('.btn10').hide();
$('.btn11').hide();
$('.btn11').hide();
$('.btn12').hide();
$('.btn13').hide();
$('.btn14').hide();
$('.btn15').hide();
$('.btn16').hide();
$('.btn17').hide();
$('.btn18').hide();
$('.btn19').hide();
$('.btn20').hide();
$('.btn21').hide();
$('.btn22').hide();
$('.btn23').hide();
$('.btn24').hide();
$('.btn25').hide();
$('.btn26').hide();
$('.btn27').hide();
$('.btn28').hide();
$('.btn29').hide();
$('.btn30').hide();
$('.btn31').hide();
$('.btn32').hide();
$('.btn33').hide();
$('.btn34').hide();
$('.btn35').hide();
$('.btn36').hide();
$('.btn37').hide();
$('.btn38').hide();
$('.btn39').hide();
$('.btn40').hide();
$('.btn41').hide();
$('.btn42').hide();
$('.btn43').hide();
$('.btn44').hide();
$('.btn45').hide();
$('.btn46').hide();
$('.btn47').hide();
$('.btn48').hide();
$('.btn49').hide();
$('.btn50').hide();
$('.btn51').hide();
$('.btn52').hide();
$('.btn53').hide();
$('.btn54').hide();
$('.btn55').hide();
$('.btn51').hide();
$('.btn52').hide();
$('.btn53').hide();
$('.btn54').hide();
$('.btn55').hide();
$('.btn56').hide();
$('.btn57').hide();
$('.btn58').hide();
$('.btn59').hide();
$('.btn60').hide();
$('.btn61').hide();
$('.btn62').hide();
$('.btn63').hide();
$('.btn64').hide();
$('.btn65').hide();
$('.btn66').hide();
$('.btn67').hide();
$('.btn68').hide();
$('.btn69').hide();
$('.btn70').hide();
$('.btn71').hide();
$('.btn72').hide();
$('.btn73').hide();
$('.btn74').hide();
$('.btn75').hide();
$('.btn76').hide();
$('.btn77').hide();
$('.btn78').hide();
$('.btn79').hide();
$('.btn80').hide();
$('.btn81').hide();
$('.btn82').hide();
$('.btn83').hide();
$('.btn84').hide();
$('.btn85').hide();
$('.btn86').hide();
$('.btn87').hide();
$('.btn88').hide();
$('.btn89').hide();
$('.btn90').hide();
$('.btn91').hide();
$('.btn92').hide();
$('.btn93').hide();
$('.btn94').hide();
$('.btn95').hide();
$('.btn96').hide();
$('.btn97').hide();
$('.btn98').hide();
$('.btn99').hide();
$('.btn100').hide();
$('.btn98').hide();
$('.btn99').hide();
$('.btn100').hide();
$('.btn1').show();
});
});
$(document).ready(function() {
$('#btn2').click(function() {
$('.btn0').hide();
$('.btn1').hide();
$('.btn2').hide();
$('.btn3').hide();
$('.btn4').hide();
$('.btn5').hide();
$('.btn6').hide();
$('.btn7').hide();
$('.btn8').hide();
$('.btn9').hide();
$('.btn10').hide();
$('.btn11').hide();
…………………….. BTN12 to 97 ……………………..
$('.btn98').hide();
$('.btn99').hide();
$('.btn100').hide();
$('.btn1').show();
});
});
Etc., up to 100 buttons
// JavaScript Document
Assuming you can't change the html structure, I would probably do:
$('[id^="btn"]').on('click', function() {
const id = $(this).attr('id');
$('[class^="btn"]').hide();
$(`.${id}`).show();
});
Which will listen to the click event on any element where the id starts with btn, then hide all elements where the class starts with btn, then show the element with the same class as the id that was just clicked (e.g. #btn2 click will show .btn2)
something like this.
for(let i = 0;i<=99;i++){
let btnclass= ".btn" + i;
$(btnclass).hide()
}
You can use a for loop to iterate from 0 to 100:
$(document).ready(function() {
$("#btn1").click(function() {
for (let i = 0; i <= 100; i++) {
$(`.btn${i}`).hide();
}
});
})
Full version:
// JavaScript Document
$(document).ready(function() {
$("#btn0").click(function() {
location.reload();
});
});
$(document).ready(function() {
$("#btn1").click(function() {
for (let i = 0; i <= 100; i++) {
$(`.btn${i}`).hide();
}
});
})
$(document).ready(function() {
$("#btn2").click(function() {
for (let i = 0; i <= 100; i++) {
$(`.btn${i}`).hide();
}
});
});
Common class and data attributes along with event delegation makes the code easier to maintain.
document.querySelector("#wrapper").addEventListener("click", function (event) {
var toggles = event.target.dataset.toggles;
// Hide previous selected elements
var selectedElems = document.querySelectorAll(".out.selected");
if (selectedElems.length){
selectedElems.forEach(function (elem) {
elem.classList.remove("selected");
});
}
// show the new active elements
const activeElems = document.querySelectorAll(toggles);
if (activeElems.length){
activeElems.forEach(function (elem) {
elem.classList.add("selected");
});
}
});
.out {
display: none;
}
.out.selected {
display: block;
}
<div id="wrapper">
<button id="btn1" data-toggles=".out1">1</button>
<button id="btn2" data-toggles=".out2">2</button>
<button id="btn3" data-toggles=".out3">3</button>
<button id="btn4" data-toggles=".out4">4</button>
</div>
<div class="out out1">1</div>
<div class="out out2">2</div>
<div class="out out3">3</div>
<div class="out out4">4</div>
If you want to use jQuery
$("#wrapper").on("click", "[data-toggles]", function (event) {
var toggles = $(this).data('toggles');
$(".out.selected").removeClass("selected");
$(toggles).addClass("selected");
});
.out {
display: none;
}
.out.selected {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
<button id="btn1" data-toggles=".out1">1</button>
<button id="btn2" data-toggles=".out2">2</button>
<button id="btn3" data-toggles=".out3">3</button>
<button id="btn4" data-toggles=".out4">4</button>
</div>
<div class="out out1">1</div>
<div class="out out2">2</div>
<div class="out out3">3</div>
<div class="out out4">4</div>

Changing color of only button that was clicked

I mean I want to change CSS properties of only the button that I've clicked and at the same time set other buttons to previous color. Hope I explained my problem clear
for(let i = 0; i < categoryBtns.length; i++) {
categoryBtns[i].addEventListener('click', function() {
let attr = this.getAttribute('id');
if(categoryBtns[i - 1].id != attr || categoryBtns[i + 1].id != attr) {
log([i]);
console.log('works');
this.style.backgroundColor = '#000000';
} else {
log('no');
}
})
}
I have also code that shows only divs that have current category. Should I code buttons in the same time when divs are showing and hiding?
$(document).ready(function() {
$('.category-item').click(function() {
let category = $(this).attr('id');
if(category == 'all') {
$('.prod_item').addClass('hide');
setTimeout(function() {
$('.prod_item').removeClass('hide');
}, 300);
} else {
$('.prod_item').addClass('hide');
setTimeout(function() {
$('.' + category).removeClass('hide');
}, 300);
}
});
});
I hope that I understood what you want correctly
const btns = document.querySelectorAll('.btn')
btns.forEach(btn => {
btn.addEventListener('click', () => {
btns.forEach(b => {
(b.classList.contains("active"))?
b.classList.remove("active"):true
});
btn.classList.add("active")
});
})
.active {
background-color: blue;
}
<button class = "btn">Click Me</button>
<button class = "btn">Click Me</button>
<button class = "btn active">Click Me</button>
<button class = "btn">Click Me</button>
<button class = "btn">Click Me</button>
use Array.forEach() to loop through the buttons and add/remove a styled class:
const btns = document.querySelector(".buttons");
const arr = Array.prototype.slice.call(btns.children, 0);
arr.forEach((el) => {
el.addEventListener("click", () => {
arr.forEach((el2) => {
el2.classList -= "active";
});
el.classList.toggle("active");
});
});
button.active {
color: red;
}
<div class="buttons">
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<button>Button 4</button>
<button>Button 5</button>
</div>
You can add a class for the button clicked state, and a default color for all buttons inside divs with class category-item. One javascript function removes the clicked class from all buttons while the other adds it to a specific button.
$(document).ready(function() {
$('.category-item input[type="button"]').click(function() {
removeClickedClass();
addClickedClass(this.id);
});
function removeClickedClass() {
$('.category-item input[type="button"]').removeClass("btnColorClicked");
}
function addClickedClass(elemID) {
let id = "#" + elemID;
$(id).addClass("btnColorClicked");
}
});
.category-item input[type="button"] {
font-weight: bold;
background-color: #4CAF50;
cursor: pointer;
}
.btnColorClicked {
background-color: #0099ff !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="category-item">
<input type="button" class="" id="1" value="hi" />
</div>
<div class="category-item">
<input type="button" class="" id="2" value="there" />
</div>
<div class="category-item">
<input type="button" class="" id="3" value="hey" />
</div>
Here is an answer for your first block without jQuery, but you should get it.
function colorizeButtons(id) {
for (let i = 0; i < categoryBtns.length; i += 1) {
const buttonId = categoryBtns[i].getAttribute('id');
// Clicked button
if (buttonId === id) {
// Set the clicked color button
} else {
// Set other buttons color
}
}
}
for (let i = 0; i < categoryBtns.length; i++) {
categoryBtns[i].addEventListener('click', function() {
let attr = this.getAttribute('id');
colorizeButtons(attr)
});
}
here is an example with jquery btns are the list of buttons elements and when clicked they turn red if click again they turn white
$(btns).on("click",function(){
if(!this.clicked){
this.clicked = true;
$(this).css("background-color", "red");
}
else{
this.clicked = false;
$(this).css("background-color", "white");
}
});

Hide text with the same button it opened it

how can I hide the text opened while clicking on a button by clicking on the same button ? In other words, the same button should show or hide a text when you click on it.
Here's my code that shows a text :
<h3>
<button class="button" onclick="myFunction()" ><img src="infoicon.png" height="30"></button>
<p id="infos"></p>
<script>
function myFunction() {
document.getElementById("infos").innerHTML = "blablabla";
}
</script>
</h3>
Define a variable to save the button state
var clicked = 0;
function myFunction() {
if(clicked == 0 ) {
document.getElementById("infos").innerHTML = "blablabla";
clicked = 1;
} else {
document.getElementById("infos").innerHTML = "";
clicked = 0;
}
}
<h3>
<button class="button" onclick="myFunction()" ><img src="infoicon.png" height="30"></button>
<p id="infos"></p>
</h3>
Try this out, it worked for me:
function showHide() {
var demo = document.getElementById('demo');
if (demo.innerHTML === "") {
demo.innerHTML = "bla";
} else {
demo.innerHTML = "";
}
}
<p id="demo"></p>
<button onclick="showHide()">Show Hide</button>
Quite simple, using jQuery—
$( "#button" ).click(function() {
$('#text-to-toggle').toggle(200);
});

How to select the previous element using jquery "on"?

I am trying to edit the text on a label.
I want to:
Show a label and hidden text Box.
On click of label: label gets hide and text Box shows where I can edit text.
On Enter, text Box should hide and label should display the entered text.
Here is the sample code.
But its not working as expected.
<h4>Editable labels (below)</h4>
<span class="k-link">
<label class="pull-left">Dashboard</label>
<input class="clickedit" type="text" id="731"/>
</span>
Demo
Check out this Demo.
Change the code from
$('.k-link').on('click', ".clickedit.prev()", function (event) {..
into
$('.k-link').on('click', ".pull-left", function (event) {..
And add inline css style for
<input class="clickedit" type="text" id="731" style="display:none"/>
Is this the functionality you want?
$(document).on('click', '#label', function() {
var that = $(this);
that.hide();
$('#731').removeClass('hidden');
});
$(document).on('focusout', '#731', function() {
var that = $(this);
var val = that.val();
that.hide();
$('#label').after('<span>' + val + '</span>');
});
.hidden { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h4>Editable labels (below)</h4>
<span class="k-link">
<label id="label" class="pull-left">Dashboard</label>
<input class="clickedit hidden" type="text" id="731"/>
</span>
This works:
$(document).ready(function(){
$(".clickedit").hide()
$(".pull-left").on("click", function(){
$(this).hide()
$(".clickedit").show()
});
$(".clickedit").on("blur", function(){
$(this).hide()
$(".pull-left").text($(this).val()).show()
});
});
this is working check it
i have just edit the selector it was .clickedit.prev() and i have change it to .pull-left
$('.k-link').on('click', ".pull-left", function (event) {
$(this).hide();
$(this).next().show().focus();
event.stopPropagation();
});
http://jsfiddle.net/anisboukhris/qho0uLzv/
may be try this:
$(document).ready(function(){
$("#f1").hide();
$("#text").hide();
var $curr = $( "#start" );
$curr.css( "background", "#f99" );
$( "button" ).on('click',function() {
$curr = $curr.prev();// this will go to previous div as you have asked how to get previous element.
$curr.show();
});
$( "#label" ).on('click',function() {
$("#label").hide();
$("#text").show();
$( "#text" ).blur(function() {
$("#label").show();
$("#text").hide();
$("#label").html($("#text").val());
});
});
});
div {
width: 150px;
height: 40px;
margin: 10px;
float: left;
border: 2px blue solid;
padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="f1"><span id="label">Came to previous div</span><input type="text" id="text" /></div>
<div id="start"></div>
<p><button>Go to Prev</button></p>

jQuery progress bar giving values to certain divs

I have a simulated multi page layout I am working on. Some of them have conditional statements to hide or show them. Right now I have it set in the function to increment the progress bar by 5 every time the user clicks next. The problem is that if I have a few of the divs hidden and they never appear, the progress bar does not increment correctly. Is there a way to give each div a value so that it reads it when it is marked unhidden so that the progress bar is updated accordingly? Demo Here
This is my Div layout:
<div class="Page" id="DealerInfo" style="display: block;">
<script>$( "#DealerInfo" ).load( "formPages/DealerInfo.php" );</script>
</div>
<div class="Page hidden" id="AdditionalLocations" style="display: none;">
<script>$( "#AdditionalLocations" ).load( "formPages/AdditionalLocations.php" ); </script>
</div>
<div class="Page" id="OwnerInfo" style="display: none;">
<script>$( "#OwnerInfo" ).load( "formPages/OwnerInfo.php" );</script>
</div>
<div class="Page" id="SalesInfo" style="display: none;">
<script>$( "#SalesInfo" ).load( "formPages/SalesInfo.php" );</script>
</div>
This is the function
function nextForm() {
$(".Page:visible").hide( ).nextAll( ".Page" ).not(".hidden").first().show();
var value = $( "#progressbar" ).progressbar( "option", "value" );
$( "#progressbar" ).progressbar( "option", "value", value + 5 );
$('.progress-label').text(value + "%");
}
These are my buttons:
<p class="navigation"><button class="button" type="button" onclick="prevForm();">Previous</button>
<button class="button" type="button" onclick="nextForm();">Next</button></p>
Why not simply calculate a percent done as a function of how many .not('hidden') divs are before your active one divided by the total number of .not('hidden') divs?
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if($(".Page:visible").length < 1) {
value = 100;
} else {
value = Math.floor(100*($(".Page:visible").prevAll(".Page:not(.hidden)").length)/($(".Page:not(.hidden)").length));
}
$("#progressbar").progressbar("option", "value", value);
$('.progress-label').text(value + "%");
}
function nextForm() {
$(".Page:visible").hide().nextAll(".Page").not(".hidden").first().show();
updateProgress();
}
function prevForm() {
$(".Page:visible").hide().prevAll(".Page").not(".hidden").first().show();
updateProgress();
}
JSFiddle Demo
This will scale automatically as you add sections. You won't need to add any values to the divs at all.
If you are going to show/hide .hidden divs depending on answers to questions, simply leave :not(.hidden) out of the selectors:
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if($(".Page:visible").length < 1) {
value = 100;
} else {
value = Math.floor(100*($(".Page:visible").prevAll(".Page").length)/$(".Page").length);
}
$("#progressbar").progressbar("option", "value", value);
$('.progress-label').text(value + "%");
}
JSFiddle Demo

Categories