I’m stuck with this one! When I alert the object that I stringify the gender’s value stays the same all the time! How to change this to work?
I have this piece of code:
<!DOCTYPE HTML>
<html>
<head>
<title>Practical 2 - exercise</title>
<script type="text/javascript">
function myJSONobj(){
var JSONObject={
"name" : document.getElementById("name").value,
"surname" : document.getElementById("surname").value,
"email" : document.getElementById("eMail").value,
"gender" : document.getElementById("gender").value
};
var jsonstr=JSON.stringify(JSONObject);
alert(jsonstr);
var jobjson=JSON.parse(jsonstr);
alert(jobjson.gender);
}
</script>
</head>
<body>
<form method="post" action="display.php">
<p>
Your name:
</br>
<input type="text" id="name" name="theName" placeholder="Fill in your name" autofocus="autofocus" required="required"/>
</p>
<p>
Your surname:
</br>
<input type="text" id="surname" name="theSurname" placeholder="Fill in your surname" required="required"/>
</p>
<p>
Your email:
</br>
<input type="email" id="eMail" name="theMail" placeholder="mail@mail.com" required="required"/>
</p>
<p> Please select your gender:
<br/>
<input type="radio" id="gender" name="gender" value="M" /> M
<input type="radio" id="gender" name="gender" value="F" required="required" /> F
</p>
<input onClick="myJSONobj();" type="button" id="theSubmit" name="theSubmit" value="Fire away!!"/>
</form>
</body>
</html>
By all means test it and see what it does!
Thank you!
The element id must be unique into a page, so the first error is use the same id for 2 different radio. Use a unique id:
Then to retrieve the selected gender into your myJSONobj function use must use something like:
or (a little bit more generic):