Javascrip code wont run properly.

Joined
Oct 2, 2022
Messages
1
Reaction score
0
i always get error:
Uncaught ReferenceError: colourChosen is not defined
html:27:15
Untitled-6 (Isnt working).html:22 Uncaught ReferenceError: animalRadio is not defined
at HTMLButtonElement.onclick
createAnimal @ Untitled-6 (Isnt working).html:22
onclick @ Untitled-6 (Isnt working).html:16
the code is:
<html>
<body>
<select id="colour">
<option>red</option>
<option>yellow</option>
<option>purple</option>
<option>orange</option>
<option>green</option>
</select>
<form id="animals">
<input type="radio" name="animals" value="elephant">Elephant <br>
<input type="radio" name="animals" value="tortoise">Tortoise <br>
<input type="radio" name="animals" value="dolphin">Dolphin <br>
<input type="radio" name="animals" value="kangroo">Kangroo <br>
</form>
<button onclick="createAnimal ()">Create the animal</button>
<script>
function createAnimal () {
var dropDownName = document.getElementById("colour");
var colourChosen = dropDownName.options[dropDownName.selectedIndex].text;
for(i=0; i<4; i++){
if(animalRadio.checked) {
var animalChosen = animalRadio.value;
}
}
}
alert(colourChosen + " " + animalChosen);
</script>
</body>
</html>
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
You need to globalize your vars. Right now they are available only within your function createAnimal

Try this:
Code:
var dropDownName,colourChosen,animalChosen=false;
function createAnimal () {
dropDownName = document.getElementById("colour");
colourChosen = dropDownName.options[dropDownName.selectedIndex].text;
for(i=0; i<4; i++){
if(animalRadio.checked) {
 animalChosen = animalRadio.value;
 }
 }
 }

!!NOTICE!!
animalRadio still not defined. Where is it in your code?
 
Joined
Nov 13, 2020
Messages
302
Reaction score
38
MeMate is correct that the values you use in the alert are not defined outside of the function and that you should make them global. But you could also place the alert inside the function and things work out fine for that This will work
Code:
<script>
function createAnimal () {
    var dropDownName = document.getElementById("colour");
    var colourChosen = dropDownName.options[dropDownName.selectedIndex].text;

    for(i=0; i<4; i++){
        if(animals[i].checked) {
            var animalChosen = animals[i].value;
        }
    }
alert(colourChosen + " " + animalChosen);
}
</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top