0

I'm at very beggining stage and I'd like to know something.. Is there a way to set a variable like this (or a similiar way)?

<body>

<button id="button1" onclick="change(this.something);"> click me </button>
<button id="button2" onclick="change(this.lorem);"> or this one </button>
<div id="target"> change this content </div>

<script>
function change(variable)
{
document.getElementById("target").innerHTML = variable;
}
</script>
</body>

or something like this

<body>

<button id="button1" onclick="change(this.value(v1));"> click me </button>
<button id="button2" onclick="change(this.value(v2));"> or this one</button>

<div id="target"> change this content </div>

<script>
function change(value)
{
var v1 = "something";
var v2 = "lorem";

document.getElementById("target").innerHTML = variable;
}
</script>

of course both are not working.. just don't know how to find an answer.

2 Answers 2

4

Perhaps you mean to pass a string literal to the function, i.e. change('literal text'):

function change(variable) {
  document.getElementById("target").innerHTML = variable;
}
<button id="button1" onclick="change('something');"> click me </button>
<button id="button2" onclick="change('lorem');"> or this one </button>
<div id="target"> change this content </div>

Sign up to request clarification or add additional context in comments.

Comments

0

If you intent to set the contents of the div to something or lorem, then you should pass those using a string literal instead of trying to access a property on this.

<button id="button1" onclick="change('something');"> click me </button>
<button id="button2" onclick="change('lorem');"> or this one </button>

Using a string literal passes a String containing the value specified to the change function whereas using this.something is a property accessor which will try to get the value of the something property on the this object.

In your second example, you can't use v1 and v2 from the onclick handler because those variables are scoped inside your change function and aren't accessible from the outside.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.