Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

javascript - Live update multple input fields to multiple span tags

I have a form where I want the user to be able to enter data into the text field, but then I want this to be entered into the span tags live as they are typing each character.

I have managed to do this successfully with one input field going to one span tag using most of the javascript in this post. But changing it slightly to try and accomodate multiple input fields to multiple span tags.

But I can't seem to get this to work when I have multiple text fields that I want to live update to multiple span tags. For example:

I want this input to live update to the below span tag:

<input type="text" class="inst_name">

<span class="nametag"></span>

and I want this input to live update this span tag:

<input type="text" class="keypair_name">

<span class="keyname"></span>

But when I do, it works with the first one (the inst_name to nametag) but when I try it with the second one (keypair_name to keyname) it keeps showing up in my html as undefined where the text should be live updating to but the code doesn't actually produce any errors.

Below is the JavaScript code I have tried:

var inputKeyName = document.querySelector(".keypair_name"),
outputKeyName = document.querySelector(".keyname"),
inputInstName = document.querySelector(".inst_name"),
outputInstName = document.querySelector(".nametag");

function keydownHandler() {
    outputKeyName.innerHTML = inputKeyName.value;
}

function keydownHandlerInstName() {
    outputInstName.innerHTML = inputInstName.value;
}

inputKeyName.addEventListener("input", keydownHandler);
inputInstName.addEventListener("input", keydownHandlerInstName);

Any ideas on how I can get this to work would be much appreciated. Thanks

question from:https://stackoverflow.com/questions/65860233/live-update-multple-input-fields-to-multiple-span-tags

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So I have found out the problem. A rookie mistake of using the same name twice in my html. I had used the same name for a class name of "inst_name" for my input field as well as a div elsewhere in my code that I didn't realise were named exactly the same. Thanks for commenting and confirming this was working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...