Display first and lastname with JavaScript - javascript

I'm learning JavaScript and I'm trying to make it so the user is able to enter a name and lastname and then click a send button. When that happens the name and lastname is displayed on the the screen just bellow.
The problem is that it doesn't work. Nothing happens when the user clicks the send button.
Here is how I tired it.
HTML:
<body>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<br>
<input type="button" value="Send" onclick="MyFunction()">
<div id="here"></div>
<body>
JavaScript:
function MyFunction() {
var first, second;
first = document.getElementById("firstname").value;
second = document.getElementById("lastname").value;
document.GetElementById("here").InnerHTML = first;
document.GetElementById("here").InnerHTML = second;
}
https://jsfiddle.net/7wu3gjqm/

This is your example worked fine after some changes :
HTML:
<input type="text" name="firstname" id="firstname">
<input type="text" name="lastname" id="lastname">
JS:
myFunction = function() {
var first = document.getElementById("firstname").value;
var second = document.getElementById("lastname").value;
document.getElementById("here").innerHTML = first+" "+second;
}
Find your example here : jsFiddle.

You wanted this as your output code:
document.getElementById("here").innerHTML = first + " " + second;
The G and I should be lower case and you should output both first and last names at the same time using string concatenation. Note though, that this will have XSS vulnerabilities.
Also, change your input name attributes to id attributes.

You are using getElementById but you dont have any element with the given Ids, I believe you've forgot to add id's to your input elements:
<input type="text" name="firstname" id="firstname">
<input type="text" name="lastname" id="lastname">
You might also want to change GetElementById for getElementById as js is case sensitive.

Related

I need help writing data from a html form to a text file in JavaScript

I Know someone has already answered this question, but for some reason it might have been deleted or removed because I can seem to find it anymore, thanks for any help provided strong text
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("<your Path>/filename.txt", True);
var firstName = document.getElementById('FirstName');
var lastName = document.getElementById('lastName');
s.writeline("First Name :" + FirstName);
s.writeline("Last Name :" + lastName);
s.Close();
}
<form onSubmit="WriteToFile(this)">
<label>Type your first name:</label>
<input type="text" name="FirstName" id="firstName" size="20">
<label>Type your last name: </abel>
<input type="text" name="LastName" id="lastName" size="20">
<input type="submit" value="submit">
</form>

Passing form data to javascript

So I have a problem, im looking to pass very basic user input into a javascript function for javascript to then process that information, I am really only looking to pass strings, however I just want to learn the concept. Below is how I would (THINK) you'd do this, but it doesn't work and I am not sure why. Could someone show me how to do this simply and properly.
<body>
<form id="frm1">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction(fname, lname)" value="Submit">
</form>
<script>
function myFunction(fname, lname) {
console.log(fname);
console.log(lname);
}
</script>
</body>
Here is an alternative approach that might help:
You can see part of the following code in action at this link:
https://jsfiddle.net/m85yLoca/
<html>
<head></head>
<body>
<form id="frm1">
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<script>
function myFunction() {
let fname = document.querySelector('#fname').value;
let lname = document.querySelector('#lname').value;
console.log(fname);
console.log(lname);
}
</script>
</body>
I made sure to add id="" settings for the fname and lname form inputs. This can help us with individually specifying what input we want to access for later use.
This approach uses document.querySelector() to pinpoint which form input you are wanting to access. I get the value of the input via the .value part at the end of the document.querySelector() lines and then assign these to individual variables fname and lname.
Then, you can access the individual fname and lname variables in your function.
This can be done by the following step.
getting the all input DOM value by document.querySelectorAll(). I didn't add id in each of the input. Instead, I select them all
select each one of them and assign the value to a variable.
<form id="frm1">
First name: <input type="text" name="fname" ><br>
Last name: <input type="text" name="lname" ><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<script>
function myFunction() {
const inputValues = document.querySelectorAll('#frm1 input')
const fname = inputValues[0].value;
const lname = inputValues[1].value;
console.log(fname, lname);
}
</script>
If later on, you need to submit the data to server. Just add the onsumbit attribute.
<form onsubmit="sendData()">
//input and other structure
<input type="submit" value="Submit">
</form>
<script>
function sendData(){
//pack all your input value
//make the ajax call here
}
</script>

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 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