Javascript capture form text field onChange to hidden field - javascript

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/

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 .

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>

Create dynamic name of newly appended child

I have the following form inputs in a particular td tag.
<input type="text" value="" name="form_data[1][1][text]"><br>
<input type="text" value="" name="form_data[1][2][text]"><br>
<input type="text" value="" name="form_data[1][3][text]"><br>
Also I have the code for appending new form. But i need to change its name like this form_data[1][4][text] that is array name with next index for text should come.
i.e.
<input type="text" value="" name="form_data[1][4][text]"><br>
Add a class to your input, get the number of elements with this class:
var nbElt = document.getElementsByClassName('yourclass').length;
var newInp = document.createElement('input');
newInp.name = "form_data[1]["+parseInt(nbElt+1)+"][text]";
document.body.appendChild(newImp);
And it's done.

Creating Javascript function called ReadName()

I want to create a form which has a text entry box where a user can enter their name and then I want a button as well. But what I want this button to have a function called ReadName() where what will happen is when the user clicks on the button it will come up with a message saying "Hello user name will appear here
I have tried my self and but I don't think I am not getting what I want. Any help will be appreciated.
<form>
<label for="name">Name:</label>
<input type="text" name="name" id="name"/>
<input type="text" name="name" onfocus="ReadName()"/>
</form>
function ReadName() {
var name = document.getElementById('name').value;
alert('Hello '+ name);
}

Categories

Resources