简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM