Why doesn't my object display when I call it? - javascript

var section = [];
var name = [];
var gender = [];
var age = [];
var favsub = [];
var studRec = { section, name, gender, age, favsub };
function saveButton() {
section.push = document.getElementById("section").value;
name.push = document.getElementById("name").value;
gender.push = document.getElementById("gender").value;
age.push = document.getElementById("age").value;
favsub.push = document.getElementsByClassName("favsub");
document.getElementById("saveStud").reset();
window.alert(studyRec);
}
<body>
<form id="saveStud" method="POST">
<center>
<p>Section</p>
<select id="section" autofocus required>
<option value="0">select</option>
<option value="truth">truth</option>
<option value="faith">faith</option>
<option value="honesty">honesty</option>
<option value="charity">charity</option>
<option value="obedience">obedience</option>
</select><br>
<p>Student Name</p><input id="name" type="text" required><br>
<p>Gender</p>
<select id="gender">
<option value="M">Male</option>
<option value="F">Female</option>
</select><br>
<p>Age</p><input id="age" type="number" required><br>
<p>Favorite Subjects</p><input class="favsub" type="text" required><br>
<input class="favsub" type="text" required><br>
<input class="favsub" type="text" required><br>
<button type="button" onclick="saveButton()">save</button>
<button type="reset" value="reset">reset</button>
</center>
</form>
</body>
The purpose of the code is to get the information from the form then when you press save the values will be put in their separate arrays which are in an object, and the values on the form will reset. To test if the function works I tried to display it using document.write but when I do press the save button, it just resets but doesn't display

section.push,name.push and so on is wrong syntax. Apparently it mean if section and name is a object then section.push or so will create key in that object, but here they are not object.
Also var studRec= {section, name, gender,age,favsub}; does not make any sense unless you are looking for object destructing and this object syntax is wrong.
You can just add keys to studRec inside saveButton function & there is a typo at window.alert(studyRec);
document.getElementsByClassName("favsub") will gives a collection and you need to get the index to retrieve value from it.Also if you want to alert alert(studRec) you will only see object object
var section = [];
var name = [];
var gender = [];
var age = [];
var favsub = [];
var studRec = {
};
function saveButton() {
studRec.section = document.getElementById("section").value;
studRec.name = document.getElementById("name").value;
studRec.gender = document.getElementById("gender").value;
studRec.age = document.getElementById("age").value;
studRec.favsub = document.getElementsByClassName("favsub");
document.getElementById("saveStud").reset();
alert(studRec);
}
<form id="saveStud" method="POST">
<center>
<p>Section</p>
<select id="section" autofocus required>
<option value="0">select</option>
<option value="truth">truth</option>
<option value="faith">faith</option>
<option value="honesty">honesty</option>
<option value="charity">charity</option>
<option value="obedience">obedience</option>
<option value="chastity">chastity</option>
<option value="generosity">generosity</option>
<option value="humility">humility</option>
</select><br>
<p>Student Name</p><input id="name" type="text" required><br>
<p>Gender</p>
<select id="gender">
<option value="M">Male</option>
<option value="F">Female</option>
</select><br>
<p>Age</p><input id="age" type="number" required><br>
<p>Favorite Subjects</p><input class="favsub" type="text" required><br>
<input class="favsub" type="text" required><br>
<input class="favsub" type="text" required><br>
<button type="button" onclick="saveButton()">save</button>
<button type="reset" value="reset">reset</button>
</center>
</form>

Add all the items to the object and then send it.
If you're getting the element by class name then you need to iterate over by length and then get the value.
Check the below code.
I've included the examples if you're pushing into an array or if you want to assign a value to an object also. Try understanding the code first.
var section = [];
var name = [];
var gender = [];
var age = [];
var favsub = [];
var studyRec= {section, name, gender,age,favsub};
function saveButton(){
studyRec.section=document.getElementById("section").value;
studyRec.name=document.getElementById("name").value;
studyRec.gender=document.getElementById("gender").value;
studyRec.age =document.getElementById("age").value;
studyRec.favsub.push(document.getElementsByClassName("favsub")[0].value);
studyRec.favsub.push(document.getElementsByClassName("favsub")[1].value);
studyRec.favsub.push(document.getElementsByClassName("favsub")[2].value);
document.getElementById("saveStud").reset();
console.log(studyRec);
}
<form id="saveStud" method="POST">
<center>
<p>Section</p><select id="section" autofocus required>
<option value="0">select</option>
<option value="truth">truth</option>
<option value="faith">faith</option>
<option value="honesty">honesty</option>
<option value="charity">charity</option>
<option value="obedience">obedience</option>
<option value="chastity">chastity</option>
<option value="generosity">generosity</option>
<option value="humility">humility</option>
</select><br>
<p>Student Name</p><input id="name" type="text" required><br>
<p>Gender</p><select id="gender">
<option value="M">Male</option>
<option value="F">Female</option>
</select><br>
<p>Age</p><input id="age" type="number" required><br>
<p>Favorite Subjects</p><input class="favsub" type="text" required><br>
<input class="favsub" type="text" required><br>
<input class="favsub" type="text" required><br>
<button type = "button" onclick="saveButton()">save</button>
<button type="reset" value="reset">reset</button>
</center>
</form>

Related

View option picked from datalist

I would like to take the option of which the user selects from a datalist. This is what I have:
<input type="text" name="my-input" class="searchBar" list="my-list">
<input id="clickMe" type="button" value="clickme" onclick="handleSelect();" />
<datalist id="my-list">
<option value="COMP232"></option>
<option value="COMP248"></option>
<option value="ENGR201"></option>
</datalist>
My JS method:
function handleSelect()
{
var elm = document.getElementById("my-list").innerHTML.value;
console.log(elm);
//window.location = "./class/" + elm.toUpperCase() + ".php";
}
The console responds "undefined" when I submit. What is wrong here?
You can assign an id to input and take a value of id on button click.
<input id= "inp" type="text" name="my-input" class="searchBar" list="my-list">
<input type="button" value="clickme" onclick="handleSelect();" />
<datalist id="my-list">
<option value="COMP232"></option>
<option value="COMP248"></option>
<option value="ENGR201"></option>
</datalist>
and JS code snippet will look like,
var elm = document.getElementById("inp").value;
Your code should be like this.
<script>
function handleSelect(){
var elment = document.getElementById("selectedValue").value;
console.log(elment);
}
</script>
<input id="selectedValue" type="text" name="my-input" class="searchBar" list="my-list">
<input id="clickMe" type="button" value="clickme"
onclick="handleSelect();" />
<datalist id="my-list">
<option value="COMP232"></option>
<option value="COMP248"></option>
<option value="ENGR201"></option>
</datalist>

jquery add values dropdown using data attribute

I have a simple HTML form:
<div class="form-group">
<label class="control-label col-md-2">Monday<span class="required"> * </span></label>
<div class="col-md-5">
<select name="monday_main" id="monday_main_list" class="form-control">
<option value=""></option>
<option value="Carlow" data-staff="1" data-price="100" data-km="100" data-call="200" >Carlow</option>
<option value="Cavan" data-staff="1" data-price="100" data-km="100" data-call="200" >Cavan</option>
</select>
</div>
<div class="col-md-5">
<select name="monday_side" id="monday_side_list" class="form-control">
<option value=""></option>
<option value="Dublin" data-staff="1" data-price="200" data-km="200" data-call="400" >Dublin</option>
<option value="Galway" data-staff="1" data-price="200" data-km="200" data-call="400" >Galway</option>
</select>
</div>
</div>
<input type="number" placeholder="" value="" name="amountPrice" id="amountPrice">
<input type="number" placeholder="" value="" name="amountKm" id="amountKm">
<input type="number" placeholder="" value="" name="amountCall" id="amountCall">
<input type="number" placeholder="" value="" name="amountStaff" id="amountStaff">
What I need to achieve is to calculate values for each data attribute separately (e.g. separate value for data-staff, data-price, data-km and data-call) on changing options and then displaying values in 4 separate input fields.
I am not sure even if it is possible, but if so I would be very grateful if someone could help me
// good idea to cache elements you'll be re-using
var dropdowns = $('select'),
inputPrice = $('#amountPrice'),
inputKm = $('#amountKm'),
inputCall = $('#amountCall'),
inputStaff = $('#amountStaff');
// attach 'onchange' event handler to all dropdowns
dropdowns.change(function () {
var amountPrice = 0,
amountKm = 0,
amountCall = 0,
amountStaff = 0;
// for each dropdown, tally amounts
dropdowns.each(function () {
// get selected option
var option = $('option:selected', this);
amountPrice += parseInt(option.data('price'), 10);
amountKm += parseInt(option.data('km'), 10);
amountCall += parseInt(option.data('call'), 10);
amountStaff += parseInt(option.data('staff'), 10);
});
// set inputs
inputPrice.val(amountPrice);
inputKm.val(amountKm);
inputCall.val(amountCall);
inputStaff.val(amountStaff);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-md-2">Monday<span class="required"> * </span></label>
<div class="col-md-5">
<select name="monday_main" id="monday_main_list" class="form-control">
<option value=""></option>
<option value="Carlow" data-staff="1" data-price="100" data-km="100" data-call="200" >Carlow</option>
<option value="Cavan" data-staff="1" data-price="100" data-km="100" data-call="200" >Cavan</option>
</select>
</div>
<div class="col-md-5">
<select name="monday_side" id="monday_side_list" class="form-control">
<option value=""></option>
<option value="Dublin" data-staff="1" data-price="200" data-km="200" data-call="400" >Dublin</option>
<option value="Galway" data-staff="1" data-price="200" data-km="200" data-call="400" >Galway</option>
</select>
</div>
</div>
<input type="number" placeholder="" value="" name="amountPrice" id="amountPrice">
<input type="number" placeholder="" value="" name="amountKm" id="amountKm">
<input type="number" placeholder="" value="" name="amountCall" id="amountCall">
<input type="number" placeholder="" value="" name="amountStaff" id="amountStaff">
I am not sure if I follow your question but you can access to those data with a change listener.
$('#monday_main_list').on('change', function() {
if($(this).val()!=='') {
var selectedOption = $(this).find('option[value=' + this.value + ']').first();
if (selectedOption) {
var data = selectedOption.data();
console.log(data);
}
}
})

JSP form not submitting on button click

Hello I am new to JSP Programming. I have been given a task where I create a personal loan application form. When a user enters all the details in the form and hits submit the form gets stored in the database. I have created the form and all the required JSP pages and connectivity statements. My problem is that when I give values and click on submit nothing happens. It is staying in the same page. I don't know where the problem is. Please help me out. Thanks in advance.
Application form.jsp
<%# page language="java" import="java.util.Random"%>
<%!
public int generateRandomNumber(int start, int end ){
Random random = new Random();
long fraction = (long) ((end - start + 1 ) * random.nextDouble());
return ((int)(fraction + start));
}
%>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function changeContents(){
var dropDown = document.getElementById("employmenttype");
var showDetails = document.getElementById("salariedType");
showDetails.style.display = dropDown.value == "salaried" ? "block" : "none";
var elements = document.getElementById("employmenttype");
var businessDetails = document.getElementById("selfEmployedType");
businessDetails.style.display = elements.value == "self_employed_business" ? "block" : "none";
}
</script>
<title>Bank</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Welcome to Bank</h1>
<p></p>
</div>
<form action="personalloanhandler.jsp" method="POST">
<div class="row">
<div class="col-md-3">
Your Application ID: <input type="text" name="app_id" value="<%=generateRandomNumber(10000,99999)%>" />
</div>
<div class="col-md-6">
</div>
<div class="col-md-5">
Full Name:*
<input class="form-control" name="fullname" type="text" />
<br><br>
Mobile No.:*
<input name="mobilenumber" class="form-control" type="text" pattern="[7-9]{1}[0-9]{9}" title="ex:9870367035"required />
<br><br>
Email_ID:*<input name="email" class="form-control" type="email" title="ex:hari21#gmail.com" required />
<br><br>
Pancard NO:*<input name="pan" class="form-control" type="text" pattern="[A-Za-z]{5}\d{4}[A-Za-z]{1}" title="ex:AIAPY3476G" required />
<br><br>
Gender: <input class="form-control"
name="gender" type="radio">Male
<input class="form-control"name="gender" type="radio">Female
<br><br>
Date OF Birth (DD/MM/YYYY):<input class="form-control" type="date" name="seldob" required>
<br><br>
Age*<input class="form-control"name="age" type="text" required />
<br><br>
Address* <textarea class="form-control" name="address" rows="2" cols="20" required>
</textarea>
<br><br>
City*<input class="form-control" name="city" id="focusedInput" type="text" required />
<br><br>
State*
<select name="state" onchange ="showText(this.value)">
<option value="">Select</option>
<option value='Andamans and Nicobar' >Andamans and Nicobar</option><option value='Andhra Pradesh' >Andhra Pradesh</option><option value='Arunachal Pradesh' >Arunachal Pradesh</option><option value='Assam' >Assam</option><option value='Bihar' >Bihar</option><option value='Chandigarh (UT)' >Chandigarh (UT)</option><option value='Chhattisgarh' >Chhattisgarh</option><option value='Dadra and Nagar Haveli' >Dadra and Nagar Haveli</option><option value='Daman Dui' >Daman Dui</option><option value='Delhi' >Delhi</option><option value='Goa' >Goa</option><option value='Gujarat' >Gujarat</option><option value='Habra' >Habra</option><option value='Haryana' >Haryana</option><option value='Himachal Pradesh' >Himachal Pradesh</option><option value='Jammu and Kashmir' >Jammu and Kashmir</option><option value='Jharkhand' >Jharkhand</option><option value='Karnataka' >Karnataka</option><option value='Kerala' >Kerala</option><option value='Madhya Pradesh' >Madhya Pradesh</option><option value='Maharashtra' >Maharashtra</option><option value='Manipur' >Manipur</option><option value='Meghalaya' >Meghalaya</option><option value='Mizoram' >Mizoram</option><option value='Nagaland' >Nagaland</option><option value='Odisha' >Odisha</option><option value='Puducherry' >Puducherry</option><option value='Punjab' >Punjab</option><option value='Rajasthan' >Rajasthan</option><option value='Sikkim' >Sikkim</option><option value='Tamil Nadu' >Tamil Nadu</option><option value='Telangana' >Telangana</option><option value='Tripura' >Tripura</option><option value='Uae' >Uae</option><option value='Uttar Pradesh' >Uttar Pradesh</option><option value='Uttarakhand' >Uttarakhand</option><option value='West Bengal' >West Bengal</option>
</select>
Pincode* <input class="form-control" id="focusedInput" type="text" required />
<br><br>
Type of employment*
<select name="employmenttype" id="employmenttype"
class="employer-info" onchange="changeContents()">
<option value="">Select</option>
<option value="salaried" id="salaried" >Salaried</option>
<option value="self_employed_business" id="self_employed_business">Self Employed business</option>
</select><br/></div>
<div id="salariedType" class="employer-info" style="display:none;">
<br/>Retirement age:*<input class="employer-info" name="retirementage"
id="focusedInput" type="text" required />
<br><br>
Date of joining:*<input class="employer-info" name="doj"
id="focusedInput" type="text" required />
<br><br>
Experience:<select class="form-control" name="workexperience">
<option value="select">Select</option>
<option value="0"> <1 </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">>10</option>
</select>
<br><br>
</div>
<br><br>
<div id = "self_employed_business" style="display:none">
TIN no:*<input class="form-control" name="tin" id="focusedInput" type="text" required /><br/>
<br><br>
Net profit (annually):*<input class="form-control" name="profit" id="focusedInput" type="text" required /><br/><br/>
</div>
<div class="form-control" id="salariedType1" style="display:none;">
<br/>Employer name:*
<select name="employer_name" id="focusedInput"
class="employer-info">
<option value="">Select</option>
<option value="IBM" >IBM</option>
<option value="Fujitsu" >Fujitsu</option>
<option value="CSC" >CSC</option>
<option value="Accenture" >Accenture</option>
<option value="Northrop Grumman" >Northrop Grumman</option>
<option value="Hitachi" >Hitachi</option>
<option value="Capgemini" >Capgemini</option>
<option value="NTT Data Corporation" >NTT Data Corporation</option>
<option value="NEC" >NEC</option>
<option value="Ericsson" >Ericsson</option>
<option value="BT Global Services" >BT Global Services</option>
<option value="Atos Origin" >Atos Origin</option>
<option value="T-Systems" >T-Systems</option>
<option value="Siemens" >Siemens</option>
<option value="Lockheed Martin" >Lockheed Martin</option>
<option value="Nokia Siemens Networks" >Nokia Siemens Networks</option>
<option value="SAIC" >SAIC</option>
<option value="Microsoft" >Microsoft</option>
<option value="ACS" >ACS</option>
<option value="Huawei" >Huawei</option>
<option value="Dell" >Dell</option>
<option value="Logica" >Logica</option>
<option value="General Dynamics" >General Dynamics</option>
<option value="Alcatel-Lucent" >Alcatel-Lucent</option>
<option value="Self Employed Professional">Self Employed
Professional</option>
</select><br/><br/>
</div>
Monthly Income<input class="form-control" id="focusedInput" type="text" name="monthly_income" required />
<br><br>
Reason for loan:*
<select class="form-control" name="reason_for_loan">
<option value="select">Select</option>
<option value="newcar">Car</option>
<option value="marriage">Marriage</option>
<option value="Other">Other</option>
</select>
<br><br>
Total years of work experience:*
<select class="form-control" name="experience">
<option value="select">Select</option>
<option value="0"> <1 </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">>10</option>
</select>
<br><br>
Tenure:*<input name="loan_tenure" type="text" class="form-control"required />
<br><br>
Loan Amount:*<input type="text" name="loan_amt" class="form-control" required />
<br/><br/>
ROI:10.5<input name="emi" type="text" value=10.5 class="form-control" disabled>
<br><br>
EMI:* <input name="emi" type="text" class="form-control" required />
<br><br>
Guarantor Name:*<input name="guarantorname" type="text" class="form-control" required />
<br><br>
Guarantor's Annual income(Rs):*<input name="guarantor_address" class="form-control" type="text"required />
<br><br>
Guarantor's Phone number:*<input name="guarantor_contact" class="form-control" type="text"required />
<br><br>
Existing customer:* <input class="form-control" name="cust_gender" type="radio" value="yes">Yes
<input class="form-control" name="cust_gender" type="radio">No<br/>
<br><br>
<input class="form-control" type="checkbox"required /> I agree with terms & conditions:*
<br><br>
Savings account number:*<input class="form-control" name="acc_no" type="text"required >
<br><br>
<input type="submit" value="Submit" name="personalloanhandler" />
</div>
</form>
</div>
<script>
$(document).ready(function() {
$("#divLoanApplicationForm").hide();
$("#salariedType").hide();
$("#selfEmployedType").hide();
});
$("#salaried").click(function(e){
$("#divLoanApplicationForm").hide();
$("#salariedType").show();
$("#selfEmployedType").hide();
});
$("#self_employed_business").click(function(e){
$("#divLoanApplicationForm").show();
$("#salariedType").hide();
$("#selfEmployedType").show();
});
/*$("#employmenttype").ready(function(e) {
var value=$("#employmenttype").val();
$("#divLoanApplicationForm").show();
if(value=="SALARIED")
{
$("#selfEmployedType").hide();
$("#salariedType").show();
}
if(value=="SELF_EMPLOYED_BUSINESS")
{
$("#selfEmployedType").show();
$("#salariedType").hide();
}
});*/
</script>
</body>
</html>
The Jsp Page(personalloanhandler.jsp):
<%# page language="java" import="java.sql.*"%>
<%
String appid = request.getParameter("app_id");
String mobileNumber = request.getParameter("mobilenumber");
String emailId = request.getParameter("email");
String pancardNumber = request.getParameter("pan");
String applicantGender = request.getParameter("gender");
String dateofBirth = request.getParameter("seldob");
String applicantAddress = request.getParameter("address");
String cityofResidence = request.getParameter("city");
String stateofResidence = request.getParameter("state");
String typeofEmployment = request.getParameter("employmenttype");
String retirementAge = request.getParameter("retirementage");
int retiringAge = Integer.parseInt(retirementAge);
String dateofJoining = request.getParameter("doj");
String workExperience = request.getParameter("workexperience");
int experienceinWork = Integer.parseInt(workExperience);
String tinNo = request.getParameter("tin");
int tin = Integer.parseInt(tinNo);
String netProfit = request.getParameter("profit");
int profit = Integer.parseInt(netProfit);
String employeeName = request.getParameter("employer_name");
String monthlyIncome = request.getParameter("monthly_income");
int monthIncome = Integer.parseInt(monthlyIncome);
String reasonforLoan = request.getParameter("reason_for_loan");
String totalworkExpreience = request.getParameter("experience");
int workExperienceTotal = Integer.parseInt(totalworkExpreience);
String loanTenure = request.getParameter("loan_tenure");
int tenure = Integer.parseInt(loanTenure);
String loanAmount = request.getParameter("loan_amt");
int loanAmt = Integer.parseInt(loanAmount);
String guarantorName = request.getParameter("guarantorname");
String guarantorAddress = request.getParameter("guarantor_address");
String guarantorContact = request.getParameter("guarantor_contact");
int guarantorNo = Integer.parseInt(guarantorContact);
String emiAmount = request.getParameter("emi");
int emiAmt = Integer.parseInt(emiAmount);
String savingsaccntNumber = request.getParameter("acc_no");
int accNo = Integer.parseInt(savingsaccntNumber);
String applicantName = request.getParameter("fullname");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hr","themoonwalker");
PreparedStatement prepare = conn.prepareStatement("INSERT INTO BOI_Personal_loan_app-form values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
prepare.setString(1,appid);
prepare.setString(2,mobileNumber);
prepare.setString(3,emailId );
prepare.setString(4,pancardNumber );
prepare.setString(5,applicantGender);
prepare.setString(6,dateofBirth );
prepare.setString(7,applicantAddress);
prepare.setString(8,cityofResidence);
prepare.setString(9,stateofResidence);
prepare.setString(10,typeofEmployment);
prepare.setInt(11,retiringAge);
prepare.setString(12,dateofJoining);
prepare.setInt(13,experienceinWork);
prepare.setInt(14,tin);
prepare.setInt(15,profit);
prepare.setString(16,employeeName);
prepare.setInt(17,monthIncome);
prepare.setString(18,reasonforLoan);
prepare.setInt(19,workExperienceTotal);
prepare.setInt(20,tenure);
prepare.setInt(21,loanAmt);
prepare.setString(22,guarantorName);
prepare.setString(23,guarantorAddress );
prepare.setInt(24,guarantorNo );
prepare.setInt(25,emiAmt );
prepare.setInt(26,accNo);
prepare.setString(27,applicantName );
int i = prepare.executeUpdate();
if (i > 0){
out.println("Success");
}
}catch(Exception e){
System.out.println("Sorry couldn't process the request. Please try again");
}
out.close();
%>
I have included the necessary jar files and everything in the project. Please help
tin and profit inputs are required but not visible, so you can't submit the form
<div id = "self_employed_business" style="display:none">
TIN no:*<input class="form-control" name="tin" id="focusedInput" type="text" required /><br/>
<br><br>
Net profit (annually):*<input class="form-control" name="profit" id="focusedInput" type="text" required /><br/><br/>
</div>

Onchange wont work for select when table form is at start

I am having a problem with a form and using an onchange for a select in that form. When I start the form right before the 2 selects it works wonderfully, but when I move the form outside the table (to include everything), the onchange will not work. Any ideas as to why?
Here is my form:
<table border="0" class="signUp">
<tr><td align="center" class= "signUpfont"> Sign up for FREE </td></tr>
<tr><td><input type="text" text="First Name" class='signUpinput' id="fname" name="fname" placeholder="First Name" /></td></tr>
<tr><td><input type="text" class='signUpinput' id="lname" name="lname" placeholder="Last Name"/></td></tr>
<tr><td><input type="text" class='signUpinput' id="email" name="email" placeholder="Email"/></td></tr>
<tr><td><input type="text" class='signUpinput' id="email2" name="email2" placeholder="Re-enter Email"/></td></tr>
<tr><td><input type="password" class='signUpinput' id="pass" name="pass" placeholder="Password"/></td></tr>
<tr><td><form name="form1" action="submit.php" method='POST'>
<select name="country" onchange="window.getSchools()" style="color: white; background-color: #2B4478;">
<option value="0">Select State</option>
<option value="louisiana">Louisiana</option>
<option value="texas">Texas</option>
<option value="alabama">Alabama</option>
<option value="mississippi">Mississippi</option>
</select>
<br>
<select name="school" style="color: white;background-color: #2B4478;">
<option value="">Select School</option>
</select></td></tr>
<tr><td><input type="submit" name="submit" value="Sign Up" style="color:white; background-color:#2B4478; width: 100px;margin-left: 52px;"></td></tr>
</form>
</table>
and here is my onchange function:
<script type="text/javascript">
function getSchools()
{
var xmlhttp;
try{
xmlhttp = new XMLHttpRequest;
}catch(e)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp)
{
var form = document['form1'];
var country = form['country'].value;
xmlhttp.open("GET", "getSchools.php?country="+country, true);
xmlhttp.onreadystatechange = function ()
{
if(this.readyState == 4)
{
var s = document.createElement('select');
s.name = "school";
s.style.color = "white";
s.style.background = "#2b4478";
s.innerHTML = this.responseText;
if(form['school'])
{
form.replaceChild(s, form['school']);
}else
form.insertBefore(s, form['submit']);
}
}
xmlhttp.send(null)
}
}
Your event is not being fired because you do not explicitly define 'window.getSchools'. So you have two options.
Option 1
Fix the onchange inline handler:
<select name="country" onchange="getSchools()">
<option value="0">Select State</option>
<option value="louisiana">Louisiana</option>
<option value="texas">Texas</option>
<option value="alabama">Alabama</option>
<option value="mississippi">Mississippi</option>
</select>
Define your event:
getSchools = function()
{
//put your code here
alert("fired");
}
Option 2
Keep your same html:
<select name="country" onchange="window.getSchools()">
<option value="0">Select State</option>
<option value="louisiana">Louisiana</option>
<option value="texas">Texas</option>
<option value="alabama">Alabama</option>
<option value="mississippi">Mississippi</option>
</select>
Fix your event handler:
window.getSchools = function()
{
//put your code here
alert("fired");
}
You can see the official documentation here
You also have malformed HTML. You close the element before closing the element. See this jsFiddle for a working example.
I would definitely suggest going through the JavaScript documentation, it may seem tedious when starting out, but trust me when I say that it will save you quite literally days of your life in debugging and troubleshooting :)

Get array values from an option select with javascript to populate text fields

I have a form where the user can make an "instant search" with ajax, and the search result are shown as "select... option" tags, when the user choose an option, it's value will populate a text field. The "simplified" version of the code is this:
<form action="action.php" method="post" name="form1" id="form1">
Code: <input type="text" name="Code" value="" size="32" readonly="readonly" /> <br />
<select class="paselect" onchange="form1.elements['Code'].value = this.options[this.selectedIndex].value;">
<option value="2413">2413 - Name A</option>
<option value="2414">2414 - Name B</option>
<option value="2415">2415 - Name C</option>
</select>
</form>
You can also check it on line: http://jsfiddle.net/BCXfQ/
Now, I need to get TWO values for each option select, like this:
<form action="action.php" method="post" name="form1" id="form1">
Code: <input type="text" name="Code" value="" size="32" readonly="readonly" /> <br />
Name: <input type="text" name="Name" value="" size="32" readonly="readonly" /> <br />
<select class="paselect" onchange="form1.elements['Code'].value = this.options[this.selectedIndex].value;">
<option value="['Name A', '2413']">2413 - Name A</option>
<option value="['Name B', '2414']">2414 - Name B</option>
<option value="['Name C', '2415']">2415 - Name C</option>
</select>
</form>
But I don't know how to get the array values and populate the two fields one with Code and the other with Name.
Online: http://jsfiddle.net/zm3nX/
I tried since now to change
form1.elements['Code'].value = this.options[this.selectedIndex].value
to
form1.elements['Code'].value = this.options[this.selectedIndex].value[0]
and to
form1.elements['Code'].value = this.options[this.selectedIndex[0]].value
but with no luck.
Thanks for any help.
Have you considered using data attributes instead?
Code: <input type="text" id="foo-code" name="Code" value="" size="32" readonly="readonly" /> <br />
Name: <input type="text" id="foo-name" name="Name" value="" size="32" readonly="readonly" /> <br />
<select class="paselect" id="foo-list">
<option data-name="Name A" data-code="2413">2413 - Name A</option>
<option data-name="Name B" data-code="2413">2413 - Name B</option>
<option data-name="Name C" data-code="2413">2413 - Name C</option>
</select>
and glue things together:
var select = document.getElementById("foo-list");
var code = document.getElementById("foo-code");
var name = document.getElementById("foo-name");
select.addEventListener('change', function(event) {
code.value = this.getAttribute("data-code");
name.value = this.getAttribute("data-name");
}, false);
You can do something like:
<script>
function updateValues(el) {
var form = el.form;
var v = el.value;
v = v.replace(/^\[\'|\'\]$/g,'').split("', '");
form.Code.value = v[1];
form.Name.value = v[0];
}
</script>
<form action="action.php" method="post" name="form1" id="form1">
Code: <input type="text" name="Code" size="32" readonly> <br>
Name: <input type="text" name="Name" size="32" readonly> <br>
<select class="paselect" onchange="updateValues(this);">
<option value="['Name A', '2413']">2413 - Name A
<option value="['Name B', '2413']">2413 - Name B
<option value="['Name C', '2413']">2413 - Name C
</select>
</form>
Note that in IE if the user navigates the options using the cursor keys, an onchange event will be dispatched every time they move focus to a different option. Other browsers will wait for an option to actually be chosen with tab or space (depending on the browser).
Yeah I'd take an approach similar to the way Angular does this - using jquery with rodneyrehm's example:
<select class="paselect" id="foo-list">
<option data-name="Name A" data-code="2413">2413 - Name A</option>
<option data-name="Name B" data-code="2413">2413 - Name B</option>
<option data-name="Name C" data-code="2413">2413 - Name C</option>
</select>
$('#foo-list').change(function() {
var opt = $(this.options[this.selectedIndex]);
var name = opt.attr('data-name');
var code = opt.attr('data-code');
$('#status').text('Name: ' + name + ', Code: ' + code);
});
http://jsfiddle.net/b9chris/mbSLB/
This avoids the potentially flimsy regex; strings you store and what to escape when become simpler to consider and error check.
The data- prefix is just there to comply with the HTML5 spec, but the truth is you can make up whatever attribute names you like - so if you were generating this HTML on the server and wanted to keep it short you could even use a= and b=.
Try this
<form action="action.php" method="post" name="form1" id="form1">
Code: <input type="text" name="Code" value="" size="32" readonly="readonly" /> <br />
Name: <input type="text" name="Name" value="" size="32" readonly="readonly" /> <br />
<select class="paselect" onchange="getValue(this.value);">
<option value="Name A-2413">2413 - Name A</option>
<option value="Name B-2413">2413 - Name B</option>
<option value="Name C-2413">2413 - Name C</option>
</select>
</form>
<script>
function getValue(val){
var myval=val.split('-');
form1.elements['Code'].value=myval[1];
form1.elements['Name'].value=myval[0];
}
</script>
Use this code.
<script>
function setdata(selectvalue, selecttext){
form1.elements['Code'].value = selectvalue;
form1.elements['Name'].value = selecttext;
}
</script>
<form action="action.php" method="post" name="form1" id="form1">
Code: <input type="text" name="Code" value="" size="32" readonly="readonly" /> <br />
Name: <input type="text" name="Name" value="" size="32" readonly="readonly" /> <br />
<select class="paselect" onchange="setdata(this.value,this.options[this.selectedIndex].text)">
<option value="['Name A', '2413']">2413 - Name A</option>
<option value="['Name B', '2414']">2414 - Name B</option>
<option value="['Name C', '2415']">2415 - Name C</option>
</select>
</form>
Hope it helps to you.

Categories