I have an array in js, and want user to check if his product number exist in array. Code is:
var arr = ['3bktzgo4',
'2ltold4k',
'l4u93l4r'];
function check() {
var input = document.getElementById("Input").value;
for (i = 0; i < arr.length; i++) {
if (arr[i] == input) {
alert("congratulations! Product code found! Your product is original!");
return;
}
}
alert("Product code not found! Your product is counterfeit!");
};
<div>
<button onclick="beginhere()">Search</button>
<input id='Input'>
</div>
<html !DOCTYPE html>
<head>
</head>
<body>
<script>
var arr = ['3bktzgo4',
'2ltold4k',
'l4u93l4r'];
function check() {
var productNumber = document.getElementById("productNumberId").value;
console.log(productNumber);
if(arr.indexOf(productNumber) != -1)
return alert("congratulations! Product code found! Your product is original!");
return alert("Product code not found! Your product is counterfeit!");
};
</script>
<div>
<button onclick="check()">Search</button>
<input id='productNumberId'>
</div>
</body>
</html>
I have created this snippet and would like you to know what mistakes or changes you need to make in your code.
Do not use words like "input" for variable names or ids, use words that can describe the value it stores.
The "check" function was never called and it should have replaced the "beginhere" function since this function was never defined.
You did not enclose your javascript code inside the <script> tag (read more about the important tags in HTML).
Read about the useful functions in javascript like "indexOf", "splice", "push", "pop", etc that can help reduce your code or/and complexity.
Related
I'm working on a project for a friend and he wants a pure walk cycle with only HTML/JS (no CSS). So I've tried to work it out but the image only shows up on the webpage.
It doesn't move when I press any buttons or anything at all.
Please show me where I went wrong. I'm used to using HTML and CSS but this is my first JS so I don't know many terms.
How it appears in the website:
My code (HTML + JS):
<!DOCTYPE html>
<html>
<head>
<title>Javascript Animation</title>
<script language="Javascript">
<!--
var walker = new Array(6);
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5) curWalker == 0;
else ++curWalker;
document.animation.src = walker[curWalker].src;
}
-->
</script>
</head>
<body>
<p><img src="walk1.png" name="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval('marathon(),100);">
<input type="button" name="stop" value="stop" onclick="clearsetInterval(startwalking);">
</form>
</body>
</html>
Here it is how I did it get to work (I had to build my simple images with Paint in order to use them in the animation):
<html>
<head>
<title>Javascript Animation</title>
</head>
<body>
<p><img src="walker1.png" id="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval(marathon,100);">
<input type="button" name="stop" value="stop" onclick="clearInterval(startWalking);">
</form>
<script>
var walker = [];
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5)
curWalker = 0;
else
++curWalker;
document.getElementById("animation").src = walker[curWalker].src;
}
</script>
</body>
</html>
I had to correct several typos/mistakes:
Put the JS just before the </body> closing tag
The first paramether of setInterval() must be a function name, so it must be marathon (you had 'marathon(); note that leading single quote)
In order to get the image to be substituted it is better to access the element though Id instead of name attribute. So I changed the image to <img src="walker1.png" id="animation"> (animation is now the Id) and accessed it through document.getElementById("animation")
Now the animation starts... but stops to the last image instead of restarting to the first.
That was because you used to check the curWalker variable instead of performing an assignment: I put curWalker = 0; instead of curWalker == 0;
Almost there. The loop is complete, but the stop button doesn't work. Two typos are preventing this to work:
clearsetInterval doesn't exist. The function to be called is clearInterval
Javascript is a case sensitive language. You use startwalking variable as a parameter, but the correct variable name is startWalking. So you have to correct the onclick event writing clearInterval(startWalking); instead of clearsetInterval(startwalking);
Your animation is now complete.
Note: as correctly noted by #Mike 'Pomax' Kamermans, nowadays you can avoid the use of onclick as you can attach events to the document (such as "click") by using document.addEventListener.
I am trying to capture time from a stopwatch within a browser and display the times (laps) below. To do this, I am intending to create an unordered list from an array within a JavaScript file.
Here is the JS:
laps = []:
function show() {
$time = document.getElementById('time');
document.getElementById("capture").setAttribute("disabled","disabled"); // disable capture button until start
update();
}
function update() {
$time.innerHTML = formatTime(time());
displayLaps();
}
function displayLaps() {
if (laps == "" || laps.length == 0) {
return false; // stop the function if the value is empty
}
var inner = `Lap ${lap_count} :${formatTime(laps[lap_count-1])}`;
document.getElementById("laps").innerHTML += '<li>' + inner + '</li>';
}
And the associated html:
<!doctype html>
<html lang="en">
<head>
</head>
<body onload="show()">
<div>Time: <span id="time"></span></div>
<button onclick="onStart()" id="start" style="width:150px">Start</button>
<button id="capture" style="width:150px">Capture</button>
<div id="laps"><ul></ul></div>
<script src=".\stopwatch.js"> </script>
</body>
</html>
I am getting peculiar behaviour though. It seems that the += operator on the last line of code keeps adding rows that display the last array vaue (see below), whereas replacing this with a simple = operator just creates a single row that is then replaced every time a new lap value is added to the array.
I'm obviously missing something, but would appreciate some guidance, if possible.
Many thanks!
How can I stop this Javascript code from passing the last number of the iteration to the delete function?
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="lista"></div>
</body>
<script type="application/javascript">
var dados = ['vassoura','lixo','papel'];
function deletar(elemento){
console.log(elemento);
}
function listar(){
var div = document.getElementById('lista');
for(i in dados){
campo = document.createElement("output");
button = document.createElement("button");
button.addEventListener("click",()=>{
deletar(dados[i]);
});
button.innerHTML="deletar";
div.appendChild(campo);
div.appendChild(button);
console.log(i);
campo.value = dados[i]+" ";
console.log(dados[i]);
}
}
listar();
</script>
it is passing the last number corresponding to iteration because when I click on the button the iteration has already been made and finished
Looks like here is a common mistake with a variable scope.
Simplest way is to either use closure or replace for(i in dados) at least with for(let i in dados)
First ,get the length of dados. and check when i = dados_length (last element) then skip that code which you want to skip.
I'm trying to create an HTML page that allows the user to input integers into a stored array using a button and then search that array for the inputted integers using another button. I am very confused and new to coding so any help would be much appreciated!
Try this out
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="data">[]</p>
<input id="inputNumber" value="0"/> <button id="pushBtn" onclick="push()">PUSH</button>
<input id="findNumber" value="0"/> <button id="pushBtn" onclick="find()">FIND</button>
<script>
var data = [];
function push(e) {
var toAdd = document.getElementById("inputNumber").value;
data.push(toAdd);
refresh();
}
function find(e) {
var toFind = document.getElementById("findNumber").value;
for(var i=0; i < data.length; i++){
if(data[i]==toFind) return alert("found at "+i);
}
return alert("couldn't find that number");
}
function refresh(){
document.getElementById("data").innerHTML = data;
}
</script>
</body>
</html>
Basically, I'm just using using the buttons to call the functions within the script that handles insertion and query for me. Additionally a refresh function is there to refresh the newly added data
So i have a array of objects, I want to add new object into it. so I am using following code here is my code. I have seen other questions asked on the same topic but still I am not able to add my new object that i am fetching using jquery into my list. I am doing silly mistake please find it for me. Thanks
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<input placeholder="name" type="text" id="name"></br>
<input placeholder="rno" type="text" id="rollno"></br>
<input type="submit" value="Add Roll" id="add" >
<script type="text/javascript">
$(document).ready(function(){
console.log("loaded");
var list=[
{name:"sud",rno:1},
{name:"diya",rno:2},
{name:"sakshi",rno:3}
];
for(i=0;i<list.length;i++){
console.log("old list is"+list[i].rno+"\t"+
list[i].name);
};
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
//here i want to add rno and name to my list
for(i=0;i<list.length;i++){
console.log("new list is"+list[i].rno+"\t"+
list[i].name);
};
});
});
</script>
</body>
</html>
Array#push adds items to the end of an array. eg: arr.push("test");
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
// Use Array#push to add an item to an array.
// No need to use `new` when using the `{}` syntax for object creation.
list.push({name:"sudarshan",rno:"33"});
// Just a tip. You should use `var i = 0;` instead of `i = 0;` to keep the `i` variable out of the global scope.
for(var i = 0; i < list.length; i++){
console.log("new list is"+list[i].rno+"\t"+list[i].name);
};
});
to append to an array you can use push
list.push({name:"sudarshan",rno:"33"});
or just
list[list.length] = {name:"sudarshan",rno:"33"};
which is the same as above.