How to change text in HTML by clicking - javascript

function diffSign(div) {
var sign = document.getElementById(div.id);
if (XXXXX) {
XXXXX
} else {
XXXX
}
}
<div data-toggle="collapse" data-target="#demo#(i.tostring)" id="Sign#(i.ToString)" onclick=diffSign(this)>+</div>
I want to change + sign to - and can change back!
THX

function diffSign(div) {
var sign = document.getElementById(div.id);
sign.innerText = (sign.innerText === "+") ? "-" : "+";
}
but if you pass in the div, why would you search it again?
function diffSign(div) {
div.innerText = (div.innerText === "+") ? "-" : "+";
}
would work too if the div parameter is the real div...
make sure this div has nothing other than the + or the - signs..
cheers.

The function's div Argument is already representing this by reference.
jsBin demo
function diffSign(div){
if (div.innerHTML === '+') { // If has "+"
div.innerHTML = '-'; // Set as "-"
} else { // else? well...
div.innerHTML = '+';
}
}
Or you can do it also like: jsBin demo using bitwise XOR (^=) and Ternary Operator(?:)
function diffSign(div) {
div.innerHTML = (div.io^=1) ? '-' : '+' ;
}
https://stackoverflow.com/a/22061240/383904

function diffSign(div) {
var sign = document.getElementById(div.id);
if (sign.innerHTML == '+') {
sign.innerHTML = '-';
} else {
sign.innerHTML = '+';
}
}
<div data-toggle="collapse" data-target="#demo#(i.tostring)" id="Sign#(i.ToString)" onclick=diffSign(this)>+</div>

Since div is the actual DOM element and a javascript object you can use it directly and add properties to it dynamically.
function diffSign(div) {
//Add a new property to maintain the element's state on the first call, toggle it on subsequent calls
div.useMinus = !div.useMinus;
//set the text based on the current state.
div.innerHTML = (div.useMinus ? '-' : '+');
}

you can use document.getElementById.innerHTML = "your new text"........ to change text.

Related

While loop to hide div elements

I am trying to create searchable content with the help of some JS yet am having trouble hiding the content when there is no input in the search field.
Here is my script:
var $searchContainer = $("#search");
var $contentBoxes = $searchContainer.find(".content");
var $searchInput = $searchContainer.find("#search-input");
var $searchBtn = $searchContainer.find("#search-btn");
$searchBtn.on("click", searchContent);
$searchInput.on("input", searchContent);
while($searchInput == null) {
for($contentBoxes) {
hide();
}
}
function searchContent(){
var userInput;
//Check if call comes from button or input change
if($(this).is(":button")){
userInput = $(this).siblings("input").val();
} else {
userInput = $(this).val();
}
//make the input all lower case to make it compatible for searching
userInput = userInput.toLowerCase();
//Loop through all the content to find matches to the user input
$contentBoxes.each(function(){
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if(!searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}
});
};
I understand a while loop could have a condition where if userInput is equal to null it would loop through each content box and hide the element.
Something like this maybe?
while($searchInput == null) {
$contentBoxes.each(function(){
hide();
}
}
Any help would be greatly appreciated.
You would need to update your userInput variable every cycle of the loop because the userInput value never gets updated. Nonetheless this not a good way to do this because you will block your entire application.
There is no need for a loop, just use an if statement. Also, because this function gets executed when the value of the input is changed, there is no need to use this.
You could put this block of code beneath your $contentBoxes.each function:
$contentBoxes.each(function(){
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if(!searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}
});
if (userInput === null) {
$contentBoxes.each(function(){
$(this).hide();
});
}
I think it will be work like this. You just check if search input !== null and dont hide any content in this case
if($searchInput != null && !searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}

Change text on button when clicked with 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.

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('');
}
}

How to find if parent Node has no Children

I'm not sure if I am using the correct syntax, as my ELSEIF doesn't appear to be firing. Is this the correct syntax, or what is the best way to test it?
<script>
function OnLoad() {
var links = document.getElementById("<%=TreeView1.ClientID %>").getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].setAttribute("href", "javascript:NodeClick(\"" + links[i].id + "\", \"" + links[i].getAttribute("href") + "\")");
}
}
window.onload = OnLoad;
function NodeClick(id, attribute) {
var nodeLink = document.getElementById(id);
if (nodeLink.hasChildNodes)
{
eval(attribute);
}
else if (nodeLink.hasChildNodes == false)
{
alert(nodeLink.innerHTML + " clicked");
window.open("../NewFolder/addNewProduct.aspx");
}
else
{
return;
}
}
</script>
If I move the alert/open window by itself it works, so I feel that the problem lies in this line:
else if (nodeLink.hasChildNodes == false)
The syntax for hasChildNodes says it is a method .i reckon changing it to a method should solve the problem
It should be noted, hasChiildNodes() considers whitespace and comments. From the MDN docs
childNodes also includes e.g. text nodes and comments. To skip them, use ParentNode.children instead.
i.e
if (nodeLink.hasChildNodes())
{
eval(attribute);
}
else if (!nodeLink.hasChildNodes())
{
alert(nodeLink.innerHTML + " clicked");
window.open("../NewFolder/addNewProduct.aspx");
}
else
{
return;
}
Check the two fiddles to get the difference
hasChildNodes fiddle .
ParentNode.Children fiddle
parentNode.children.length;
if it is 0, then no child node at all
For example
console.log(document.getElementById('d1').children.length); //->0
console.log(document.getElementById('d2').children.length); //->3
<div id="d1"></div>
<div id="d2">
<div></div>
<div></div>
<div></div>
</div>

Storing document.getElementById in a variable?

I have this script that is supposed to change the text of the button when the button is clicked.
<body>
<button onclick="toggleText(this);" id="id">Edit</button>
</body>
function toggleText(element){
var text = document.getElementById(element.id).textContent;
if (text == 'Edit') {
text = 'Done';
} else {
text = 'Edit';
}
}
But it doesn't work. It only works when you put document.getElementById(element.id).textContent directly into the if statements.
How do I get the variable to store properly?
Since you already get the element, you don't need to get it again. You can just use element.
But the reason why you can't change it is that you're only changing the variable that contains the text. It does not point to the element's properties. You need to use this:
function toggleText(element){
var text = element.textContent;
if (text == 'Edit') {
element.textContent = 'Done';
} else {
element.textContent = 'Edit';
}
}
When you access document.getElementById(element.id).textContent you get the value of it, not the reference. So changes to it won't affect the element.
But when you assign element to variable, it gets reference to it.
var element = document.getElementById(element.id);
if (element.textContent == 'Edit') {
element.textContent = 'Done';
} else {
element.textContent = 'Edit';
}
Just use:
index.js
var mainText = document.getElementById("mainText").value;
document.write(mainText);
index.html
<textarea id="mainText"></textarea>
As tymeJV commented, you can store by reference the element you get by id. Its property is stored by value. Instead store the element in a variable and access its property from the variable.
var text = document.getElementById(element.id);
if (text.textContent == 'Edit') {
text.textContent = 'Done';
} else {
text.textContent = 'Edit';
}
Is jquery an option ?
I used to do something like :
var a = $('#theid');
A.something

Categories

Resources