Reputation: 403
I need to store an input data from several fields into JS variables and then paste them in a text. Here is my code which doesn't seem to be working for some reason.
These are input fields:
<ul id="listings">
<li><input type="text" id="adjectives1" value="Adjective"></li>
<li><input type="text" id="adjectives2" value="Adjective"></li>
<li><input type="text" id="adjectives3" value="Adjective"></li>
</ul>
And here is that text:
<div id="textualdiv"> As the <span id="adjective1">fatal</span> mating dance of a pair of black holes with a total mass of more than a billion suns. Mostly in the form of <span id="adjective2">violent</span> in space-time known as <span id="adjective3">gravitational</span> waves.</div>
</div>
Here is JS script:
<script>
var adjective1 = document.getElementById("adjectives1").value;
var adjective2 = document.getElementById("adjectives2").value;
var adjective3 = document.getElementById("adjectives3").value;
</script>
<script>
document.getElementById('adjective1').innerHTML = adjective1;
document.getElementById('adjective2').innerHTML = adjective2;
document.getElementById('adjective3').innerHTML = adjective3;
</script>
It only pastes default "Adjective" values in the text which are already present in the input fields. But if I type something else it doesn't change the text, but keeps showing Adjective word.
Upvotes: 0
Views: 64
Reputation: 562
you can hook an onchange
event to the inputs so that when you change anything in the input, you change the innerHTML
on the span tags.
<input type="text" id="adjectives1" value="Adjective" onchange="document.getElementById('adjective1').innerHTML = this.value;">
Upvotes: 0
Reputation: 388316
You need to use a change event handler, which will update the target element content on change of the input value.
function update(el){
var value = el.value;
document.getElementById(el.id.replace('adjectives', 'adjective')).innerHTML = value;
}
<ul id="listings">
<li><input type="text" id="adjectives1" value="Adjective" onchange="update(this)"></li>
<li><input type="text" id="adjectives2" value="Adjective" onchange="update(this)"></li>
<li><input type="text" id="adjectives3" value="Adjective" onchange="update(this)"></li>
</ul>
<div id="textualdiv"> As the <span id="adjective1">fatal</span> mating dance of a pair of black holes with a total mass of more than a billion suns. Mostly in the form of <span id="adjective2">violent</span> <span id="noun3">ripples</span> in space-time known as <span id="adjective3">gravitational</span> waves.</div>
Upvotes: 3