Reputation: 21
I've been trying to replace part of the header with the input from the text field. When a user enters zip code the text would read "GREAT NEWS! WE HAVE A LOCATION IN 12345".
<h4>GREAT NEWS! WE HAVE A LOCATION IN YOUR AREA. <span id="zipPrint"></span></h4>
function myFunction() {
var x = document.getElementById("zipNumber");
var text = " ";
var i;
for (i = 0; i < x.length ;i++) {
$('#hide-me').hide();
text += .replace("YOUR AREA", x.elements[i].value);
}
document.getElementById("zipPrint").innerHTML = text;
}
Upvotes: 1
Views: 1033
Reputation: 4783
In order to make manipulating the DOM
simpler for us, here's how the h4
tag will look like:
<h4>GREAT NEWS! WE HAVE A LOCATION IN <span id="zipPrint">YOUR AREA.</span></h4>
Now the span
tag that will display the zip code contains the text "YOUR AREA." that will be replaced by the zip code.
var zipNum = document.getElementById("zipNumber"), zipPr = document.getElementById("zipPrint");
zipNum.addEventListener('blur', function myFunction() {
var zc = this.value.trim();
zipPr.textContent = (zc.length && !isNaN(zc)) ? zc:'YOUR AREA.';
});
<h4>GREAT NEWS! WE HAVE A LOCATION IN <span id="zipPrint">YOUR AREA.</span></h4>
<input id="zipNumber"/>
Explanations:
A blur
event listener is attached to the input
tag with id="zipNumber"
that handles the process of writing the zip code in the h4
tag.
The anonymous function that handles the event checks if the input
has a valid number in it: if so, the value of the input
is placed in the span
tag, else, if the value of the input
is empty or doesn't represent a valid number, the string "YOUR AREA."
is placed in the span
tag.
Hope I pushed you further.
Upvotes: 0
Reputation: 5486
You can use the span you set yourself up for. No need to use replace. Here I added an event listener on the input (which you can change if needed) that will replace the span in the text when you click out of the input.
document.getElementById("zipNumber").addEventListener("change",myFunction);
function myFunction() {
let zip = this.value;
// do some zip validation if needed
document.getElementById("zipPrint").innerHTML = zip;
}
<h4>GREAT NEWS! WE HAVE A LOCATION IN <span id="zipPrint">YOUR AREA</span></h4>
<input id="zipNumber"/>
Upvotes: 1
Reputation: 1089
The text +=
line looks wrong to me. I think you need this instead.
var text = "GREAT NEWS! WE HAVE A LOCATION IN YOUR AREA.";
text = text.replace("YOUR AREA", x.elements[i].value);
That way, "YOUR AREA"
gets replaced by the location number, and that result gets assigned to the variable text
.
Upvotes: 2