user8690818
user8690818

Reputation:

Changing <p> value onclick doesn't work

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

Answers (4)

Khauri
Khauri

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

Federico klez Culloca
Federico klez Culloca

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

gurvinder372
gurvinder372

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

Alf Moh
Alf Moh

Reputation: 7437

It's supposed to be <button onclick="usernameChange()">Change</button> not <button onlick="usernameChange()">Change</button>

Upvotes: 0

Related Questions