Reputation:
I have only started to learn JS and I'm a bit stuck. So I have an HTML code + JS to change the
value but it doesn't work and I have no idea why... Thanks for help ^^
<p class="username">T</p>
<input type="text" class="usernameValue">
<button onclick="usernameChange()">Change</button>
function usernameChange(){
var usernameValue = document.querySelector('.usernameValue').value;
var username = document.querySelector('.username').innerHTML;
username = usernameValue;
}
Oh I'm so dumb, thanks everyone for the help
Upvotes: 1
Views: 671
Reputation: 3863
There doesn't appear to be a div with a class of username, so add that if it's not in your code.
You misspelled onclick
inside of <button onclick="usernameChange()">Change</button>
You'll also want to capture the element itself rather than a reference to innerHTML
, and then set the element's innerHTML to your value.
var username = document.querySelector('.username');
username.innerHTML = usernameValue;
function usernameChange(){
var usernameValue = document.querySelector('.usernameValue').value;
var username = document.querySelector('.username');
username.innerHTML = usernameValue;
}
<div class="username"></div>
<input type="text" class="usernameValue">
<button onclick="usernameChange()">Change</button>
Upvotes: 0
Reputation: 27119
username
is not a reference to the actual string. If you want to change the innerHTML
of the element with class username
you need to explicitly say so
document.querySelector('.username').innerHTML = usernameValue;
Also, you have a typo in your html. It should be onclick
, not onlick
.
Upvotes: 4
Reputation: 68393
You are assigning the one string to another, it doesn't update the element's innerHTML
, you need to do
document.querySelector('.username').innerHTML = usernameValue ;
You also need to change onlick
to onclick
, refer to the demo below.
Demo
function usernameChange(){
var usernameValue = document.querySelector('.usernameValue').value;
document.querySelector('.username').innerHTML = usernameValue;
}
<p class="username" id="username">T</p>
<input type="text" class="usernameValue">
<button onclick="usernameChange()">Change</button>
Upvotes: 3
Reputation: 7437
It's supposed to be <button onclick="usernameChange()">Change</button>
not <button onlick="usernameChange()">Change</button>
Upvotes: 0