Home > Back-end >  How to use input value in object [javascript]
How to use input value in object [javascript]

Time:06-06

I'd like to get User input(name) by onChange function by get element's value, and want to print it by using jQuery .html

but in browser it keep show like:

text [object HTMLInputElement]' text

var getUserName=()=>{var userName= document.getElementById("userName").value }

var getname = {"something": {"character": "text"   userName   "text"},

$("#character").html(getName[something]["character"]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="userName" onchange="javascript:getUserName()"/>

CodePudding user response:

Besides the unbalanced quotes, and unbalanced braces, different spellings of variable names, referencing something as a variable instead of a string literal, ...etc, etc, you need to move the code that you want to execute upon the event, all inside that event handler.

Correction:

var getUserName = () => {
    var userName= document.getElementById("userName").value;
    var getName = {"something": {"character": "text"   userName   "text"}};
    $("#character").html(getName["something"]["character"]);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="userName" onchange="getUserName()"/><button>Enter</button>
<div id="character"></div>

Some other remarks:

  • Using jQuery just for this is overkill, as you can just assign to .textContent. But if you're going to use jQuery any way, then use it to the full (so no document.getElementById then...)

  • Don't use html() when you are only planning to assign text, not HTML.

  • Bind your event handler via code, not via HTML attribute, and at least drop the "javascript:" prefix, as that creates a label (see this).

CodePudding user response:

put double quotation for something too may work

  • Related