I am VERY knew to Javascript & HTML, just started studying IT and this is my first assessment. Essentially, the task is - provide a dropdown list and an age input box, provide a "Submit" button and add an alert box with JS that shows if the user has entered the correct details to proceed. (New Zealand and 18 (or higher) being the "correct" answers to proceed - other country options and lower than 18 get a rejection alert answer)
Here is my HTML so far:
<body>
<form method="get">
<select id="country" name="country">
<option value="0">PLEASE SELECT YOUR COUNTRY</option>
<option value="1">New Zealand</option>
<option value="2">Australia</option>
<option value="3">Switzerland</option>
</select>
<input type="number" id="dob">
</form>
<button type="button" id="submit" >SUBMIT</button>
<script src="test.js"></script>
</body>
I have tried using Javascript (var as below) and also function(which I got confused with and deleted):
var select = document.getElementById("country");
document.getElementById("button").onclick = function(){
var value = select.value
if (value == "1")
{
alert("Thanks");
}
if (value == "2")
{
alert("sorry");
}
if (value == "3")
{
alert("sorry");
}
if (value == "0")
{
alert("sorry");
}
};
CodePudding user response:
Your id in document.getElementById("button").onclick is wrong. the id is submit not button
var select = document.getElementById("country");
document.getElementById("submit").onclick = function(){
var value = select.value
if (value == "1")
{
alert("Thanks");
}
if (value == "2")
{
alert("sorry");
}
if (value == "3")
{
alert("sorry");
}
if (value == "0")
{
alert("sorry");
}
};
I've refactored your code. It should run like this
const select = document.getElementById("country");
const inp = document.getElementById("dob");
document.getElementById("submit").onclick = function(){
const selected = select.value;
const dob = parseInt(inp.value);
if( selected === "1" && dob >= 18 ){
alert("Thanks");
} else {
alert("Sorry");
}
};
<form method="get">
<select id="country" name="country">
<option value="0">PLEASE SELECT YOUR COUNTRY</option>
<option value="1">New Zealand</option>
<option value="2">Australia</option>
<option value="3">Switzerland</option>
</select>
<input type="number" id="dob">
</form>
<button type="button" id="submit" >SUBMIT</button>