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.
Related
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!
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
this is shan and i'm a javascript noob and i'm trying to work qa code as an example here. i'm trying to load a small javascript content to a div element but it is not working any help would be great and here is the code.
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext () {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerhtml="adding 1 to 100 gives "+sum;
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
You need to call the function. It's also a good idea to wait until the window is loaded (or you can use some more advanced JS to detect the DOM ready state.):
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext() {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML = "adding 1 to 100 gives "+sum;
}
window.onload = function(){
displaytext();
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
3 problems:
You never actually call the function. It is only declared.
The property is innerHTML not innerhtml. Javascript is case-sensitive.
The script is above an element is is referencing. As scripts are executed as they are found (page construction is paused during execution) the element you are referring to is never found.
Also you declare the loopindex variable twice, which i think will cause a syntax error on ES5 strict.
<html>
<head>
<title>
using d for statement
</title>
</head>
<body>
<div id="targetdiv">
</div>
</body>
<script>
function displaytext () {
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML="adding 1 to 100 gives "+sum;
}
displaytext();
</script>
</html>
I would like to redirect a user to a php page containing a form field after the user has viewed the three numbers after each other. I would like to also pass the index array to a php array for processing and storage.
Here's the code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="">
<meta name="description" content="">
<title>Digit Span Backward</title>
<script src="jquery.min.js" type="text/javascript">
</script>
</head>
<body>
<p>Digit Span Backward - Javascript edition</p>
<script type="text/javascript" language="javascript">
function randomize(number)
{
var index = [];
for (var i = 0; i < number; i++)
{
index.push(Math.floor(Math.random()*10));
}
return index;
}
function showMessage(message)
{
$('p').html(message);
}
var i = 0;
function shuffle(list, i)
{
if (!(i >= 0))
{
i = 0;
}
setTimeout((function(msg)
{
i++;
return function()
{
if(i < list.length)
{
shuffle(list, i);
}
showMessage(msg);
}
})(list[i]), 1000);
}
</script>
<form>
<input type="button" onclick="shuffle(randomize(3))" value="Start Digit Span Backward">
</form>
</body>
</html>
Any ideas?
i am not a HTML 5 geek or a php professional but here is my suggestion
Can i suggest putting a hidden field in the page and then use the join method of the array to convert it to string splitted by what ever choice splitter like , and then set it to the hidden field value and pass it to the next page just give it a name
Example
JavaScript Function
function ArrayToStringSplitted(ary,splitter,hiddenfield)
{
var aryString= ary.join(spliter);
hiddenfield.value = aryString ;
}
HTML
just add the Hidden Field to the page
<input type='hidden' id="hdfld" name="hdfld" />
i think this will not work with the normal javascript redirection window.location = path
i think this will work with setting the form attributes the action to the location of the php page and the method to post
in there in the php page you can catch the hiddenfield value with $hiddenfield name and split it with the same splitter to return it to a array again
regards
I'm writing a webpage and I need to display a div with some content when a user clicks on a button.
I've written the code below and I don't understand why it doesn't work.
Does someone know why ?
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
<script type="text/javascript">
function traverse(){
output.innerHTML+='Test'; // Nothing happens !
}
function check() {
var keywords = document.getElementById('text').value.split(" ");
for (var i=0; i < keywords.length; ++i) {
traverse_tree()
}
}
</script>
</head>
<body onload ="init()">
<input id="text" type="text" size="60" value="Type your keywords here" />
<input type="button" value="Display the text 'Test'" onclick="check();" />
<div id="output">
</div>
</body>
</html>
thanks,
Bruno
Perhaps because the function is called traverse() and you're calling traverse_tree()?
Also, in your method traverse, you should get the element using document.getElementById('output'), instead of using a (undefined) variable output:
i.e:
function traverse(){
document.getElementById('output').innerHTML+='Test';
}
You could also speed this up by caching the node (to avoid calling getElementById each time the button is clicked):
// Create a closure by wrapping the cached node in a self-executing
// function to avoid polluting the global namespace
var traverse = (function (nodeId) {
// Cache the node to be updated here
var node = document.getElementById(nodeId);
// This is the function that "traverse()" will call. Return this function,
// which will assign it to the variable traverse.
return function () {
node.innerHTML += 'test';
};
// Execute the function with the id of the node to cache, i.e. output
}('output'));