Why is my function not defined and not loading - javascript

I have a function that's called with a submit button and another that is based on key entry enter. When I run my code I keep getting an error saying myFunction() is not defined why is this?
js code: The validate function is suppose to add in user input elements based on how many volunteers need and invitation for the website. the myFunction() code is supposed to save fields of the form to variable (more code variables are in here but you guys don't need to see that)
html: it is a basic form the user is supposed to enter how many guests and the JavaScript is supposed to create a field for each recipient name. I am then supposed to save the names to and array which I will be working on later but I can get past the myFunction is not defined error.
var wage = document.getElementById("howMany");
window.onload = wage.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
var num = document.getElementById("howMany").value;
for (i = 1; i < num; i++) {
//loop set to repeat to the amount of guests inputed by user
container.appendChild(document.createTextNode("Recipient " + (i + 1) + ":"));
//creates a text for the user to read which recipient each input is for
var x = document.createElement("input");
//creates the input element
x.setAttribute("id", "empInput" + i);
x.setAttribute("type", "text");
//sets the type and attribute
container.appendChild(x);
//places the input element in the container
//values.push(x);
}
}
window.onload = function myFunction() {
//loads the function on page load to change variables for user
var urlParams = new URLSearchParams(location.search);
//sets var for the URL information the users inputed information on submit
//var num = urlParams.get("howMany");
//sets the var for the amount of guests attending
var container = document.getElementById("container");
//sets a variable to reference the container in the form to place the input elements
var values = new Array();
}
<section id="pageForm">
<form name=myForm action="#">
<div>
<label for="howMany">How Many Guests:
<br />(max. 10) <br />
</label>
<input type="number" id="howMany" value="" placeholder="0" />
</div>
<div>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" placeholder="Enter your Recipient Name" />
</div>
<div id="container">
</div>
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" placeholder="Enter your Organization Name" />
<label for="eventDate">Event Date:
</label>
<input type="text" name="eventDate" placeholder="Enter your Event Date" />
<label for="websiteURL">URL:
</label>
<input type="text" name="websiteURL" placeholder="Enter your Website URL" />
<label for="hostName">Host name:
</label>
<input type="text" name="hostName" placeholder="Host Name" />
<input type="submit" value="Submit" onclick="myFunction()">
</form>
</section>

That's definitely not intuitive, but the name "myFunction" as you had it is basically ignored. Try this instead.
function myFunction() {
//loads the function on page load to change variables for user
//etc. as before
}
window.onload = myFunction;

Related

onchange function does not work after reset the form

I have the following html and JS:
<body>
<form id="form_test">
<label>Your name: </label>
<input type="text" name="name">
<label>Your age: </label>
<input type="number" name="age" onchange="update()" value="0" min="0">
<button type="button" onclick="send(this.form)">Send</button>
</form>
<script>
function send(forma){
let data = Object.fromEntries((new FormData(forma)).entries());
console.log(data);
forma.reset();
}
function update(){
console.log('Input number has changed');
}
</script>
</body>
When I fill the form an send it with an age different of 1 I can go back and fill the form again, as you can see in the code, there is a console log for every time I change the age, however, If I send the form with an age of 1, and then I fill the form again, but changing the age with the input number buttons, it looks like the onchage event does not work, but if I change the value by typing everything works fine.
Do you know why this is happening? As I mentioned, this only happens after sending the form with the input number equals to 1 and by changing the value with the input number buttons.
Prefer to code this "natural" way:
const formTest = document.querySelector('#form_test') // same as CSS notation
formTest.onsubmit = evt =>
{
evt.preventDefault(); // disable form submit / page reload
let data = Object.fromEntries((new FormData(formTest)).entries());
console.clear();
console.log(data);
formTest.reset();
}
formTest.age.onchange = evt => // use form's elements names directly
{
console.clear();
console.log('Input number has changed :', formTest.age.valueAsNumber );
}
<form id="form_test">
<label>Your name: </label>
<input type="text" name="name">
<br> <br>
<label>Your age: </label>
<input type="number" name="age" value="0" min="0">
<br>
<br>
<button type="submit">Send</button>
</form>

Set form field typed value to Javascript Variable and then using this value in another variable

I'm a javascript noobie. I'm creating a form for visitors to sign up to a webinar. I need to create a "unique code" or unique identifier for each visitor that submits the form.
For this I've created a hidden field called "Unique Code". This unique code is generated from a variable which concatenates a string, the email address value typed in the form and a webinar id that I assign from another variable. When I submit the form I just get the string and the webinar id concatenated by not the email address. The desired resulting value is something like this: GTW-visitor#emailaddress.com-12345. Here's my code:
<form action="/destination/" method="post" name="GTW_Test_Form">
<input type="hidden" name="gtwWebinarId" id="gtwWebinarId" value="">
<input type="hidden" name="uniqueCode" id="uniqueCode" value="">
<label for="email"><b>Email</b></label><br>
<input type="text" placeholder="Enter Email" name="emailAddress" id="emailAddress" required><br>
<label for="name"><b>First Name</b></label><br>
<input type="text" placeholder="Your First Name" name="firstName" id="firstName" required><br>
<label for="name"><b>Last Name</b></label><br>
<input type="text" placeholder="Your Last Name" name="lastName" id="lastName" required><br><br>
<input type="submit" value="Register to webinar">
</form>
And then, the javascript:
<SCRIPT LANGUAGE="JavaScript">
var emailAddressInput = document.getElementById("emailAddress").value;
var webinarId = "12345678";
var uniqueCode = "GTW-" + emailAddressInput + "-" + webinarId;
document.querySelector("#gtwWebinarId").value = webinarId;
document.querySelector("#uniqueCode").value = uniqueCode;
</script>
Thanks in advance,
Daniel
Your script runs even before the form fields have any value, you may have to write your script code inside a function which will be invoked by "onsubmit" event of the form.
<form onsubmit="foo(event)">
<script LANGUAGE="JavaScript">
const foo = (event)=>{
event.preventDefault();
var emailAddressInput = document.getElementById("emailAddress").value;
var webinarId = "12345678";
var uniqueCode = "GTW-" + emailAddressInput + "-" + webinarId;
document.querySelector("#gtwWebinarId").value = webinarId;
document.querySelector("#uniqueCode").value = uniqueCode;
}
</script>
Try to use var emailAddressInput = document.querySelector("#emailAddress").value;
That actually worked! Thank you, Sai!

javascript code not working with html script

hi guys I just begin to learn javascript recently and I came across an issue, when I enter a "10" as the first input element and click submit, it should print a "10" at the bottom of the html page, but instead it prints nothing.
<html>
<head>
<head>
<form action="" method="POST" id="info">
<br>Age:<br><label>
<input name="age" id="age" type="text" placeholder= "enter your age" />
</label>
<br>Sex:<br><label>
female<input name="female" id="female" type="checkbox" />|
male<input type="checkbox" name="male" id="male" />|
</label>
<br>weight:<br><label>
<input type="text" name="weight" id="weight" placeholder="enter your weight in kg" />
</label>
<input type="submit" form="info" value="Submit" onclick="validation()"/>
</form>
<div id="div1"> </div>
<script src = "test.js"></script>
<html>
This is the html code (index.html)
function validation(){
var ageinput = parseInt(document.getElementById("age"));
var femaleinput = ducument.getElementById("female");
var maleinput = ducument.getElementById("male");
var weight = parseInt(document. getElementById("weight"));
var formulaformale;
var formulaforfemale;
var gendererror;
if (ageinput == 10){
gendererror = ageinput
}
document.getElementById("div1").innerHTML = gendererror;
}
this is the javascript code.(test.js)
I tried to find syntax errors but everything looks fine to me, I also compared my code with other people's and I could find anything in my code that is different.I am totally new in javascript so I might have missed certain part of the programming language. please help.
Your button type is submit, so it will always submit and reload the page every time you press the button. Make it a normal button by changing input type to button
<input type="button" form="info" value="Submit" onclick="validation()"/>
Then follow #Ibra answer
// add .value
var ageinput = parseInt(document.getElementById("age").value);
// ducument -> document
var femaleinput = ducument.getElementById("female").value;
Try again like this :
// add .value
var ageinput = parseInt(document.getElementById("age").value);
// ducument -> document
var femaleinput = ducument.getElementById("female").value;

Javascript capture form text field onChange to hidden field

I have a form with a simple text field for a person's full name.
After a user enters their name and moves/tabs to the next field, I want to be able to capture the full name, extract only the first name, and attach to a separate hidden form field.
If the user goes back and corrects their full name, the extraction should repeat to get the correct first name. The full name text field would still be passed along during form submittal.
I'm thinking plain JS would be the best approach (I'm not using JQuery).
<form>
<input type="text" name="fullname" value="">
<input type="hidden" name="firstname" value="">
</form>
you can try this
this is your html
<form>
<input type="text" name="fullname" value="" id="fullname">
<input type="hidden" name="firstname" value="" id="firstname">
</form>
this is your javascript
<script>
let fullName = document.getElementById("fullname");
let firstName = document.getElementById("firstname");
fullName.addEventListener("blur", function() {
let names = fullName.value.split(" ");
if (names.length > 0) {
firstName.value = names[0];
}
});
</script>
https://jsfiddle.net/3k8kur9u/

Dynamically copy input of two fields and paste it in third field?

I'm trying to copy the First Name and Last Name field into another 'Username' field dynamically. The Username field should also be lowercase and have a hyphen in the middle. So for example,
if First Name = John
and Last Name = Smith
then Username (dynamically-created) = john-smith
Any ideas?
You can do this with plain JavaScript. I'm assuming there is a button of some sort to add the fields together. Also assuming that your Input is <input> text boxes.
document.getElementById("button").addEventListener("click", function() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var userName = document.getElementById("userName");
userName.value = firstName.toLowerCase() + "-" + lastName.toLowerCase();
});
<input id="firstName" type="text" placeholder="First Name" />
<input id="lastName" type="text" placeholder="Last Name" />
<input id="userName" type="text" placeholder="Username" disabled />
<button id="button">Create Username</button>
To make it dynamically update, use onkeydown or onkeyup. Follow kemotoe's answer.
Another option is using onkeyupevent to make it dynamic. This also takes care of any uppercase letters.
function generateFullName() {
document.getElementById("username").innerText =
document.getElementById("fName").value.toLowerCase() +
"-" +
document.getElementById("lName").value.toLowerCase();
}
First Name <input type="text" id="fName" onkeyup="generateFullName()" />
Last Name <input type="text" id="lName" onkeyup="generateFullName()" /> <br/>
Username: <span id="username" />
You can do it with jquery, too. This is a working example.
Working Fiddle
HTML
<input id = "first"> <br> <br>
<input id = "last"> <br> <br>
<input id = "username">
<button id ="generate">Generate</button>
JS
$("#generate").on("click", () => {
let first = $("#first").val()
let last = $("#last").val()
$("#username").val(first+ "-"+last)
})
$('#firstName').change(updateUsername());
$('#lastName').change(updateUsername());
function updateUsername(){
$('#userName').val($('#firstName').val().toLowerCase() +"-"+$('#lastName').val().toLowerCase() );
}
Bind with change event to update the user name field
You can use the onkeypress event.
It would look like this
document.querySelector('.form').addEventListener(("keypress"), () => {
//Code to edit the username field goes here
//Try pressing a key inside the form
alert('Hi');
});
<form class='form'>
<input type="text">
<input type="text" >
<input type="text" class='username'>
</form>

Categories

Resources