Reputation: 609
I am working on HTML and Javascript.
I have a label which you can see below
<label for="optGender">Gender: </label>
<input id="optGender" type="radio" name="optGender" value="F" onclick="changeGender(this.value)">
Female
<br>
<input id="optGender" type="radio" name="optGender" value="M" onclick="changeGender(this.value)">
Male
<br>
Where do you want to live?
<br>
<select id="txtCity" name="lstCity" size="5">
<option value="06">Ankara</option>
<option value="34">Istanbul</option>
<option value="35">Izmir</option>
<option value="27">Gaziantep</option>
</select>
<br>
and in my javascript file I have this function to check whether its checked or not
function changeGender(whichOne){
var gender = document.forms["ProcessInfo"]["optGender"].value;
var optGender = document.getElementById("optGender");
var txtCity = document.getElementById("txtCity");
if ( !document.getElementById('optGender').checked )
{
errMessage += "Please select your gender.\n";
document.getElementById('optGender').checked = false;
}
//if ( gender == "M" ) { alert("lol");}
}
When I select "Female" button, it works, doesn't give an error. But when I choose male, it gives me an error that I havent selected any option. What is wrong with that?
Edit * What I actually want to do is, If I select F the list will have the cities which starts with I, for M its going to be G. I can easily handle this part, but I'm stuck at easiest part.
Upvotes: 0
Views: 201
Reputation: 1450
you have the same ID for both inputs. That won't work... Document.getelementbyid returns the first instance it finds the id you provided, which is the male input. I think what you might want here is a select instead of an input...
Give me a second and I'll modify your code for you.
<label for="optGender">Gender: </label>
<input id="Female" type="radio" name="optGender" value="F" onclick="changeGender(this)">
Female
<br>
<input id="Male" type="radio" name="optGender" value="M" onclick="changeGender(this)">
Male
<br>
Where do you want to live?
<br>
<select id="txtCity" name="lstCity" size="5">
<option value="06">Ankara</option>
<option value="34">Istanbul</option>
<option value="35">Izmir</option>
<option value="27">Gaziantep</option>
</select>
<br>
function changeGender(whichOne){
var gender = whichOne.value;
if ( gender == "M" ) { alert("lol");}
if ( gender == "F" ) { alert("wat");}
}
Upvotes: 3
Reputation: 7256
You cannot have 2 elements with the same id
in HTML
. You have 2 elements with same id ie optGender
.
Upvotes: 0