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

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>

Related

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!

Output Contents of Input in div

I am creating a contact form that creates something like a cart view depending on the inputs.
I managed to get all the checkboxes to output when they are checked; I am having trouble getting the same to work with text and number inputs. So input type text, number and textarea.
<input id="form_name" type="text" name="name" class="form-control"
placeholder="Please enter your firstname *" required="required"
data-error="Pflichtfeld" data-validate="true">
<input type="number" id="age" name="age" min="16" max="99"
class="form-control" required="required"
data-error="Pflichtfeld" data-validate="true">
<div id="descript11" style="display:none;">Vorname:
<b id="vorname"></b>
</div>
<div id="descript12" style="display:none;">Alter:
<b id="alter"></b>
</div>
So I tried the method with $(document).change() but that did not work. I want to grab the contents of the input or textarea and output it to the div with the corresponding id. So "age" should output to "alter" and so on. I'm not sure how to achieve this and w3schools or other sites don't offer an answer.
You can do this by adding an input event listener to your input text boxes. In the example below, I loop through all your input text boxes (as I gave them a class of text-input) using a forEach loop. You can then grab the text from the textbox using this.value and place it into its associated div. To help with this I created a mapping object which is used to map the id of the input to the id of where the text should be placed into.
See example below:
const input_map = {
form_name: "vorname",
age: "alter"
}
document.querySelectorAll(".text-input").forEach(elem => {
elem.addEventListener('input', function() {
const textbox_value = this.value; // get text from input bpx
const target = input_map[this.id]; // get location (ie: the id) of where the text should be placed
document.getElementById(target).innerText = textbox_value; // place the text in that location
});
});
<input id="form_name" type="text" name="name" class="form-control text-input" placeholder="Please enter your firstname *" required="required" data-error="Pflichtfeld" data-validate="true">
<input type="number" id="age" name="age" min="16" max="99" class="form-control text-input" required="required" data-error="Pflichtfeld" data-validate="true">
<div id="descript11">Vorname:<b id="vorname"></b></div>
<div id="descript12">Alter: <b id="alter"></b></div>
Note: In the example above I removed the style="display: none;" from your divs so that you can see the output
You can do it like this:
$('input').on('input',function(){
let text = $(this).val();
let id = $(this).attr('id');
$('div.'+id).text(text)
});
This snippet checks changes on inputs and sets their value to the div with class that matches each input's id .

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/

How to transfer values from between input

Before anyone marks this as a duplicate, I have looked at many sites and am currently using this one - jQuery - passing value from one input to another for guidance, yet no result... I am trying to pass a value from one input in one form to another input in a 'table'. I have put it in a table because of a very weird reason - it does not display a Sparql value when in a form only displays in a table so the input was placed in a table. My code is below:
Form
<form onclick="txtFullName.value = txtFirstName.value +'_'+ txtLastName.value">
First name : <input type="text" name="txtFirstName" value="#ViewBag.FirstName"/> <br><br>
Last name : <input type="text" name="txtLastName" value="#ViewBag.LastName" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
Table
<table id="results">
<Full name:
<br>
<input id="userInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="submit" type="submit" value="Submit">
</table>
JQUERY
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('txtFullName').val($(this).val());
});
});
I am trying to display the txtFullName into userInput input when pressing submit but right now only the `txtFullName' is displayed when pressing submit. Also the submit is the submit button in the FORM.
Anymore info needed let me know:)
You need to change the onclick to action on the form if you are trying to use submit button. The other way is to use input type button instead of submit:
So:
$(document).ready(function() {
$('#submit12').on('click', function (e) {
console.log('test');
$("#txtFullName").val($("#txtFirstName").val() + '_' + $("#txtLastName").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name : <input type="text" id="txtFirstName" value="First"/> <br><br>
Last name : <input type="text" id="txtLastName" value="Last" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
If you want to display txtFullName into userInput, simply do something like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').val($('#txtFullName').val());
});
And why do you need change function there , if yo need changes when click submit.
Edit your JQuery like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('#txtFullName').val($(this).val());
});
});
$('#submit').on('click', function () { //Form submit
$('#userInput').val($('#txtFullName').val());
});
I don't clearly understand why you do it but It can fix your code.
It is not entirely clear what the two buttons do, but the operation itself is really very simple. See comments inline for explanations:
// Wait until the DOM is loaded and all elements are avaialble
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you'll need
var theForm = document.getElementById("frmTest");
var txtFirstName = document.getElementById("txtFirstName");
var txtLasttName = document.getElementById("txtLastName");
var txtFulltName = document.getElementById("txtFullName");
var txtUserInput = document.getElementById("txtUserInput");
var btn1 = document.getElementById("btnSubmit1");
var btn2 = document.getElementById("btnSubmit2");
// Function to join names together
function combine(){
txtFullName.value = txtFirstName.value + '_' + txtLastName.value;
}
// Set event handlers
frmTest.addEventListener("click", combine);
btn1.addEventListener("click", combine);
});
<!-- Keep you JavaScript out of your HTML -->
<form id="frmTest">
First name : <input type="text" id="txtFirstName" name="txtFirstName" value="#ViewBag.FirstName">
<br><br>
Last name : <input type="text" id="txtLastName" name="txtLastName" value="#ViewBag.LastName" >
<br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="btnSubmit1" type="button" value="Combine Names">
<table id="results">
<Full name:
<br>
<input id="txtUserInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="btnSubmit2" type="submit" value="Submit">
</table>
</form>

Display first and lastname with 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.

Categories

Resources