Change text on button when clicked with JavaScript - javascript

I'm trying to change the text of a button when it's pressed with JavaScript. Should be very straightforward, however, it's not working. Can anyone explain? Here's my code:
function changeInnerHTML() {
var buttonValue = document.getElementById('elementTEST').innerHTML;
var buttonValueInnerHTMLBegin = '<p id="elementTEST">';
var buttonValueInnerHTMLEnd = '</p>';
alert("buttonValue = " + typeof(buttonValue)); // -> "string"
if (buttonValue == "Online") {
alert("turn off"); // -> "turn off"
buttonValue = buttonValueInnerHTMLBegin + "Offline" + buttonValueInnerHTMLEnd; // -> DOESN'T CHANGE ANYTHING
alert("turned off"); // -> "turned off"
} else if (buttonValue == "Offline") {
buttonValue = "Online";
} else {
alert("There's a problem");
}
}
<div class="containerTEST">
<div class="divTEST" onclick="changeInnerHTML()">
<p id="elementTEST">Online</p>
</div>
</div>
I have run this both with and without the "buttonValueInnerHTMLBegin/End" variables being included, and I get the same result.
I get the alerts (shown as comments in the code), but the text/innerHTML doesn't change.
Thanks for any help!

It's not a reference, you'll have to set it directly at the end:
document.getElementById('elementTEST').innerHTML = buttonValue

try this:
var buttonValue = document.getElementById('elementTEST');
function changeInnerHTML(){
if (buttonValue.innerHTML == "Online")
buttonValue.innerHTML= "Offline";
else if (buttonValue.innerHTML == "Offline")
buttonValue.innerHTML = "Online";
}
codepen: example

There's absolutely no reason to change the HTML. Change only the textContent
(Use Element.innerHTML = "bla" to set a new inner HTML)
Use Element.textContent = "bla" to set a new text content
Don't use inline JS onclick - it's discouraged for code maintainability reasons
Use a <button> for semantic reasons and accessibility
Here's a simpler version
[...document.querySelectorAll(".toggleOnline")].forEach( el =>
el.addEventListener("click", () => {
el.textContent = /online/i.test(el.textContent) ? "Offline" : "Online";
})
);
.toggleOnline {
border: none;
border-radius: 0;
background: #ddd;
padding: 8px 16px;
}
<button class="toggleOnline" type="button" aria-live="assertive" aria-atomic="true">
Online
</button>
Now you can also tab your element and use Spacebar or Enter to toggle your button.

Related

How make input RESET Button?

How make input RESET Button?
INFO:
Hi I'm trying to do that if I click on my input which has the ID search-input so that if I write something in the input then class cancel which is the cross that resets the value it's like <button type =" reset "> so if I write something so that it appears to me sodisplay: block;and if I delete or input it won't have a value to dodisplay: none;and I would like to do all this to make it work even if the user doesn't have Javascript so I would like to do it in PHP version but I don't know what I have so far I only have this code which shows the icon when something is in the input but unfortunately the code has stopped working and especially when I delete the input via the button so the icon doesn't disappear for more information be sure not to be afraid to ask.
const input = document.getElementById("search-input")
const button = document.getElementById("cancel")
const icon = document.getElementById("icon")
input.addEventListener('keyup', test);
button.addEventListener("button", test)
function test() {
let isShown = false
if (input.value.trim() == "" || isShown == false) {
icon.style.display = "none"
isShown = true
} else {
icon.style.display = "flex"
}
}
PS: Everything was translated by Google translator if there was a mistake or you did not understand something write and I will definitely tell you how it should be thought in advance thank you very much for your help.
I think Uttam Nath's answer was close to what you wanted but not exactly. This may work better:
EDIT: Alright I changed the code a bit and I added the HTML with it so there is no confusion.
<body>
<input type="text" id="search-input">
<button type="button" id="cancel">Cancel</button>
<div id="icon" style="background-color: green; width: 50px; height: 50px; display: none;"></div>
</body>
<script>
const input = document.getElementById("search-input");
const button = document.getElementById("cancel")
const icon = document.getElementById("icon");
input.addEventListener('keyup', changeIconDisplay);
button.addEventListener('click', () => {
input.value = '';
changeIconDisplay();
});
function changeIconDisplay() {
if (input.value.trim() == "" ) {
icon.style.display = "none";
} else {
icon.style.display = "flex";
}
}
</script>

Foreach element create one element after it on click (error warning)

So for a form I'd like to create an error message after each element which is invalid, onclick of the submit button.
I have almost got it right, except it adds the span twice after the element (because two elements are invalid). I need to to add it once, to both invalid elements.
So my JS/jquery (yes, I know, I mixed it :p):
function checkrequired() {
var nbform = document.getElementById("userpanel");
var elements = document.querySelectorAll('[required]');
elements.forEach(element => {
if (element.value === "") {
nbform.classList.add('submitted-form-invalid');
$('.show-error').after("<span class='col-sm-12' style='color:red;'> Name is required.</span>");
} else {
return true;
}
});
How it looks:
I also know it adds it twice, instead of once, because it adds it foreach element. But I don't know how to surpass this. Anyone?
EDIT:
I came up with the next Javascript, this idea is all that I need. It doesn't need to be really complicated:
function checkrequired() {
var el = document.createElement("div");
el.setAttribute('class', 'error-message');
el.innerHTML = "Dit veld is verplicht";
var x = document.querySelectorAll('.show-error');
for (var i = 0; i < x.length; i++) {
x[i].appendChild(el);
}
}
The only problem now is that it only appends the child to the sconds div with class "error-message". Not both.
try this
// select your inputs with an id
var elements = document.querySelectorAll('#voornaam');
$("button").click(function(){
elements.forEach(element => {
if (element.value === ""&& element.nextSibling.id !="error") {
$("<span class='col-sm-12 error' id='error' style='color:red;'> Name is required.</span>").insertAfter(element);
return
}
else return true
})
});
});
$('.show-error') returns an array of elements. For all these elements you are adding the span after it checks invalid. I think plain js gives you more control here.
So here's an example snippet in plain vanilla js.
Maybe this jsFiddle is helpfull too. And remember: checking in the browser will not render a server side check unnecessary.
document.addEventListener("click", checkRequired);
const setError = (elem, remove) => {
const span = document.createElement("span");
span.classList.add("foutmelding");
span.appendChild(document.createTextNode(` vul svp ${elem.getAttribute("placeholder")} in`));
elem.insertAdjacentElement("afterEnd", span);
};
function checkRequired(evt) {
if (evt.target.id === "check") {
document.querySelectorAll(".foutmelding")
.forEach(el => el.parentNode.removeChild(el));
const validMsg = document.querySelector("#formValidation");
validMsg.dataset.invalid = "";
document.querySelectorAll('[required]')
.forEach(element => {
if (element.value.trim() === "") {
setError(element);
validMsg.dataset.invalid = "onvolledig ingevuld";
}
});
validMsg.dataset.invalid = validMsg.dataset.invalid || "all checks out well";
}
}
input {
margin: 0.3rem 0;
}
.foutmelding,
.formulierMelding {
color: red;
}
.formulierMelding:before {
content: attr(data-invalid);
}
<div id="theForm">
<input type="text" id="voornaam" placeholder="voornaam" required><br>
<input type="text" id="email" placeholder="e-mailadres" required>
</div>
<button id="check">Check</button>
<span id="formValidation" data-invalid class="formulierMelding"></span>

Condition not working inside eventListener

I need to make a simple events listener, which will change the 1st value element of the input.value each time, when the button will be clicked. To solve this problem, I wrote a simple condition inside the function menuide for onclick listener. But for some reason it's only works once when listening to an event, although every time an event triggers, it should work and fulfil one of the conditions.
Can anyone explain to me why my function change input.value[0] only once of all clicks?
function menuide() {
menu.classList.toggle('ul-wide');
var arr = 'b';
var value = Array.prototype.slice.call(inp.value);
var newValue = value.splice(1);
if (inp.value[0] != 'b') {
inp.value = arr + newValue.join('');
}
if (inp.value[0] == 'b') {
inp.value[0] == 'a' + newValue.join('');;
}
}
inp.addEventListener('click', menuide);
ul {
display: none;
}
.ul-wide {
display: grid;
}
<input type="button" id="inp" value="a click on me to make a wonder! :)"></input>
<ul id="menu">
<li>Smile</li>
<li>Happy</li>
<li>Dog</li>
</ul>
There is few errors in your code:
1. Instead of inp.value[0] == 'a' + newValue.join('');;
you probably want to write inp.value = 'a' + newValue.join('');
2. Also before second if you need to add else
function menuide() {
menu.classList.toggle('ul-wide');
var arr = 'b';
var value = Array.prototype.slice.call(inp.value);
var newValue = value.splice(1);
if (inp.value[0] !== 'b') {
inp.value = arr + newValue.join('');
} else if (inp.value[0] === 'b') {
inp.value = 'a' + newValue.join('');
}
}

Creating a callback function containing if else statement

the problem I have is that I would like to use an if else statement in a callback function like this:
alertNotify("alert","Do you want to delete this",function(delete) {
if(delete) {
//do code
}else {
//do nothing
}
});
current function code:
function alertNotify(text,type) {
$("body").append("<div id = 'alert' class='common'>\
<div id ='content'class='common'>\
</div>\
</div>");
var alert = $("<div id = 'ok' class='common'>\
Ok\
</div>\
<div id = 'cancle''class='common'>\
Cancle\
</div>");
var rename = $("<div class='common rename_it'>\
Ok\
</div>");
var type_file = $("<input type='text' id ='rename'><div id='hover'></div>");
if(type == "alert") {
$("#content").append(text);
$("#content").append(alert);
}
if(type == "rename") {
$("#content").append(rename);
$("#content").append(type_file);
}
$("#ok").click(function() {
$("div").remove("#alert");
});
$(".rename_it").click(function() {
$("div").remove("#alert");
});
$("#cancle").click(function() {
$("div").remove("#alert");
});
}
I would like the if statement to differentiate between whether the #ok div was clicked or the #cancel div was clicked but I have no idea where to start. Any ideas?
You can use confirm instead:
document.getElementById("prompt").onclick=function(){
if(confirm("Do you want to delete item?")){
// Delete
document.getElementById("status").innerHTML = "deleted";
}else{
// Don't delete
document.getElementById("status").innerHTML = "spared";
}
}
<button id="prompt">delete item</button>
<div id="status"></div>
It is possible that you are trying to do something like this
if( confirm("Do you want to delete this")){
//delete
}else{
// do not delete
}
In raw JavaScript your code might look something like:
//<![CDATA[
var pre = onload;
onload = function(){
if(pre)pre(); // if previous onload run here using this type of Event handler
var doc = document, bod = doc.body;
function E(id){
return doc.getElementById(id);
}
var ok = E('ok');
ok.onclick = function(){
console.log('ok was clicked');
}
// another way to use E
E('cancel').onclick = function(){
console.log('cancel was clicked');
}
}
//]]>
First you need event listeners on each element. So you can use something like
var element0 = document.getElementById(divID);
element0.addEventListener('click', funcDivClicked(element0));
To put a click event listener on all of them with a loop, see here:
Simple way to get element by id within a div tag?
I suggest using window.confirm instead of alert:
http://www.w3schools.com/js/js_popup.asp
function funcDivClicked(el){
var cBox = confirm("Delete "+el.getAttribute("id")+"?");
var strAction;
if (cBox == true) {
strAction = "You pressed OK";
//deletes the element
el.parentNode.removeChild(el);
} else {
strAction = "You pressed Cancel!";
}
console.log(strAction);
}
You could check the target within the event handler:
document.querySelector('body').addEventListener('click', function(e){
if(e.target.id === 'ok'){
alert('ok');
} else if(e.target.id === 'cancel'){
alert('cancel');
}
});
document.querySelector('body').addEventListener('click', function(e){
if(e.target.id === 'ok'){
alert('ok');
} else if(e.target.id === 'cancel'){
alert('cancel');
}
});
div {
color: white;
display: inline-block;
text-align: center;
height: 20px;
width: 100px;
}
div#ok {
background: green;
}
div#cancel {
background: red;
}
<div id="ok">Ok!</div>
<div id="cancel">Cancel!</div>
Sorry about that little bit of confusion. If I had of explained myself properly someone else might have answered but instead i got it. Add paremeter called callback and simply return callback(true); when the ok button is clicked and then my USB stopped working....

Adding links to jQuery tabs

I'm working on a project for my JavaScript class, and I don't know how to edit this jQuery where when you select a tab, it will bring you to a new page. I try adding "a href" to the body, but it doesn't look right. Is there a piece of code I have to enter in the jQuery so when you choose "About" that it will bring you to the actual page? Here's the code:
jQuery
function handleEvent(e) {
var el = $(e.target);
if (e.type == "mouseover" || e.type == "mouseout") {
if (el.hasClass("tabStrip-tab") && !el.hasClass("tabStrip-tab-click")) {
el.toggleClass("tabStrip-tab-hover");
}
}
if (e.type == "click") {
if (el.hasClass("tabStrip-tab-hover")) {
var id = e.target.id;
var num = id.substr(id.lastIndexOf("-") + 1);
if (currentNum != num) {
deactivateTab();
el.toggleClass("tabStrip-tab-hover")
.toggleClass("tabStrip-tab-click");
showDescription(num);
currentNum = num;
}
}
}
}
function deactivateTab() {
var descEl = $("#tabStrip-desc-" + currentNum);
if (descEl.length > 0) {
descEl.remove();
$("#tabStrip-tab-" + currentNum).toggleClass("tabStrip-tab-click");
}
}
$(document).bind("click mouseover mouseout", handleEvent);
HTML
<div class="tabStrip">
<div id="tabStrip-tab-1" class="tabStrip-tab">Home</div>
<div id="tabStrip-tab-2" class="tabStrip-tab">About</div>
<div id="tabStrip-tab-3" class="tabStrip-tab">Contact</div>
<div id="tabStrip-tab-3" class="tabStrip-tab">Gallery</div>
</div>
add this to your handler if you need a new page..
window.open('url', 'window name', 'window settings');
or this if you want to redirect the actual view
window.location.href('url');
furthermore this should be a better choice:
$('div[id^=tabStrip-tab]').bind("click mouseover mouseout", handleEvent);
now only the 'tabStrip-*' id´s will trigger the events/handler
The best solution for your problem is to put hidden div with content for every tab you have.
All you have to do is display the current div depending which tag is selected. The another solution is using ajax and then you have a template for the content and you fill the template with the data you have received.

Categories

Resources