In the sample code below, note that the value of the variable dependent
depends on the variable prereq
. When the function changePrereq
is called, it changes the value of prereq
. This change is shown if logged, but it isn't reflected in the value of dependent
. Instead, when dependent
is put into a span, it shows Some text - undefined
.
How can I have dependent
change depending on the value of prereq
?
var display = document.getElementById('text'),
prereq,
message = "Some text - " prereq;
function updateDisplay() {
display.innerHTML = message;
console.log(prereq);
}
function changePrereq() {
prereq = "I am some text.";
updateDisplay();
}
<p><span id="text"></span></p>
<button onclick="changePrereq()">Click</button>
CodePudding user response:
The problem is that changeMyText
doesn't update when someText
does. You need to define changeMyText
inside of the changeTextFunc
function and then pass someText
as a parameter.
Example:
var myText = document.getElementById('text');
var someText1;
var m1 = 1;
function changeTextFunc(someText, m) {
var changeMyText = "Some text - " someText;
if (m > 0) {
myText.innerHTML = changeMyText;
} else {
console.log('m < 0');
}
}
function changeText() {
someText1 = "I a'm some text.";
changeTextFunc(someText1, m1);
}
<div>
<button onclick="changeText()">Click</button>
<p id="text"></p>
</div>
CodePudding user response:
move changeMyText variable into changeTextFunc function. the code will looks like this
function changeMyText(m){
var changeMyText = "Some text - " someText1;
if (m > 0) {
myText.innerHTML = changeMyText;
} else {
console.log('m < 0');
}
}