I'm trying to input text in a field, and have it output to multiple fields.
Currently, it only outputs to the first field.
Here's the input:
<form class="form" onchange="myFunction()">
<div class="mb-4">
<p>The quick sly fox jumped over the <input id="object" class="inline borderless-input"></p>
</div>
</form>
function myFunction()
{
//Object
var x = document.getElementById("object");
var div = document.getElementById("objectDisplay");
div.innerHTML = x.value;
}
ID's have to be unique. Use classes and a for
loop to cycle through each one and change it.
This cannot be done with document.getElementById
. See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById for some basic information about document.getElementById
. document.getElementsByClassName
returns an array filled with existing elements with a certain class. In this case, objectDisplay
. If you want to read more about that then take a look here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName.
The new code should look like this:
function myFunction() {
//Object
var x = document.getElementById("object");
var div = document.getElementsByClassName("objectDisplay");
for (i = 0; i < div.length; i++) {
div[i].innerHTML = x.value;
}
}
.container {
padding: 10px;
}
.text-strong {
font-weight: bold;
}
.inline {
display: inline;
}
.borderless-input {
background-color: transparent;
border-style: solid;
border-width: 0px 0px 1px 0px;
padding: .5rem .75rem;
text-align: center;
}
<div class="container">
<div class="row">
<div class="col-lg-12">
<form class="form" onchange="myFunction()">
<div class="mb-4">
<p>The quick sly fox jumped over the <input id="object" class="inline borderless-input"></p>
</div>
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h3><strong>Output</strong></h3>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<p>The quick sly fox jumped over the <span class="objectDisplay inline"></span>.</p>
<p>The quick sly fox jumped over the <span class="objectDisplay inline"></span>.</p>
<p>The quick sly fox jumped over the <span class="objectDisplay inline"></span>.</p>
</div>
</div>
</div>
<!-- For Testing Only -->
<div class="container">
<div class="row">
<div class="col-lg-10 offset-lg-1 mx-auto">
<!-- Test Here -->
</div>
</div>
</div>