Otherwise, I want their original value.
Basic desired outcome: For this example, type a name to see the result. Erase the name and I want it to say “[empty]” instead of the name (in the text below the field). If I type the name again it should show the name again.
I am using “span” in a larger program so I used it in this example just in case, regardless the result should be the same.
EDIT: nevermind, this is false. The result is not the same. I need it to work when “span” is in the declared variable.
I am having a huge issue here. if/else statements are not working and I have tried all variations of ternary arguments.
I got this working halfway by doing the following after declaring nameHere, however, it would not return to having the inputted name value when it was entered:
var empty = null; var nameHere = empty || "[empty]";
Here is some sample code of what I have right now:
function getResponse() { var resultValue = "Hello my name is " + nameHere + ", nice to meet you."; document.getElementById("result").innerHTML = resultValue; var nameHere = (nameHere === null) ? `<span>${"[EMPTY]"}</span>` : `<span>${document.getElementById("name").value}</span>`; }
<div class="formclass"> <label for="name">Input name here</label> <input id="name" onchange="getResponse()"></input> </div> <div id="result"></div>
Advertisement
Answer
Please run following snippet. Once you type a name, it will be printed in the result div, once you erase EMPTY will be shown instead.
function getResponse(){ let val = document.getElementById("name").value if (!val.length) val = "[empty]"; var resultValue = "Hello my name is " + val + ", nice to meet you."; document.getElementById("result").innerHTML = resultValue; }
<div class="formclass"> <label for="name">Input name here</label> <input id="name" onInput="getResponse()"></input> </div> <div id="result"></div>