my button in very simply web site won't log in console - javascript

i create a very simple website with javascript and html and all i want to do is log input value to the console and my console is printing something and immediately delete it
html:
const alertFunction = () => {
console.log(document.getElementsByClassName("input"))
}
<!DOCTYPE html>
<html>
<head>
<link href="./styles.css" rel="stylesheet" type="text/css">
<script src="./script.js"></script>
<title>Button With Alert</title>
</head>
<body>
<form>
<input placeholder="Please type your name" class="input" type="text">
<br />
<button class="button" onclick="alertFunction()">Alert Your Name</button>
</form>
</body>
</html>

You have few issues in you code:
Since the default type of button is submit, on clicking it from submission is happening. Thus everything disappears. To prevent the form submission you can either use event.preventDefault() inside the event handler function or specify the type="button" in the element.
Document.getElementsByClassName() returns an array-like object of all child elements which have all of the given class names. You have to use proper index to get the specific element. Finally get the value from the input using value property.
const alertFunction = () => {
console.log(document.getElementsByClassName("input")[0].value)
}
<!DOCTYPE html>
<html>
<head>
<link href="./styles.css" rel="stylesheet" type="text/css">
<script src="./script.js"></script>
<title>Button With Alert</title>
</head>
<body>
<form>
<input placeholder="Please type your name" class="input" type="text">
<br />
<button type="button" class="button" onclick="alertFunction()">Alert Your Name</button>
</form>
</body>
</html>

getElementsByClassName returns an NodeList object. Access the element and get value using .value.
Also use input type=button instead of button. Because button click will perform submit event which is not required
Refer- https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
const alertFunction = function() {
console.log(document.getElementsByClassName("input")[0].value)
}
<!DOCTYPE html>
<html>
<body>
<form>
<input placeholder="Please type your name" class="input" type="text">
<br />
<input type="button" class="button" onclick="alertFunction()" value="Alert Your Name">
</form>
</body>
</html>

You need to prevent the default event of form submit
const alertFunction = (event) => {
console.log(document.getElementsByClassName("input")[0].value);
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<link href="./styles.css" rel="stylesheet" type="text/css">
<script src="./script.js"></script>
<title>Button With Alert</title>
</head>
<body>
<form>
<input placeholder="Please type your name" class="input" type="text">
<br />
<button class="button" onclick="alertFunction(event)">Alert Your Name</button>
</form>
</body>
</html>

Related

ReferenceError: Can't find variable X when calling JS function (or variable) from HTML file

I am trying to call a function in an external JavaScript file from an HTML-file. The goal is to work with the content of a form there.
I tried so many things and always got the Error "ReferenceError: Can't find variable: X"
The positioning of the jquery javascript file loading
The positioning of the <script src="XXX"> call
Calling the function from the button "onclick" or the form "onsubmit"
Trying to call the javascript file from an embedded script in the HTML
This is what my JavaScript file and my HTML looks like right now:
function submit(e) {
answerText = document.getElementById("text").value;
// Do something with it.
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit(e)">Send</button>
</form>
</body>
I also tried
function doSomething() {
// Do something
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit(e)">Send</button>
</form>
<script>
function submit(e) {
doSomething();
}
</script>
</body>
In both cases, it returned the same error over and over again: "ReferenceError: Can't find variable: X". In the first example, X being "submit" and in the second "doSomething".
All help is very welcome. I know there are similar headlines here, but non of the solutions did anything for me.
Hey so when I ran the code without the e as a parameter for the submit function in the html it didn't give me the error. I think it may be because the e is the place holder for the text of the submit function in this case. Hope this helps.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit()">Send</button>
</form>
<script type="text/javascript">
function submit(e) {
answerText = document.getElementById("text").value;
// Do something with it.
}
</script>
</body>
</html>

Send JavaScript variable to HTML page

I have the following HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
</body>
</html>
I want to get the value that is introduced in value1 and when the submit is clicked to put that value in the output. So I wrote in script.js the following code but somehow it doesn't work.
<script>
window.onload = function(){
var val = document.getElementById('value1').innerHTML;
document.getElementById('result').innerHTML = val;
};
</script>
Any ideas?
You have to use .value property of the input field instead of innerHTML. so it would be:
var val = document.getElementById('value1').value;
and also, since you're executing it when the page loads. There will be no value assigned to the input field with id 'value1'. Therefore, you won't get any result.
You can try adding a button with onClick event to execute this function in place of using window.onload
HTML controls you are working on are textboxes, so they have a value property, not innerHTML.
Use this:
var val = document.getElementById('value1').value;
document.getElementById('result').value= val;
You can't get the value of an input element using the innerHTML attribute. Use value instead:
var val = documento.getElementById('value1').value;
Also you should keep in mind that your function is executed when the page loads, NOT when the form is submitted.
The code is not working, because you are calling this function when the window loads, not when the submit button is clicked. Since there is no form, and thus no page loading going on, I'd recommend switching the <input type="submit" value="Click" /> to a button. They are functionally similar, and visually identical. With the the button, though you could use the onclick attribute to call a function when the button is clicked. See below for an example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<button onclick="printOutput()">Click</button>
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
</body>
</html>
Then in your script.js you would have,
function printOutput(){
var val = document.getElementById('value1').value;
document.getElementById('result').innerHTML = val;
}
when the submit is clicked to put that value in the output
You have chosen wrong event window.onload, also you need .value instead of .innerHTML
Option 1: using jQuery, as you already have the import
$(function() {
$('input[type="submit"]').on('click', function(e) {
$('#result').val($('#value1').val());
});
});
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
Option 2: using plain js
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
document.querySelector('#result').value = document.querySelector('#value1').value;
});
});
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
<script>
$( document ).ready(function() {
setTimeout(function(){
var val = document.getElementById('value1').innerHTML;
var generateHere = document.getElementById("result");
generateHere.innerHTML = val;
}, 2000);
});
</script>

Why does getting my form with document.getElementByID stop alert() from firing?

I'm trying to alert the values of the form elements but this isn't functioning even at its simplest: getting the elements of the form then alerting a string.
The alert fires when it's by itself, but not when I put the form's data in the variable. Why?
I'm sure there's probably a very simple mistake in here somewhere, but I'm stumped.
<!DOCTYPE html>
<html>
<head>
<!-- ISTE240 Exercise 5b -->
<meta charset=utf-8 />
<title>Get elements from a form</title>
<script>
function getFormValues() {
// function to send first and last names to an 'alert' message.
alert("test");
var form = document.getElementById(“regForm”).elements;
}
</script>
</head>
<body>
<p>JavaScript Exercise 5b </p>
<form id="regForm" onsubmit="getFormValues()">
First name: <input type="text" name="fname" value="Boo"><br>
Last name: <input type="text" name="lname" value="Radley"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
By default form tag will try to submit form values. You must prevent default behavior, demo below
document.querySelector('#regForm').onsubmit = function(e){
e.preventDefault();
alert('a');
var form = document.getElementById("regForm").elements; //<-- wrong syntax, must be "
console.log(form);
}
<!DOCTYPE html>
<html>
<head>
<!-- ISTE240 Exercise 5b -->
<meta charset=utf-8 />
<title>Get elements from a form</title>
</head>
<body>
<p>JavaScript Exercise 5b</p>
<form id="regForm">
First name:
<input type="text" name="fname" value="Boo">
<br>Last name:
<input type="text" name="lname" value="Radley">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Form onreset Event after the form reset

Here's a sample form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form onreset</title>
</head>
<body>
<form onreset="myFunction();">
<input type="text" name="fname">
<input type="text" name="lname">
<button type="reset" value="Reset">Reset</button>
</form>
<script>
function myFunction() {
alert("The form was reset!");
}
</script>
</body>
</html>
When I click the reset button, the form onreset event fires first, i.e. the alert message appears before resetting the form fields. How can it happen after the form fields rest?
I also tried the following to no avail:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form onreset</title>
</head>
<body>
<form>
<input type="text" name="fname">
<input type="text" name="lname">
<button type="reset" value="Reset" onclick="myFunction();">Reset</button>
</form>
<script>
function myFunction() {
alert("The form was reset!");
}
</script>
</body>
</html>
Try it
function myFunction() {
setTimeout(function () {
alert("The form was reset!");}, 100);
}

Button calling javascript function error

In my view, I want two buttons to populate three hidden fields of a form and submit it. It's not working, and I can't know why. Any ideas?
I have the following code:
<script language="javascript" type="text/javascript">
function FillAndSubmit(thisid) {
$('input[name=First]').val(thisid);
$('input[name=Second]').val(#Model.ID);
$('input[name=Third]').val(#ViewBag.Something);
document.form.submit();
}
</script>
A have a form with invisible fields:
#using (Html.BeginForm(null, null, FormMethod.Post,
new { name = "form", id = "form" }))
{
#Html.Hidden("First")
#Html.Hidden("Second")
#Html.Hidden("Third")
}
And two buttons:
<button class="Button" id="ButtonA" onclick="javascript:FillAndSubmit(this.id);">
CaptionA
</button>
<button class="Button" id="ButtonB" onclick="javascript:FillAndSubmit(this.id);">
CaptionB
</button>
If I put the buttons inside the scope of the form, it submits but without populating the hidden fields. So, it is just not calling the function. Javascript is working in other pages of the same application.
ADDED:
Generated source:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Title</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function Botao(thisid) {
$('input[name=First]').val(thisid);
$('input[name=Second]').val(41);
$('input[name=Third]').val(10/5/2012 1:58:02 PM);
document.form.submit();
}
</script>
...
Some div's with some text
...
<form action="/Controller/Action/" id="form" method="post" name="form"><input id="First" name="First" type="hidden" value="" /><input data-val="true" data-val-required="The DateTime field is required." id="Second" name="Second" type="hidden" value="10/5/2012 1:58:02 PM" /><input id="Third" name="Third" type="hidden" value="" /></form>
<button class="Button" id="ButtonA" onclick="javascript:Botao(this.id);">
CaptionA
</button>
<button class="myButton" id="ButtonB" onclick="javascript:Botao(this.id);">
CaptionB
</button>
</body>
</html>
This needs quotes:
$('input[name=momentoDaConsulta]').val("10/5/2012 1:58:02 PM");
JQuery's .val(value) accepts either string or array of strings, place quotes around #Model.ID and #ViewBag.Something:
$('input[name=Second]').val("#Model.ID");
$('input[name=Third]').val("#ViewBag.Something");

Categories