Javascript: Taking in User-Input - javascript

I have explicitly defined a Javascript file for my HTML document. In my HTML, I have created a text box where the user can type in their name, then click a button called "submit."
In JS, as soon as they click "submit," I want to store what they have entered as their name in a variable (I'm using eventListener to know when they click "submit"). My question is, how would I be able to do this without using onclick in my HTML doc? Here is my following code at the moment:
my_button.addEventListener('click', my_function);
function my_function(){
alert("Hello world!");
}

One way would be to use oninput event and every time the user types in something update the variable in which you want to store the input. The input tag would look like this: <input type="text" oninput="myFunction()"> and in the function that is declared as the handler you can take the input and store wherever you want.

You can have the code separate. All you'd have to do in the HTML document is to load the javascript file.
Here's a snippet. First the content of the javascript file, and below the simplified HTML document.
let myButton = document.getElementById("theButton");
myButton.addEventListener('click', my_function);
function my_function(){
alert("Hello world!");
}
<button id="theButton">Test</button>

to add a separate javascript file do this anywhere in your html
<script type='text/javascript' src = 'path/filename' > </script>

to get the value of the input yoy need to slect it first. then you get the value via the value property.
see this example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id="my_input" type="text">
<button id="my_btn">click</button>
</body>
</html>
then you can use the following javascript.
var my_button = document.querySelector('#my_btn');
var my_input = document.querySelector('#my_input');
var value;
my_button.addEventListener('click',function () {
value = my_input.value;
alert(value);
})
hope this helps!

Related

I need help understanding event handlers and functions in JavaScript?

I wrote HTML document and linked to my JS document.
when I execute the HTML file on my browser it only shows the "Click me!" button, but what I expected it to do was to show the result of my math function when clicked. But .. nothing happens. I'm very new to JavaScript so I'm sure this is a simple answer, but Googling isn't helping ... I appreciate any insight to what I'm doing wrong here.
Here's the code from HTML file:
<!DOCTYPE html>
<html lang=""en">
<head>
<meta charset="UTF-8">
<script src="JS/main.js"></script>
</head>
<body>
<p id="Math">
<button onclick="myFunction()">Click me!</button>
</p>
</body>
</html>
Here's the JS file:
function myFunction(a, b) {return a * b;}
document.getElementById("Math") .innerHTML = myFunction(13, 4);
Not sure what are you trying to do, but if you want to change the content of the "Math" element, you must call the function with parameters (eg: onclick="myFunction(1,3)") and that function should replace the content:
function myFunction(a, b) {
document.getElementById("Math").innerHTML = a * b;
}
<p id="Math">
<button onclick="myFunction(3,4)">Click me!</button>
</p>
Also if you want to preserve the button after clicking, this should be located outside the "Math" element to avoid being removed when replacing innerHTML
You’re including you script file in the header, so it runs before the dom is available. When it executes, it won’t be able to find your id, so nothing will happen. You likely will see an error in the console that your document.getElementById call is returning undefined. Either include it at the end of the body, or add a defer tag:
<script src="JS/main.js" defer></script>
Also, as soon as the code runs, it overwrites the content of the p tag, including the button. Make the p and the button siblings.
One error in your html appears to be caused by an extra " in your lang attribute for your opening html tag. Try deleting it.
<html lang="en">

How to take content from an element in a webpage and show it in my html page?

I need to take the content from the elements of a page with a specific class "verse" and show it in my page, that contains a text input (to insert the link of the page where the content is) and a button to trigger the function that does the work.
This is my HTML file.
<!DOCTYPE html>
<html>
<head>
<title>Get Verse 1.0</title>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
</head>
<body>
<!--takes an input value-->
<input type="text" id="link">
<!--calls the function to display text-->
<input id="clickMe" type="button" value="Enter" onclick="getAndDisplay()">
<p id="actualText"></p>
<script type="text/javascript">
function getAndDisplay(){
//takes the input
let link = document.getElementById('link').value;
//store the <div class=verse>content in a variable
let verse = $('.verse').load('ajax/${link}');
//store the innerHTML of the content in a variable
let htmlContent = verse.innerHTML;
//display the content in a <p>
document.getElementById("actualText").innerHTML = htmlContent;
}
</script>
</body>
</html>
I've already tried with jquery but I couldn't figure out how to solve this problem.
The link that I'm using to do the tests is this https://my.bible.com/it/bible/59/GEN.1.ESV
I'm trying to take all those verses and display just the text (maybe later I will do some style with CSS)
I believe what you're looking for could be something like this:
$( "#actualText" ).load(`ajax/${link} div.verse`);
${link} is called a "template literal" and requires the " ` " sign
The target id in the jquery constructor should probably be the target of where you want the output to go.
The div.verse is the "selector" argument, as read in https://api.jquery.com/load/

JavaScript Calculator using HTML forms

I want to create a calculator that, using JavaScript, takes a number from an HTML input box like this one.
// Take form input and multiply by four
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input placeholder="Side Length of Square"/>
</body>
</html>
How could I then relay the user input, say 5, so that the JavaScript would take "5" and multiply it to find the area of the square? This is my first question ever on Stack Overflow, so I apologize if I did something wrong. Thanks for the help!
You would use javascript's onkeyup to calculate the area of a square as the user types in numbers. Check out the code below!
function calc(){
var val=document.getElementById("myInput").value;
document.getElementById("area").innerHTML=Math.pow(val, 2);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="myInput" placeholder="Side Length of Square"onkeyup="calc()"/>
<p>Area : <span id="area"></span></p>
</body>
</html>
First, you need to decide where you want to place your output, e.g. introduce a new <div> element whose text content will hold the computed side length.
Also, you should give your <input> as well as your output <div> a unique id attribute so you can identify it later on from within your JavaScript code.
Then, you would introduce a new <script> before the closing </body> tag. This guarantees that at the time of script execution, all relevant HTML elements have already been loaded and added to the Document Object Model (DOM) so that your script can access them.
Finally, you write a JavaScript "input" event handler and attach it to the <input> element.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="side-length" placeholder="Side Length of Square">
<div id="area"></div>
<script>
let input = document.getElementById("side-length");
let output = document.getElementById("area");
input.addEventListener("input", function(event) {
let sideLength = input.valueAsNumber;
output.textContent = sideLength * sideLength;
});
</script>
</body>
</html>
Note: Above event handler computes the area of the square with given side length, as per your question and opposed to the comment above your code snippet.

How can I use Javascript to handle form data & display a separate results page?

I am re-writing a large web form that is written using Perl Dancer and Template Toolkit to handle the submitted form data and display a results page. I would like to abandon Template Toolkit and Dancer in favor of a Javascript-only solution. How can I write the form to pass all of the data to Javascript and have it display the data on a nice formatted results page?
I'm unsure of what kind of data you have that could be entered in your form, so I don't have any specific help with how you could present that data in a nicely formatted way.
On the topic of passing data from a form to javascript (or jquery, since that was in your tag) here is an example of how you could accomplish this.
Let's say you have a simple form in HTML laid out something like this.
<form id="form">
<input type="text" id="input">
</form>
You can catch the submission event of this form in javascript, prevent what it would normally do, take the data from it's input fields and do something specific with them. Here's an example.
// On DOM loaded
$(document).ready(function () {
// Catch the submit event of the form
$('#form').submit(function (e) {
// Prevent default form submit event
e.preventDefault();
// Access some input field data
var input = $('#input').val();
});
});
I would be happy to point you in a more specific direction on how you could format and present your data in a nicely formatted way if you would like to provide some more information as to what data you would be passing from your form.
I figured it out! I will use HTML5 sessionStorage. Here is the code:
form html:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form test</title>
</head>
<body>
<form id='form' action="result.html" rel="external">
<input name='day' id='day' type='text'><input type='submit' id='completed' value='Completed!'>
</form>
<!-- SCRIPTS -->
<script src="jquery.js"></script>
<script src="main.js"></script>
</body>
Here is the main.js:
function saveData() {
var submit = document.getElementById('completed');
submit.onclick = function() {
sessionStorage.setItem('day', document.getElementById('day').value);
};
}
window.onload = function() {
saveData();
};
Here is the result html:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Result</title>
</head>
<body>
<div id="stuff"></div>
<!-- SCRIPTS -->
<script src="jquery.js"></script>
<script src="result.js"></script>
</body>
</html>
Here is the result.js:
function displayData() {
var div = document.getElementById('stuff');
div.innerHTML = "<p>" + sessionStorage.getItem('day') + "</p>";
}
window.onload = function() {
displayData();
};

value of textarea returned empty

I have a HTML form that contains a textarea and submit button. and a JS script that takes the value of the textarea.
The issue I'm facing is when I type text into the textarea and hit submit, the textarea value is empty. HOWEVER, if I hard code text into the textarea the hardcoded value is returned. If I erase the hardcoded value and delete the hardcoded value and type in my own, the hardcoded vale is still returned.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery/jquery-1.9.1.min.js"></script>
<script src="contentForm.js"></script>
</head>
<body>
<form method="post" >
<textarea name ="editor" id="editBox" rows="5" cols="2">type</textarea>
<p><input type="submit" id="submit" value="Submit"></p>
</form>
</body>
</html>
JS
function add() {
$("#submit").click(function() {
var message = "start js";
console.log(message);
var contents = $("textarea").val();
if(contents === undefined) {
console.log("contents undefined");
}
console.log(contents);
var item = {"id":"12", "content": contents};
var obj = JSON.stringify(item);
var obj2 = JSON.parse(obj);
console.log(obj2.id);
console.log(obj2.content);
});
}
$(document).ready(function () {
add();
});
Notice how the textarea above has "type" preloaded. That's the returned value. If I leave it empty, type in my own text in the form and hit submit, the console log shows empty for the value of contents.
I've tried this as well (using textarea id)
var contents = $("#editBox").val();
I'm assuming the issue lies with POST. Because when I hit enter, the text I entered is replaced with "type" (pre-loaded text).
Can POST interfere with it? How else can I go about retrieving the value?
I am not sure of the actual problem, but something strange I have noticed in past few days. console.log() does not work in chrome in few cases like this one. May be it is a firebug bug? Anyways, replaced console.log() with alert and removed the default value from textarea.
Updated fiddle: http://jsfiddle.net/eVmQ9/2/
This seems to work on chrome and firefox.

Categories

Resources