I'm designing an application that collects input from the users via a form. Based on the input, the application will search the array objects for corresponding value and display the value to the users.
I'm stuck at the process of selecting a particular value in the array objects. Below is a simplified version of my application. The array objects have 2 attributes: gender (male/female) and work status (full-time/part-time).
I named a variable called "gender" to convert the user's input into index (0 or 1), and use that index in the .val() to identify the object (male/female).
if($('#inputgender').val()=="Male"){var gender=0;}
if($('#inputgender').val()=="Female"){var gender=1;}
Using the same approach, I named another variable called "workstatus" to convert the user's input into the name of the array (fulltime or parttime), but .val() could not read that variable. It read data[gender].workstatus as undefined.
if($('#inputworkstatus').val()=="Full-time"){var workstatus="fulltime";}
if($('#inputworkstatus').val()=="Part-time"){var workstatus="parttime";}
console.log(data[gender].workstatus);
$("#outputbox").text("Your number is " + data[gender].workstatus);
Any better way to build this application assuming my dataset is slightly bigger than the example used here, with maybe 4 or 5 attributes (age, country, marriage status)?
Thanks.
Below is the full code.
<head>
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
</head>
<body>
<form name="myForm" id="workForm" method="get" action="#">
Your gender:<br>
<SELECT NAME="gender" SIZE="1" id="inputgender">
<OPTION>Male
<OPTION>Female
</SELECT>
<br><br>
Your work status:<br>
<SELECT NAME="workstatus" SIZE="1" id="inputworkstatus">
<OPTION>Full-time
<OPTION>Part-time
</SELECT>
<br><br>
<input type="submit" value="Submit"/>
<INPUT TYPE="reset">
</form>
<span id="outputbox"></span>
</body>
<script type="text/javascript">
var data = [{"gender":"male","fulltime":10,"parttime":20},
{"gender":"female","fulltime":30,"parttime":40}];
$(document).ready(function(){
$("form").submit(function( event ) {
if($('#inputgender').val()=="Male"){var gender=0;}
if($('#inputgender').val()=="Female"){var gender=1;}
if($('#inputworkstatus').val()=="Full-time"){var workstatus="fulltime";}
if($('#inputworkstatus').val()=="Part-time"){var workstatus="parttime";}
console.log(data[gender].workstatus);
$("#outputbox").text("Your number is " + data[gender].workstatus);
event.preventDefault();
});
});
</script>
</option>tags