-2

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()"/>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Henry lee
  • 1
  • 1
  • I helped you a little on the formatting here... But edit again to make it reproduce your issue. You have at least a missing `#character` element in the HTML and a typo on `getName`. – Louys Patrice Bessette Jun 05 '22 at 16:47

2 Answers2

1

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).

trincot
  • 317,000
  • 35
  • 244
  • 286
-3

put double quotation for something too may work

Hasan Rabiee
  • 31
  • 1
  • 8