Change text inside a button on each click using javascript? - javascript

I need to change text each time I click on button.
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("data-text") == button.innerHTML) {
button.innerHTML = button.getAttribute("data-text1");
} else {
button.setAttribute("data-text1", button.innerHTML);
button.innerHTML = button.getAttribute("data-text");
}
},
false
);
<div>
<button id="changeText" data-text="Show" data-text1="Hide">Hide</button>
</div>
I don't understand why this code doesn't work when I try to load page using google chrome. However when I loaded it to codepen it worked

It expects from you certain structure like this one:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText" text="Show" >Hide</button>
</div>
<script>
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("text") == button.innerHTML) {
button.innerHTML = button.getAttribute("text1");
} else {
button.setAttribute("text1", button.innerHTML);
button.innerHTML = button.getAttribute("text");
}
},
false
);
</script>
</body>
</html>
Copy paste it to your file and you'll see that it works.
Please mark it as an answer if it fixes your problem :)

Your code is working, but your approach is not so nice. See the 2 options down below.
let text = {
'Hide': 'Show',
'Show': 'Hide'
}
const click = (event) => {
// option 1, it needs the object above.
// It's good for multiple alternatiosn like color, icon etc
// or multiple states like hide to show, show to sure, sure to really, really to hide.
event.target.innerText = text[event.target.innerText];
// option 2, it's good for one or two alternations.
// event.target.innerText = event.target.innerText == 'Hide' ? 'Show' : 'Hide'
}
document.querySelector('button').addEventListener('click', click);
<button>Show</button>

you can make it more simple by removing the custom attribute and use the button innerHTML only along with enum by using Object.freeze(),it will make the code more readable
const titleEnum = Object.freeze({show: "SHOW", hide: "HIDE"});
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.innerHTML === titleEnum.hide) {
button.innerHTML = titleEnum.show;
} else {
button.innerHTML = titleEnum.hide;
}
},
false
);
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText">HIDE</button>
</div>
</body>
</html>

Use innerText to get the value of an element
const changeBtn = document.getElementById("changeText");
changeBtn.addEventListener("click", ()=>{
if(changeBtn.innerText === "2"){
changeBtn.innerText = "1";
}
else{
changeBtn.innerText= "2";
}
});
<div>
<button id="changeText">1</button>
</div>

Related

I want to disable click property after I click once

**I want to disable clickability after the first click ** I used this code but did not work.
let counter = 0;
inputOptions.forEach((inputOptions) => {
inputOptions.addEventListener("click", () => {
inputOptions.classList.toggle("active");
if (inputOptions.classList.contains("active")) {
inputOptions.style.pointerEvent = 'none';
}
if (inputOptions.innerHTML == "Dhaka") {
counter++;
} else { counter = 0; }
})
})
function getResult() {
document.getElementById("result").innerHTML = "No of Correct answer:" + counter;
}
you can pass parameter { once: true }
document.querySelectorAll('button').forEach((inputOptions) => {
inputOptions.addEventListener("click", (el) => {
console.log(inputOptions)
}, { once: true })
})
<button>A</button>
<button>B</button>
here is sample of code for disabled button after once click.
You need to define id in html then access button like below code.
this is just sample of working code. you need to get idea from this then implement according to your requirement
<html>
<head>
<title>JavaScript - Disable Button after Click using JavaScript Function.</title>
<script type="text/javascript">
function disableButton(btn){
document.getElementById(btn.id).disabled = true;
alert("Button has been disabled.");
}
</script>
</head>
<body style="text-align: center;">
<h1>JavaScript - Disable Button after Click using JavaScript Function.</h1>
<p><input type="button" id="btn1" value="Click to disable button." onclick="disableButton(this)"</p>
</body>
</html>

Is it possible to alter innerHTML/textContent back and forth (endlessly)?

So i'm thinking to changing innerHTML of <p>Click</p> from content of "Click" into "Clicked" and when being clicked again it changes back again to "Click" (and could be clicked back again to result "Clicked" for endless times).
Can someone give clue? *I appreciate,
This is my fail attempt so far -->
<!DOCTYPE html>
<body>
<p id="event_01">Click</p>
<script>
let goo = document.querySelector("#event_01");
let clickOnce = function() {goo.innerHTML = "Clicked"};
let clickBack = function(){
goo.innerHTML = "Click"};
if(goo.textContent == "Click") {
goo.addEventListener("click", clickOnce);
} else if (goo.textContent == "Clicked") {
goo.addEventListener("click", clickBack);
}
</script>
</body>
You should put your condition inside a click handler instead of outside. What's between the script tag will only execute once. When the code runs (on page load) the content of goo is Click, so only the listener that sets the content to "clicked" ever gets attached to the element. instead you should do somthing like this:
let goo = document.querySelector("#event_01");
let onClick = function() {
if(goo.textContent == "Click"){
goo.innerHTML = "Clicked";
} else {
goo.innerHTML = "Click";
}
};
goo.addEventListener("click", clickOnce);
You just need to check the value of the .innerHTML of the <p></p>, compare it to the current .innerHTML and change it accordingly
<!DOCTYPE html>
<body>
<p id="event_01" onClick="myFunction()">Click</p>
<script>
function myFunction() {
var x = document.getElementById("event_01");
if (x.innerHTML === "Click") {
x.innerHTML = "Clicked";
} else {
x.innerHTML = "Click";
}
}
</script>
</body>
You just need one listener, attached from the beginning:
let goo = document.querySelector("#event_01");
goo.addEventListener("click", clickListener);
let clickListener = function() {
if (goo.innerHTML == "<p>Click</p>")
goo.innerHTML = "<p>Clicked</p>";
else
goo.innerHTML = "<p>Click</p>";
}
This is simple. your adding to much code.
first of when the p is clicked you assign a click event to clickOnce but in clickOnce
back you never assign clickBack.
Here is an example about what you want to do.
let goo = document.querySelector("#event_01");
let clickMe = function() {
if(goo.textContent == "Click")
{
goo.innerHTML = "Clicked";
}
else
{
goo.innerHTML = "Click";
}
}
goo.addEventListener("click", clickMe);
<p id="event_01">Click</p>
If you don't want to use functions or variables, you can use e.target.textContent
<!DOCTYPE html>
<body>
<p id="event_01">Click</p>
<script>
document.querySelector("#event_01").addEventListener('click', (e) => {
if (e.target.textContent === 'Click') {
e.target.textContent = 'Clicked'
} else if (e.target.textContent === 'Clicked') {
e.target.textContent = 'Click'
}
})
</script>
</body>

Deleting DOM elements with button.onclick in javascript

As I am learning javascript I was testing different things. I made a small function:
foo("div", "button");
function foo(divId, buttonId)
{
var flag = 1;
var button2;
document.getElementById(buttonId).onclick = function() {
if (flag) {
button2 = createButton("Ceaning Service");
var span = createSpan("I will be removed");
var div = document.getElementById(divId);
div.appendChild(span);
document.body.insertBefore(button1, div);
flag = 0;
}
if (!flag) {
button2.onclick = function() {
div.removeChild(span);
document.body.removeChild(button1);
flag = 1;
return;
}
}
}
}
function createButton(text)
{
var button = document.createElement("BUTTON");
button.innerHTML = text;
return button;
}
function createSpan(text)
{
var span = document.createElement("SPAN");
span.innerHTML = text;
return span;
}
I can click the second button without errors only when I click the first button Click Me once. When I click Click Me button more than once and try to click the second button, it shows div is undefined. (span is undefined too, but it won't show because browser reaches div first).
Html:
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
</head>
<body>
<button id="button">Click Me</button><br>
<div id="div"></div>
<script src="test3.js"></script>
</body>
</html>
I played around with this function and when I declare span and div before ...(buttonId).onclick =... it works.
So why this code only works when I click Click Me once? I think with the second click it cannot reference to the created elements, but not sure why.
And although it removes those elements, will they be removed by the garbage collection as well or is there some kind of a memory leak happening?
And please try not to reference jQuery or some other libraries/frameworks. It would only complicate things for me for now.

javascript: toggle plain text to hide it like password text on click of a button

I do not have a <input> or any form. I want some way to toggle a plain text to something like **** on click of a button.
for example I have
<p id='one'>google_yahoo</p>
<button id='two'>toggle</button>
so when I click the button once, <p> should become:
<p>************</p>
Then when I click the button then I should again get back google_yahoo
But by default I want it be in ***** form.
What I did:
<script>
function myfunction(){
$("#two").click(function(){
$("#one").text("abc");
});
};
</script>
Any straightforward, easy to understand solution anyone?
You need to create some variables to store value of your text. Try it on JSFiddle.
var txt = document.getElementById('one');
var btn = document.getElementById('two');
var visible = 1;
var value = '';
btn.addEventListener('click', function(){
if(visible){
value = txt.innerHTML;
txt.innerHTML = '*'.repeat(value.length);
}else{
txt.innerHTML = value;
}
visible = !visible;
});
var pMemory = null;
$('button').click(function() {
var pElement = $('p').get(0);
if (pMemory === null) {
// save to cache
pMemory = $(pElement).text();
}
if (pMemory === $(pElement).text()) {
$(pElement).text('*'.repeat(pMemory.length));
} else {
$(pElement).text(pMemory);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>google_yahoo</p>
<button>toggle</button>
Using text-security css property as an option.
$(document).ready(function(){
$("#two").on("click", function(){
$("#one").toggleClass("password_field");
})
})
.password_field{
-webkit-text-security:disc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id='one' class="password_field">google_yahoo</p>
<button id='two'>Toggle</button>

Transfer href text to textbox

This is the current code I have
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body>
Active
Inactive
Banned
<input type="text">
</body>
</html>
What I want to do is when I click on active, the textbox will have the word active and so on. Is there a way to do this?
You can do this using jquery:
$(document).ready(function() {
$('a').click(function(e) {
e.preventDefault();
var text = $(this).text();
$('input[type=text]').val(text);
});
});
In pure javascript you could do this:
html - I would suggest adding an id to the input
<body>
Active
Inactive
Banned
<input id="foo" type="text">
</body>
javascript
var links = document.querySelectorAll( 'a' );
var input = document.getElementById('foo');
function setInput(event) {
event.preventDefault();
input.value = event.target.innerHTML;
};
for( var i=links.length; i--; ) {
links[i].addEventListener( 'click', setInput, false );
};
And without JQuery just in case someone wants it :
http://jsfiddle.net/s0ds5rdy/
I recommend putting "#" in the href attribute. It'll scroll to the top of the page if you don't preventDefault, while browsers might reload the page if you click on a blank link.
window.addEventListener("load", function () {
var allLinks = document.getElementsByTagName("a");
for (var i = 0; i < allLinks.length; ++i) {
allLinks[i].addEventListener("click", function (e) {
e.preventDefault();
document.querySelector('input[type=text]').value = e.target.innerHTML;
});
}
});

Categories