I am fairly new to JavaScript,
I have ben working on a simple if else script to change the color of at button, depending on the status of a variable that I get from a plc (Siemens S7-1200).
The script is working fine and the color of the button is changing.
But I have 10 buttons that I want to run this script on.
Is it possible to “reuse” the script so that I don’t have to copy the script and change the variables for every button
T
<script>
var tag = ':="web_DB".outtag1:'
var button = "button1"
window.onload = function() {
if (tag == 1) {
document.getElementById(button).style.backgroundColor = 'green';
} else{
document.getElementById(button).style.backgroundColor = 'red';
}
}
</script>
<form>
<input type="submit" id="button1" value="button">
<input type="hidden" name='"web_DB".intag1' value ="1">
</form>
It's hard to be sure since you haven't posted all your code and what you have posted doesn't actually work but I think you're looking for something like this.
const tags = [
':="web_DB".outtag1:',
':="web_DB".outtag2:',
//...
':="web_DB".outtag10:'
];
window.onload = function() {
for (let i = 0; i <= 9; i++) {
const color = (tags[i] == 1) ? 'green' : 'red';
document.getElementById('button' + (i+1)).style.backgroundColor = color;
}
}
Related
I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.
var form = document.getElementById("myForm");
form.elements[i].value
Those lines of code is what I tried but it doesn't seem to work.
Edit:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm").elements;
for(var i = 0; i < 1 ; i++){
var id = form.elements[i].id;
sessionStorage.setItem(id,"false");
}
localStorage.setItem("run", true);
}
}
So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.
Edit2:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm");
var tot = document.getElementById("myForm").length;
for(var i = 0; i < tot ; i++){
sessionStorage.setItem(form.elements[i].id,"false");
}
localStorage.setItem("run", true);
}
}
This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.
function loader(){
var form = document.getElementById("myForm");
var tot = 5;
for(var i = 0; i < 5 ; i++){
if(sessionStorage.getItem(form.elements[i].id) === "true"){
document.getElementById(form.elements[i].id).style.backgroundColor = "green";
return ;
}else{
document.getElementById(form.elements[i].id).style.backgroundColor = "red";
return false;
}
}
}
Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.
It's available via the id property on the element:
var id = form.elements[i].id;
More on MDN and in the spec.
Live Example:
var form = document.getElementById("myForm");
console.log("The id is: " + form.elements[0].id);
<form id="myForm">
<input type="text" id="theText">
</form>
You're already storing all the elements in the form so it must be :
var form = document.getElementById("myForm").elements;
var id = form[i].id;
Or remove the elements part from the form variable like :
var form = document.getElementById("myForm");
var id = form.elements[i].id;
Im new in programming and im trying to make my first project in js - hangman game (https://en.wikipedia.org/wiki/Hangman_(game))
So basically i got two buttons in my HTML file, lets say its look like this:
<button id="movies">Movies</button>
<button id="animals">Animals</button>
i want this buttons to be responsible for changing categories in my game. In js i got:
var movies = ["Shawshank Redemption","Alice in a Wonderland"];
var animals = ["Blue whale","Raspberry Crazy-Ant"];
var choice = 1;
if (choice === 0){
var pwdDraw = Math.floor(Math.random() * movies.length);
var pwd = movies[pwdDraw];
pwd = pwd.toUpperCase();
document.write(pwd);
}
else if (choice === 1){
var pwdDraw = Math.floor(Math.random() * animals.length);
var pwd = animals[pwdDraw];
pwd = pwd.toUpperCase();
document.write(pwd);
}
and this is the place where im stucked, i dont know how change var choice by clicking button (also i want to reload page after click). Im at the beginning on my way with js, so i want this code to be pure js, not any customized library.
<button onclick="changeCategory(number)">Click me</button>
<script>
function changeCategory() {
//[..]
}
</script>
https://www.w3schools.com/jsref/event_onclick.asp
thanks a lot for feedback, but i still have some troubles of implementing this js changes, When im doing it on new file with only category changer everything is running smooth. But when i try to add this to my existing code its doesnt work at all. Here you got my code:
codepen.io/iSanox/project/editor/DGpRrY/
First of all, don't put those <br> in JS code like that.
If you want to try to get the choice by clicking on the button then here's how you can do it:
HTML
<button id="movies" class="choice" value="0">Movies</button>
<br/>
<button id="animals" class="choice" value="1">Animals</button>
JS
var buttons = document.querySelectorAll(".choice");
function doSomething(e)
{
// You can get choice value by either doing:
var choice = e.target.value;
// OR
var choice = this.value;
// Continue your work here
}
for(var i = 0; i < buttons.length; i++)
{
buttons[i].addEventListener("click", doSomething);
}
Feel free to ask any questions.
Simply you can use onclick event. After some changes your code should look like this.
var movies = ["Shawshank Redemption", "Alice in a Wonderland"];
var animals = ["Blue whale", "Raspberry Crazy-Ant"];
var catname = document.getElementById('cat-name');
function selectCategory(choice) {
var pwd, pwdDraw;
if (choice === 0) {
pwdDraw = Math.floor(Math.random() * movies.length);
pwd = movies[pwdDraw];
} else if (choice === 1) {
pwdDraw = Math.floor(Math.random() * animals.length);
pwd = animals[pwdDraw];
}
pwd = pwd.toUpperCase();
catname.innerText = pwd;
}
<p>Choose Category</p>
<button id="movies" onclick="selectCategory(0)">Movies</button>
<button id="animals" onclick="selectCategory(1)">Animals</button>
<div id="cat-name"></div>
Even better with Object and Arrays
var categories = {
movies: ["Shawshank Redemption", "Alice in a Wonderland"],
animals: ["Blue whale", "Raspberry Crazy-Ant"]
};
var catname = document.getElementById('cat-name');
function selectCategory(choice) {
var pwdDraw = Math.floor(Math.random() * categories[choice].length);
var pwd = categories[choice][pwdDraw];
pwd = pwd.toUpperCase();
catname.innerText = pwd;
}
<p>Choose Category</p>
<button id="movies" onclick="selectCategory('movies')">Movies</button>
<button id="animals" onclick="selectCategory('animals')">Animals</button>
<div id="cat-name"></div>
I am making a To-do list, where I want to be able to add new tasks, and delete tasks that are checked off. However, it seems my function just deletes all tasks, not just the ones that are checked off. Neither does it seem to allow new tasks to be added.
html:
<h1 id="title"> To-do list</h1>
<div id="task_area">
</div>
<input type="text" id="putin"></input>
<button id="add">add</button>
javascript:
<button id="clear">Clear completed tasks</button>
var tasks = document.getElementById("task_area")
var new_task = document.getElementById("add")
var clear = document.getElementById("clear")
new_task.addEventListener("click", function() {
var putin = document.getElementById("putin")
var input = document.createElement('input')
input.type = "checkbox"
var label = document.createElement('label')
label.appendChild(document.createTextNode(putin.value))
task_area.appendChild(input)
task_area.appendChild(label)
})
clear.addEventListener("click", function() {
for (i = 0; i < task_area.children.length; i++) {
if (task_area.children[i].checked === true) {
task_area.remove(tasks.children[i])
}
}
})
jsfiddle: https://jsfiddle.net/4coxL3um/
.remove removes the element you are calling it from, and doesn't take an argument for what to remove. The following:
task_area.remove(tasks.children[i])
should be
tasks.children[i].remove()
EDIT: As Mononess commented below, this will only remove the checkboxes and not the labels. While you could delete both using Jayesh Goyani's answer below, it's probably better that each input/label pair be wrapped in a single div or span for easier management.
You could try adding an event listener to each child of task_area that calls the below function. Haven't gotten a chance to test it out, and may not fulfill all of your requirements, but should get the job done.
function removeClicked() {
this.parentNode.removeChild(this);
}
Please try with the below code snippet. Below code will help you to remove selected checkbox with label.
<body>
<h1 id="title">To-do list</h1>
<div id="task_area">
</div>
<input type="text" id="putin" />
<button id="add">add</button>
<button id="clear">Clear completed tasks</button>
<script>
var tasks = document.getElementById("task_area")
var new_task = document.getElementById("add")
var clear = document.getElementById("clear")
new_task.addEventListener("click", function () {
var putin = document.getElementById("putin")
var input = document.createElement('input')
input.type = "checkbox"
var label = document.createElement('label')
label.appendChild(document.createTextNode(putin.value))
task_area.appendChild(input)
task_area.appendChild(label)
//document.getElementById("task_area").innerHTML = putin.value
})
clear.addEventListener("click", function () {
for (i = 0; i < task_area.children.length; i++) {
if (task_area.children[i].checked === true) {
tasks.children[i].nextSibling.remove();
tasks.children[i].remove();
}
}
})
</script>
</body>
Please let me know if any concern.
I managed to save the text that is in the input field but the problem is that i do not know how to save the button. The buttons turn white when i click on them and the price of that seat will be visible in the input field. The price saves but the button does not stay white.
<script>
function changeBlue(element) {
var backgroundColor = element.style.background;
if (backgroundColor == "white") {
element.style.background = "blue";
add(-7.5)
} else {
element.style.background = "white";
add(7.5)
}
}
function add(val) {
var counter = document.getElementById('testInput').value;
var b = parseFloat(counter,10) + val;
if (b < 0) {
b = 0;
}
document.getElementById('testInput').value = b;
return b;
}
function save(){
var fieldValue = document.getElementById("testInput").value;
localStorage.setItem("text", fieldValue)
var buttonStorage = document.getElementsByClass("blauw").value;
localStorage.setItem("button", buttonStorage)
}
function load(){
var storedValue = localStorage.getItem("text");
if(storedValue){
document.getElementById("testInput").value = storedValue;
}
var storedButton = localStorage.getItem("button");
if(storedButton){
document.getElementsByClass("blauw").value = storedButton;
}
}
</script>
<body onload="load()">
<input type="text" id="testInput"/>
<input type="button" id="testButton" value="Save" onclick="save()"/>
<input class="blauw" type="button" id="testButton2" value="click me to turn white"
style="background-color:blue" onclick="changeBlue(this)">
<input class="blauw" type="button" id="testButton2" value="click me to turn white"style="background-color:blue" onclick="changeBlue(this)">
</body>
i made a small sample of what i want to do. And i do not want to use the Id's of the buttons because i have like 500 of them in a table.
That's because getElementsByClass (it's getElementsByClassName btw) returns a node list of all the elements with that class.
To make it work, you need to go through all the items in the list, using a for-loop, and set the value of each individual element to the localStorage-value.
See these links for more information:
Link 1
Link 2
Very small mockup to give you an idea:
(In the JS, I put in comments the lines of code you would be using for your situation.)
function changeValues() {
var list = document.getElementsByClassName("child"); //var list = document.getElementsByClassName("blauw");
for (var i=0; i<list.length; i++) {
list[i].innerHTML = "Milk"; //list[i].value = storedButton;
}
}
<ul class="example">
<li class="child">Coffee</li>
<li class="child">Tea</li>
</ul>
<p>Click the button to change the text of the first list item (index 0).</p>
<button onclick="changeValues()">Try it</button>
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
But in this task, firstly I try to catch that input in javascript file, and I am failing in the same. Can you tell me for this, which command will I use ?
Till now my work is :-
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT FILE:-
function addString(x) {
var val = x.name.value;
//var s = document.getElementById("name_id").getElementValue;//x.name.value;
alert(val);
}
EDITED
My New JAVASCRIPT FILE IS :-
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the string, but unable to show on the web page.
See this fiddle: http://jsfiddle.net/MjyRt/
Javascript was almost right
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
alert(s);
}
Try to use jQuery (simpler)
function addString() {
var s = $('#name_id').val();//value of input;
$('#list').append(s+"<br/>");//list with entries
}
<div id='list'>
</div>