Get current input value in function that is set as variable within another function. (I AM STUMPED) code examples within - javascript

I have a difficult question, I am trying to get the input value of an input field, however, I need this to happen within another function.
I already have code that works outside of this other function but I need to refactor it to work inside another function that I am calling.
Examples of working code and non-working code are below.
Here is the HTML where I am getting the input:
<!DOCTYPE HTML>
<HTML>
<head>
<title></title>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/styles.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/require.js"></script>
<script type="text/javascript">
(function () {
var config = {
baseUrl: "js",
};
var dependencies = ["otherFile"];
require(config, dependencies);
})();
</script>
</head>
<body>
<div>
<label>Input URL</label>
<input type="url" />
<p id="targetInput"></p>
</div>
</body>
</html>
Here is the non-working JS that I am trying to call within another function:
function someOtherFunction() {
var getCurrentInput = function() { };
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
var getCurrentInput = function (e) {
log.currentInput = e.target.value;
};
}
});
Lastly here is the working code that works outside of the scope of someOtherFunction
var getCurrentInput = "";
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
function getCurrentInput(e) {
log.currentInput = e.target.value;
}
Now you may notice that there isn't a form being submitted here, the reason for this is because this code is running on an iframe that is being called into another app. The submit is happening there but requires me to call a function to make it happen and technically isn't a submit, meaning I don't have control over it like a regular submit. This is why I need to call the current input value inside someOtherFunction.
Any help would be greatly appreciated here! Essentially I want to get the value inside the input and update my API with the value as a JSON string. There must be a better way!

Was a bit difficult to follow at first given the nesting, but something like this?
const doThing = (e) => {
let input = document.getElementById("input");
let log = document.getElementById("targetInput");
log.textContent = input.value;
}
<div>
<label>Input URL</label>
<input type="url" id="input"/>
<p id="targetInput"> </p>
</div>
<button onclick="doThing()">Click</button>
Essentially an external submit that takes an internal input value, and injects it into another internal element?

Related

Call a function on Input Completion

I have a name input on 1.html.
I need to call a function where the input will be stored after completion, and when the person clicks ~next~ to go to the next page (2.html), whatever was stored appears there.
Example:
~1.html~
What's your name?
~input~ John ~input~
~2.html~
Hi, John! How can i help you?
I know i can use Session Storage to do it, but i'm not sure on how to proceed.
Here's what i have:
1.html
<p>"Whats Your Name?"</p>
<input id="your-name-input" type="text">
<a href="2.html">
<button id="next-button">Next</button>
<script>
nextButton = document.getElementById("next-button);
nextButton.addEventListener("click", () => {
var name = document.getElementbyId("your-name-input").value;
if(name !== "") {
sessionStorage.setItem("name", name);
} else {
alert("Please fill yout name")
});
</script>
And then, on 2.html i have:
<p id="user-name"></p>
What i'm trying to do, is to put inside the <p>, the following greeting:
Hi (name.value), how can i help you?
How can i call a function that loads the name value on the 2.html page when the page loads?
The below code should work. There are a few things missing in your code, not sure if you copied everything in.
In either case, the below works for me. You just need to update the link in the window.location = syntax. When you do that, it will take your stored value to the new page in the same tab, and display it using the script code in 2.html.
Code in 1.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>Your name test</title>
</head>
<body>
<p>Whats Your Name?</p>
<input id="your-name-input" type="text">
<button id="next-button">Next</button>
<script>
const nextButton = document.getElementById("next-button");
const input = document.getElementById("your-name-input");
nextButton.addEventListener("click", () => {
const name = input.value;
if(name !== "") {
sessionStorage.setItem("name", name);
window.location = "<link to your 2.html file>";
} else {
alert("Please fill your name")
}
});
</script>
</body>
<footer>
</footer>
</html>
Code in 2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>See, it works</title>
</head>
<body>
<p id="user-name"></p>
<script>
const displayText = document.getElementById("user-name");
const storedValue = sessionStorage.getItem("name");
console.log(storedValue);
window.addEventListener("load", () => {
displayText.innerHTML = "Hi " + storedValue;
})
</script>
</body>
<footer>
</footer>
</html>
Original ans to original question:
You could use an addEventListener with an IF statement for your 'next' button and then the code you already have for localStorage.
Depending on what you need from your page, you could also use sessionStorage - that one doesn't save the input forever so might save, albeit limited, space on your user's computer.
I don't see the HTML for your button yet. But assuming you have it, here's an option for the rest of your code in 1.html.
Inside 1.html script tag:
nextButton = document.getElementById("yourButtonID");
nextButton.addEventListener("click", () => {
var name = document.getElementById("your-name-input").value;
if(name !== "") { // if input is not empty
localStorage.setItem("name", name); // set the value in localStorage
} else {
alert("Please fill your name")} // else, display an alert (if you like)
});

Program not getting value of a text field in JavaScript [duplicate]

This question already has an answer here:
Why is the value of my input always empty if I store it in a variable?
(1 answer)
Closed last year.
I am not really sure what is happening but I want to write a program that puts commas in a number you input, but when I run it and input a number the output is blank. Can anyone help???
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js" defer></script>
</head>
<body>
<h1>Enter your number below:</h1>
<input type="text" placeholder="Right here" id="number">
<button id="submitButton">Add commas</button><br>
<h1 id="numberWithCommas">0</h1>
</body>
</html>
JavaScript:
const number = document.querySelector("#number").value;
let answerElement = document.querySelector("#numberWithCommas")
const button = document.querySelector("#submitButton");
button.addEventListener("click", () => {
answerElement.textContent = number.toLocaleString();
})
I am not really sure what is happening so I can't tell you much. Sorry.
let answerElement = document.getElementById('numberWithCommas');
const button = document.getElementById('submitButton');
button.addEventListener("click", () => {
const number = document.getElementById('number').value;
answerElement.textContent = Number(number).toLocaleString();
})
You need to use Number(x) for it to work. Also, the variable number should be defined after the button press, each time.

How to set a default value based on user's previous value

I want to have a default value based on what the user put before. For example, if in an input I put '5' I want to see that the value of that input is 5 when I refresh the page, but if I put 6 I want the default value to be 6. Thanks (i'm a begginer)
Use local storage:
localStorage = window.localStorage;
localStorage.setItem('inputDefault', '5');
let inputDefault = localStorage.getItem('inputDefault');
Here's a more practical example I quickly whipped up:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Storage Example</title>
<script type="text/javascript">
function setLocalStorageValue()
{
let myNumberInputField = document.getElementById('myNumberInput');
let myNewValue = myNumberInputField.value;
let localStorage = window.localStorage;
localStorage.setItem('defaultValue', myNewValue);
}
function getLocalStoredValue()
{
let localStorage = window.localStorage;
let defaultValue = localStorage.getItem('defaultValue');
let myNumberInputField = document.getElementById('myNumberInput');
myNumberInputField.value = defaultValue;
}
</script>
</head>
<body onload="getLocalStoredValue()">
<label>My Number Input
<input type="number" id="myNumberInput" value="0" onchange="setLocalStorageValue()">
</label>
</body>
</html>
Does this answer your question? Note how I am writing back to local storage on the onchange event of the input in question, and I read from local storage when the body of the html loads.

Why can I call function which is in a shadow dom?

I created a custom element called "memory-box" like the below code.
Please pay attention to the function "logthis" which is in "memory-box-template".
memory-box.html
<template id="memory-box-template">
<input id="memory-box" type="form" />
<input type="button" id="testbutton" />
<script type="text/javascript">
function logthis(me){
console.log(me);
}
</script>
</template>
<script type="text/javascript">
(function() {
var thisDoc = document.currentScript.ownerDocument;
var storage = localStorage;
var proto = Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var temp = thisDoc.querySelector('#memory-box-template');
var con = document.importNode(temp.content, true);
this.createShadowRoot().appendChild(con);
var input = this.querySelector('::shadow #memory-box');
var data = storage.getItem(this.id);
input.value = data;
input.addEventListener('input', saveData.bind(input, this.id));
}
},
});
document.registerElement('memory-box', {
prototype: proto
});
function saveData(id, e) {
storage.setItem(id, this.value);
}
})();
</script>
Now, I uses the custom element "memory-box" like the below code.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="import" href="/html/memory-box.html">
</head>
<body>
<div><memory-box id="memory1"></memory-box></div>
<div><memory-box id="memory2"></memory-box></div>
<div><memory-box id="memory3"></memory-box></div>
<div><memory-box id="memory4"></memory-box></div>
</body>
<script type="text/javascript">
logthis(this);
</script>
</html>
As you can see, I putted a script in the index.html and called the function "logthis" just because I was curious. And no error occurred.
Why?
The function "logthis" is in each shadow doms. It's supposed not able to be called outside the shadow dom, I think.
As explained here, while the HTML within Shadow DOM is encapsulated, any JavaScript is NOT -- it is in the global scope, unless you utilize specific javascript techniques (namescaping, IIFE) to do so.
Hope this helps,
Jonathan Dodd

Bug displaying a div element when a user clicks on a button

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

Categories