Hiding class based on radio selection - javascript

I am trying to hide a class based on the name (etc. "hiddenA"), I previously used ID but I want to hide more than 1 class so ID is no longer an option. This is what I have currently:
function onChangePackage() {
const nodes = document.getElementsByClassName('Package');
var selectedValue;
// Get selected radio
for (var i = 0, length = nodes.length; i < length; i++) {
if (nodes[i].checked) {
selectedValue = nodes[i].value;
break;
}
}
// Showing all nodes first
const nodePostFix = ['A', 'B', 'C'];
nodePostFix.forEach(node => {
const currentElement = elementsToHide.item(i);
if (currentElement.hasClass('hidden' + selectedValue)) {
currentElement.style.display = 'none';
} else {
currentElement.style.display = 'block';
}
});
}
I feel like I am over complicating my code as there surely must be a simpler way.

Try this code here. You will just have to change the button to a radio button. Also use jquery. I think this is what you wanted.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1, #p2").toggle();
});
});
</script>
</head>
<body>
<button>Hide / Show</button>
<p id="p1">I have a class of p1</p>
<p id="p2"s>I have a class of p2</p>
<p id="p1">I have a class of p1</p>
</body>
</html>

Related

Using for loop for delete button

Good evening guys. I am learning javascript. After learning some basics, I decided to make TODO LIST and got the todo list code from the internet. But I have a question on my mind. My code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div>
<h2>ToDo</h2>
<input type="text" id="inputum" />
<button onclick="fonksiyonum()">Ekle</button>
</div>
<ul id="yeniUl"></ul>
<script>
function fonksiyonum() {
var liEkle = document.createElement('li');
var inputtaYazanlar = document.getElementById('inputum').value;
var textim = document.createTextNode(inputtaYazanlar);
liEkle.appendChild(textim);
document.getElementById('yeniUl').appendChild(liEkle);
document.getElementById('inputum').value = '';
var button = document.createElement('BUTTON');
var hiks = document.createTextNode('\u00D7');
button.appendChild(hiks);
liEkle.appendChild(button);
button.className = 'close';
var close = document.getElementsByClassName('close');
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = 'none';
};
}
}
</script>
</body>
</html>
As I understand it, for (i = 0; i < close.length; i++) is used to get the button.close[i].onclick = function () shows the function that will run when the button is pressed. But why close[i] what does the letter 'i' mean here? After that there is var div = this.parentElement. I don't understand this.parentElement. I would be happy if someone could explain the concept of parent element to me.
close.length is actually List/Array of all the Buttons. You can tell by the Elements in getElementsByClassName.
So you are looping through all the Close Buttons and adding an onclick() method to each.
list = [btn0, btn1]
list.length // length = 2
// for i=0; i<list.length; i++
// 1st pass, i == 0:
list[0] // btn0
// 2st pass, i == 1:
list[1] // btn1
// 3rd pass, i == 2
// i is not less than length, 2, end.
For the parentElement I always look at the tabs, Just go 1 left tab over and up; that's the parent! That's why formatting is important, to make this easy!
<div> <!-- <- Parent -->
<h2>ToDo</h2>
<input type="text" id="inputum" />
<button onclick="fonksiyonum()">Ekle</button> <!-- <- Button --->
</div>

Click event only works on the second click

i hope you guys fine, well..
I'm doing a To Do List, and there is a problem in my code, which I've been trying to solve for a few days, and no effective results was made..
If you guys test in the snippet with me, i am sure, that will be more
clear to understand.
When i click in some list element, my javascript should change or add the className, and add a class call 'selected'.
because, when i will click in the remove button, they will delete all elements with 'selected' classList in the list. (as you can see in the code)
But the className a not being add to the tag in the first click, just works if i click in the element one more time.
i simplified my code, just to show the real problem:
Link to jsfiddle : https://jsfiddle.net/myqrzcs2/
const textoTarefa = document.getElementById('texto-tarefa');
const criarTarefa = document.getElementById('criar-tarefa');
const listaTarefas = document.getElementById('lista-tarefas');
criarTarefa.onclick = function click() {
const lista = document.createElement('li');
lista.className = 'lista';
lista.id = 'lista';
lista.tabIndex = '0';
lista.innerHTML = textoTarefa.value;
listaTarefas.appendChild(lista);
document.body.appendChild(listaTarefas);
textoTarefa.value = '';
};
const completedLine = document.querySelector('ol');
function umClick(event) {
if (event.target.tagName === 'LI') {
const listas = document.querySelectorAll('.lista');
listas.forEach((i) => {
i.addEventListener('click', function semNomeDois() {
listas.forEach((j) => j.classList.remove('selected'));
this.classList.add('selected');
});
});
}
}
completedLine.addEventListener('click', umClick);
function removeSelected() {
// teste
const listaSelected = document.querySelectorAll('.selected');
for (let i = 0; i < listaSelected.length; i += 1) {
listaSelected[i].remove();
}
}
.lista:focus {
background: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h1>My List</h1>
</header>
<input id='texto-tarefa' type="text" />
<button id='criar-tarefa' type="submit" onClick='click()'>Add</button>
<ol id='lista-tarefas'>
</ol>
<button id='remover-selecionado' type="submit" onClick='removeSelected()'>Remove Selected (Only One)</button>
<script src="script.js"></script>
</body>
</html>
But how can i make the class be add, just in the first click, not in the second?
I think you got off on the wrong foot in programming this.
Here is the way I use, may it inspire you.
const
textoTarefa = document.getElementById('texto-tarefa')
, criarTarefa = document.getElementById('criar-tarefa')
, removerSelec = document.getElementById('remover-selecionado')
, listaTarefas = document.getElementById('lista-tarefas')
;
var li_selected = null
;
textoTarefa.oninput = () =>
{
criarTarefa.disabled = (textoTarefa.value.trim().length ===0 )
}
criarTarefa.onclick = () =>
{
listaTarefas.appendChild( document.createElement('li')).textContent = textoTarefa.value.trim()
textoTarefa.value = ''
textoTarefa.focus()
criarTarefa.disabled = true
}
listaTarefas.onclick = ({target}) =>
{
if (!target.matches('li')) return
if (!!li_selected && li_selected !== target ) li_selected.classList.remove('listaSelect')
li_selected = target.classList.toggle('listaSelect') ? target : null
removerSelec.disabled = !li_selected
}
removerSelec.onclick = () =>
{
listaTarefas.removeChild(li_selected)
li_selected = null
removerSelec.disabled = true
}
.listaSelect {
background: #ff0000c4;
}
ol#lista-tarefas {
cursor : pointer
}
<input id='texto-tarefa' type="text" value="">
<button id='criar-tarefa' disabled>Add</button>
<button id='remover-selecionado' disabled>Remove Selected</button>
<ol id='lista-tarefas'></ol>
You were unnecessarily adding an event listener to each item in the list.
You can check the updated fiddle here: https://jsfiddle.net/msa9v2nf/
Since you're already checking which target element is clicked, there isn't any need to add an individual listener to each child item in the list.
I updated the umClick function:
function umClick(event) {
if (event.target.tagName === 'LI') {
const listas = document.querySelectorAll('.lista');
listas.forEach((i) => {
listas.forEach((j) => j.classList.remove('selected'));
event.target.classList.add('selected');
});
}
}
The problem is you call the function umClick and call the function to add .selected within a click event in the same function umClick.
What happens is the click event completedLine.addEventListener('click', umClick); happens before the i.addEventListener('click', function semNomeDois() event. This is why you need a first click on the ol tag for only the first time.
To fixes this you have multiple options:
instead of calling click event on ol tag you can call mousedown which happens before click event.
Calling a click event on the li elements on creation, which needs a new function.
Depending on Vektor's answer, you can remove the unnecessary click event inside the first click event.
Also, I've made the red highlight on the .selected class instead of :focus, just to make it clear when the item is selected.
.selected {
background: red;
}
First Solution
const textoTarefa = document.getElementById('texto-tarefa');
const criarTarefa = document.getElementById('criar-tarefa');
const listaTarefas = document.getElementById('lista-tarefas');
criarTarefa.onclick = function click() {
const lista = document.createElement('li');
lista.className = 'lista';
lista.id = 'lista';
lista.tabIndex = '0';
lista.innerHTML = textoTarefa.value;
listaTarefas.appendChild(lista);
document.body.appendChild(listaTarefas);
textoTarefa.value = '';
};
const completedLine = document.querySelector('ol');
function umClick(event) {
if (event.target.tagName === 'LI') {
const listas = document.querySelectorAll('.lista');
listas.forEach((i) => {
i.addEventListener('click', function semNomeDois() {
listas.forEach((j) =>{
if(j != event.target)
j.classList.remove('selected');
});
this.classList.add('selected');
});
});
}
}
completedLine.addEventListener('mousedown', umClick);
function removeSelected() {
// teste
const listaSelected = document.querySelectorAll('.selected');
for (let i = 0; i < listaSelected.length; i += 1) {
listaSelected[i].remove();
}
}
.selected {
background: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h1>My List</h1>
</header>
<input id='texto-tarefa' type="text" />
<button id='criar-tarefa' type="submit" onClick='click()'>Add</button>
<ol id='lista-tarefas'>
</ol>
<button id='remover-selecionado' type="submit" onClick='removeSelected()'>Remove Selected (Only One)</button>
<script src="script.js"></script>
</body>
</html>
Second Solution
const textoTarefa = document.getElementById('texto-tarefa');
const criarTarefa = document.getElementById('criar-tarefa');
const listaTarefas = document.getElementById('lista-tarefas');
criarTarefa.onclick = function click() {
const lista = document.createElement('li');
lista.className = 'lista';
lista.id = 'lista';
lista.tabIndex = '0';
lista.innerHTML = textoTarefa.value;
listaTarefas.appendChild(lista);
lista.addEventListener('click',function(){
itemClick(this);
});
document.body.appendChild(listaTarefas);
textoTarefa.value = '';
};
function itemClick(item) {
const listas = document.querySelectorAll('.lista');
listas.forEach((j) =>j.classList.remove('selected'));
item.classList.add('selected');
}
function removeSelected() {
// teste
const listaSelected = document.querySelectorAll('.selected');
for (let i = 0; i < listaSelected.length; i += 1) {
listaSelected[i].remove();
}
}
.selected {
background: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h1>My List</h1>
</header>
<input id='texto-tarefa' type="text" />
<button id='criar-tarefa' type="submit" onClick='click()'>Add</button>
<ol id='lista-tarefas'>
</ol>
<button id='remover-selecionado' type="submit" onClick='removeSelected()'>Remove Selected (Only One)</button>
<script src="script.js"></script>
</body>
</html>
I am not fully understand your problem but,
If you want to add the style when selecting a item, just add the style to
.selected
If you want in focus, and remove the class when there is no focus, you may add an eventlistener to control that.

Javascript array change in realtime after button click

i'm making a web application which helps people to seek what disease they have according to the symptoms.
I want to the user to click specific symptom to add in the "u_symptom_i" array and show all of the changed array elements by alert function
However, i cannot see the added element by alert function
<script>
var j = 0;
while(j < escaped_cc.length) {
document.write('<th><button id="symptom_button">' + escaped_cc[j] + '</button></th>');
document.getElementById("symptom_button").value = escaped_cc[j];
j = j + 1;
}
$("button").click(function() {
u_symptom_i.push($(this).val());
alert($(this).val());
});
</script>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<h2>Insert Array</h2>
<input type="text" id="example" name="value">
<button id="button">Add array new item</button>
</body>
<script>
var array=[];
$("#button").click(function() {
var str = $("#example").val();
array.push(str);
alert(array);
});
</script>
</html>
Can you try this code? Adds each new value entered to an array named array and displays the records.

Why my HTML and JavaScript button are not working together?

Hey I am new to coding and I'm working on a new chrome App. So far, I am trying to make a button that counts when you click on it. For some reason it's not working. Here's the HTML:
var button = document.getElementById("button"),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> This is a "Button" (I think) </h1>
<p> (Or is it?) </p>
<button id="button"> Button: 0 </button>
</body>
</html>
You have to wait until the DOM is loaded. Use the window.onload event:
window.onload = function() {
var count = 0;
const button = document.getElementById('button');
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};
};
Edit: I also just noticed you're not including your script in your HTML.
Your missing a variable type on your count.
You want make sure your button has some kind of text inside of it before you actually
start incrementing it.
Lastly you need to get the element from the html with a "document.getElementById("id_goes_in_here")
Try this instead.
document.getElementById("button").innerHTML = ` `; //Make sure to actually pull from your element in the html with this.
let count = 0;
button.innerHTML="Button " + count
button.onclick = function() {
count += 1;
button.innerHTML = "Button: " + count;
};

How to print checked checkbox values?

The html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="scripts.js"></script>
</head>
<body>
<button id = "button1" type="button" onclick="filterValues();">Submit</button>
</body>
</html>
My javascript:
var checkingValues = ["Cat", "Dog", "Horse", "Tree"];
var createCheckboxes;
var saveValues;
document.write("Choose from the options below: </br> </br>");
for (var i = 0; i < checkingValues.length; i++) {
createCheckboxes = document.createElement("INPUT");
var checkbox = createCheckboxes.setAttribute("type", "checkbox");
createCheckboxes.setAttribute("value", checkingValues[i]);
var checkBoxText = document.body.appendChild(createCheckboxes) + document.write(createCheckboxes.value +"</br>");
}
//try to save checked values
if(createCheckboxes.checked){
saveValues = checkbox;
}
function filterValues() {
document.write(saveValues);
}
My idea is to generate a checkbox and print(filter) the selected items from the checkbox by saving the selected items in to a new array and just print them on a cick. I feel i need to make a simple if statement for that but i cant seem to write the values in the global saveValues variable. I know that is not the smartest way to do it but i want to know how to do it. I want to use pure JS.
Thanks.
If you're restricted to pure Javascript, you could always do the following:
var inputs = document.getElementsByTagName('input');
for(var i=0; i < inputs.length; i++){
if(inputs[i].type == 'checkbox' && inputs[i].checked) {
//print
console.log(inputs[i].value);
}
}
That will get all checked checkboxes on the page and print their values. Instead of printing to the console you could do some other logic, or add the checkbox to a second array for later use.
Try this,
function filterValues() {
for (var i = 0; i < checkingValues.length; i++) {
if(createCheckboxes.checked){
saveValues = checkbox;
}
}
document.write(saveValues);
}

Categories

Resources