javascript missing statement woes - javascript

I'm trying to calculate a form based on values provided, I've written the script but it says missing; before statement
Here's my code if anyone can see the error please help point it out.
<script type="text/javascript">
function calc(theForm) {
var myEquip1 = document.Edit.EQup1.value;
var myEquip2 = document.Edit.EQup2.value;
Var myFixedPrice = document.Edit.InitialPrice.value;
Var myEquip1Price = document.Edit.EQup1Price.value;
Var myEquip2Price = document.Edit.EQup2Price.value;
if (myEquip1 > 1)
{
var myEquip1Total = (myEquip1*myEquip1Price) - (myEquip1Price);
}
else
{
var myEquip1Total = (myEquip1*myEquip1Price)-(myEquip1Price);
}
if (myEquip2 > 1)
{
var myEquip2Total = (myEquip2*myEquip2Price)-(myEquip2Price);
}
else
{
var myEquip2Total = (myEquip2*myEquip2Price)-(myEquip2Price);
}
theForm.GrandTotal.value = (myEquip2Total+myEquip1Total+myFixedPrice)
}
</script>
The HTML is below i'm sure I've done something wrong but i can see it.
<form name="Edit" method="post" action="mypageprocess">
<p><label for="EQup1">How many Branches?</label><br />
<select name="EQup1" onChange="calc(this.form)" id="EQup1"/>
<option value="0">Please select</option>
<option value="1" >One</option>
<option value="2" >Two</option>
<option value="3" >Three</option>
<option value="4" >Four</option>
<option value="5" >Five</option>
</select> x <strong>$550.00</strong>
</p>
<p><label for="EQup2">How many Satellits?</label><br />
<select name="EQup2" onChange="calc(this.form)" id="EQup2"/>
<option value="0">Please select</option>
<option value="1" >One</option>
<option value="2" >Two</option>
<option value="3" >Three</option>
<option value="4" >Four</option>
<option value="5" >Five</option>
</select> x <strong>$440.00 </strong>
</p>
<input type="text" onfocus="this.blur();" name="GrandTotal" size="10" readonly="readonly"/>
<input type="hidden" name="InitialPrice" value="660" />
<input type="hidden" name="EQup1Price" value="550" />
<input type="hidden" name="EQup2Price" value="440" />
</form>
Thank you

JavaScript is case sensitive. Var won't work, use var.

Both of your <select> elements are being closed prematurely as if they have no inner content.

Related

How to limit count of checked checkboxes equal to select value using jquery?

I'm trying to limit the amount of checkboxes able to be checked according to what select option the user chooses i.e. option1 = 1 checkbox option 2 = 2 checkboxes and if they try to choose more then alert the user and .prop("checked", false).
but i just get weird stuff happening and i can't figure why please help!!
html:
<form>
<select onclick="systemSelected();" class="mySelectBox">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
<option value="5">option5</option>
</select>
</form>
<form onclick="limitCheckbox(userSelected);">
<input type="checkbox" name="box1">
<input type="checkbox" name="box2">
<input type="checkbox" name="box3">
<input type="checkbox" name="box4">
<input type="checkbox" name="box5">
</form>
javascript:
var userSelected = 0;
function systemSelected() {
$(".mySelectBox option").each(function(){
if ($(this.selected)) {
userSelected = parseInt($(".mySelectBox").val());
}
});
}
function limitCheckbox(userSystem) {
$("input[type=checkbox]").click(function(){
if($("input[type=checkbox]:checked".length > userSystem)) {
$(this).prop("checked", false);
alert("too many numbers");
} else if ($("input[type=checkbox]:checked".length === 0 )) {
alert("please select a game too play");
}
});
}
Don't use alerts (Why should a user feel stupid)
Use the disabled property (Make a user see & know)
var $ckb = $('[name*=box]'),
$sel = $('.mySelectBox');
function ckkk () {
var ckd = $ckb.filter(":checked").length,
max = parseInt($sel.val(), 10);
if(ckd > max) $ckb.prop({checked:false, disabled:false});
else $ckb.not(":checked").prop({disabled: ckd >= max});
}
$ckb.add($sel).on("change", ckkk);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="mySelectBox">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
<option value="5">option5</option>
</select>
<input type="checkbox" name="box1">
<input type="checkbox" name="box2">
<input type="checkbox" name="box3">
<input type="checkbox" name="box4">
<input type="checkbox" name="box5">
use $("input[type=checkbox]").on('change',function(){ selector which will fire event on every change of checkbox. And you can manage your cases with conditions in it.
Please check below snippet.
var userSelected = 0;
$("input[type=checkbox]").on('change',function(){
if($("input[type=checkbox]:checked").length > parseInt($(".mySelectBox").val())) {
$(this).prop("checked", false);
alert("too many numbers");
} else if ($("input[type=checkbox]:checked").length === 0 ) {
alert("please select a game too play");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select class="mySelectBox">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
<option value="5">option5</option>
</select>
</form>
<form>
<input type="checkbox" name="box1">
<input type="checkbox" name="box2">
<input type="checkbox" name="box3">
<input type="checkbox" name="box4">
<input type="checkbox" name="box5">
</form>
$('input:checkbox').change(function() {
var number = $('.mySelectBox option:selected').val();
if ($('input:checkbox:checked').length > number) {
alert('more than selected')
$(this).prop('checked', false);//dont check the click checkbox
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select class="mySelectBox">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
<option value="5">option5</option>
</select>
</form>
<form>
<input type="checkbox" name="box1">
<input type="checkbox" name="box2">
<input type="checkbox" name="box3">
<input type="checkbox" name="box4">
<input type="checkbox" name="box5">
</form>

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>

Blocking 'submit' on a form

I am creating a form:
<input type="checkbox" id="chk1">1<select name="sel1" id="sel1" class="sel">
<option value="..."></option>
<option value="a">a</option>
<option value="b">b</option>
<input type="text" name="txt1" id="txt1" class="txt"/><br />
<input type="checkbox" id="chk2">2<select name="sel2" id="sel2" class="sel">
<option value="..."></option>
<option value="a">a</option>
<option value="b">b</option>
<input type="text" name="txt2" id="txt2" class="txt"/><br/>
<input type="checkbox" id="chk3">3<select name="sel3" id="sel3" class="sel">
<option value="..."></option>
<option value="a">a</option>
<option value="b">b</option>
<input type="text" name="txt3" id="txt3" class="txt"/><br />
<button type="submit" class="btn btn-default">Submit</button>
And I am trying to create a block on the submit button so that if a checkbox is checked: the textbox can't be empty, and the dropdown has to have a different value than '...' If either of those is the case, user clicks 'submit' and nothing should happen...if all is satisfied though, then they click submit, and it goes through.
Javascript/jQuery logic I'm aiming for is something like
if ($(":checkbox:checked").length != 0) {
if ($(".txt").val === ("")) {
return false;
}
else {return true}
if ($(".sel").val === "...") {
return false;
}
else {return true}
}
DEMO
First of all I would like to correct your html and do wrap each checkbox,input, select in a group element so that you can easily get its corresponding values. You select had syntax error and select is not a self closing tag like <select/> instead it is <select>..</select>. Hence below is the updated code:
<form id="frmDetails">
<div class="container"> <!--wrap them in each container-->
<input type="checkbox" id="chk1" value="1"/>
<select name="sel1" id="sel1" class="sel">
<option value="0">Select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<input type="text" name="txt1" id="txt1" class="txt"/><br />
</div>
<div class="container">
<input type="checkbox" value="2" id="chk2"/>
<select name="sel2" id="sel2" class="sel">
<option value="0">Select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<input type="text" name="txt2" id="txt2" class="txt"/><br/>
</div>
<div class="container">
<input type="checkbox" id="chk3" value="3"/>
<select name="sel3" id="sel3" class="sel">
<option value="0">Select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<input type="text" name="txt3" id="txt3" class="txt"/><br />
</div>
<button type="submit" class="btn submit btn-default">Submit</button>
</form>
Then your js would be as below:
var valid; //A global variable to check the validation
function validate(){
valid=true; //set it to true at beginning
$.each($('#frmDetails input:checkbox'),function(){
//loop through each checkbox
if($(this).is(":checked")) //if it is checked
{
var selected=$(this).siblings('select').find('option:selected').val()
//get selected value of its select element
var text=$(this).siblings('input').val();
//get value entered in its corresponding textbox
if(text=="" || selected=="0") if text="" or selected value=0
{
valid=false;//set valid to false
return valid;//return it
}
}
});
return valid; //else this will be true
}
$(".submit").on('click',function(e){
e.preventDefault(); //prevent default action of submit
if(validate()) //validate returns true or false
{
$("#frmDetails").submit(); //submit the form if valid
}
else
{
alert('Form is invalid, You cannot submit it');
//do whatever your want here
}
});
event.preventDefault() will do that blocking for you. It will prevent the form to get submitted. Instead of returning false like native javascript. Collect that returning result in a cache variable then execute event.preventDefault() when it evaluated to false.
use Jquery to prevent form submitting
$("button[type='submit']").on("click", function(e){
e.preventDefault();
if ($(":checkbox:checked").length != 0) {
if ($(".txt").val === ("")) {
return false;
}
else {$("#myForm").submit();
}
if ($(".sel").val === "...") {
return false;
}
else {$("#myForm").submit();}
}
});

Add Up All Javascript Divs For Total Amount

Okay, So I have a javascript function setup to add a div with an ID up and total it, and have the value displayed at the top. Well It works fine and all, But Due to it being multiple Id's I'm confused on how to get the total number!
function GetCost(ID) {
var cost = $('#Cost'+ID).val();
var income = $('#Income'+ID).val();
var owned = $('#Own'+ID).val();
var new_cost = number_format(cost * owned / 10 + 1000);
$('#PropCost'+ID).html('Cost: $'+new_cost);
$('#TotalIncome').html(number_format(income * owned));
}
As you can see it's with a Div plus an ID. Well here's the HTML with multiple divs. They're split up with different Id's Such as: owned1 And then for instance owned2.
<!-- Property Start-->
<div id="PropBlock">
<form action="javascript:void" method="post">
<div id="PropName">News Stand</div>
<div align="center"><img src="http://cdn0.mobwarsapp.com/rpg_images/opensocial/mob/ingame/territory/big/newsstand.gif" /></div>
<div id="PropIncome">Income: $100</div>
<div id="PropCost1" class="PropCost">Cost: $1,000</div>
<div id="PropOwn" align="center">
Own: <input type="text" ID="Own1" value="0" size="3" maxlength="5" onkeyup="GetCost(1)" />
</div>
<div id="PropBuy">
<select id="Numbers1">
<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>
</select>
<input type="submit" value="Calculate" onClick="CalcProp(1)" />
<input type="hidden" id="Cost1" value="1000" />
<input type="hidden" id="Income1" value="100" />
<input type="hidden" id="Name1" value="News Stand" />
</form>
</div>
</div>
<!-- Property End -->
<!-- Property Start-->
<div id="PropBlock">
<form action="javascript:void" method="post">
<div id="PropName">Empty Lot</div>
<div align="center"><img src="http://cdn0.mobwarsapp.com/rpg_images/opensocial/mob/ingame/territory/big/empty_lot.gif" /></div>
<div id="PropIncome">Income: $100</div>
<div id="PropCost2" class="PropCost">Cost: $4,500</div>
<div id="PropOwn" align="center">
Own: <input type="text" ID="Own2" value="0" size="3" maxlength="5" onkeyup="GetCost(2)" />
</div>
<div id="PropBuy">
<select id="Numbers2">
<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>
</select>
<input type="submit" value="Calculate" onClick="CalcProp(2)" />
<input type="hidden" id="Cost2" value="4500" />
<input type="hidden" id="Income2" value="100" />
<input type="hidden" id="Name2" value="Empty Lot" />
</div>
</form>
</div>
<!-- Property End -->
Here's The Income Div.
<div id="Basic" align="center">Basic Properties: (Income: $<span id="TotalIncome">0</span>)</div>
Well, How it's a onkeyup Function, When I change the form for the property1. It will display the math total. But if I change the form for property2 it will display the total math for property 2. How would I have it add the 2 up and display the total for both added up? I'm going to have about 15 different ones and when you change the value, So I'm kind of confused on what to do, Please help!! Thanks!!
To understand what I'm talking about, Here's my sites link: http://psychowars.net/addtrain/property_cost
I'm not exactly sure what you want. Assuming you want to get the total (sum of all income*owned) and put it on #TotalIncome, Here you have (replace your GetCost by all this):
//Just calculates. Doesn't affect UI
function getCostsById(ID) {
var cost = $('#Cost'+ID).val();
var income = $('#Income'+ID).val();
var owned = $('#Own'+ID).val();
var new_cost = cost * owned / 10 + 1000;
return {
cost: cost,
income: income,
owned: owned,
new_cost: new_cost
};
}
//I assume total is sum of every income*owned
function getTotalCost(){
var total = 0;
for(var id=1; id<=10; id++){
var costs = getCostsById(id)
total += costs.income * costs.owned;
}
return total;
}
//This affects UI
function GetCost(ID){
var costs = getCostsById(ID);
$('#PropCost'+ID).html('Cost: $'+number_format(costs.new_cost) );
$('#TotalIncome').html(number_format(getTotalCost()));
}
Cheers, from La Paz, Bolivia
The #TotalIncome is revised with only the income from the most recently edited property. It needs to also include all the other property locations when calculating the total. Just revamp the calculated function.
$('#TotalIncome').html((income * owned));
To this:
var sum = 0;
$('[id^="Own"]').each(function(){
var id = $(this).attr('id');
id = id.replace("Own","");
sum += (( $('#Income'+id).val())*$('#Own'+id).val())
});
$('#TotalIncome').html(sum);

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 :)

Categories