I'm very new but I've completed some courses on freecodecamp. Say that I make an object about cars. I want the webpage user to be able to write "Ford Mustang" and after this all the information stored in the object fordMustang pops up for the user to read.
I've tried some different tactics but cant get it to work. Here is the code I have written,
<label for="navn">
<input type="text" id="field" name="navn">
<input type="submit" value="send" id="send" >
</label> <p id="par"> </p>
let fordMustang = {
producer: "Ford",
type: "Mustang",
engine: "v8",
horsePower: 300 }
const inputField = document.querySelector(".field");
const press = document.querySelector("#send");
const para = document.querySelector("#par");
function objScan() {
const word = String(inputField.value);
if (word == "Ford Mustang") {
para.textContent = fordMustang;
}
else {
para.textContent = "Not recognized"
}
}
press.addEventListener("click", objScan);
CodePudding user response:
You can use JSON.stringify()
to achieve this.
You need to replace para.textContent = fordMustang;
with JSON.stringify(fordMustang);
let fordMustang = {
producer: "Ford",
type: "Mustang",
engine: "v8",
horsePower: 300 }
const inputField = document.querySelector(".field");
const press = document.querySelector("#send");
const para = document.querySelector("#par");
function objScan() {
const word = String(inputField.value);
if (word == "Ford Mustang") {
para.textContent = JSON.stringify(fordMustang);
}
else {
para.textContent = "Not recognized"
}
}
press.addEventListener("click", objScan);
<label for="navn">
<input type="text" id="field" value="Ford Mustang" name="navn">
<input type="submit" value="send" id="send" >
</label> <p id="par"> </p>
CodePudding user response:
You are almost there. You just need to change your const para
identifier from id
to class
. And add some meaningful line breaks or any style you wish to show it inside the tag using innerHTML
let fordMustang = {
producer: "Ford",
type: "Mustang",
engine: "v8",
horsePower: 300
}
const inputField = document.querySelector(".field");
const para = document.querySelector(".par");
function objScan() {
const word = String(inputField.value);
if (word == "Ford Mustang") {
let result = ""
Object.entries(fordMustang).map(entries => result = entries[0] ": " entries[1] "<br>")
para.innerHTML = result
} else {
para.textContent = "Not recognized"
}
}
<label for="navn">
<input type="text" id="field" name="navn" value="Ford Mustang">
<input type="submit" value="send" id="send" onclick="objScan()">
</label>
<p id="par" > </p>