Alert message won't work using jquery - javascript

I created a form with the code below. There is a problem that I am unable to solve. The problem is the alert message won't work when the submit button is clicked.
$(document).ready(function() {
$("#btn_id").click(function() {
var valid = validate();
var name_order = $("#name").val();
var address_order = $("#address").val();
var city_order = $("#city").val();
var state_order = $("#state").val();
var zipcode_order = $("#zipcode_id").val();
var phone_order = $("#phone_id").val();
var email_order = $("#emailid").val();
var randID_order = $("#generateID").val();
var ICCID_order = $("#ID").val();
if (valid) {
$("form[name='workorder']").submit();
alert(" Name :" + name_order + " \n Address : " + address_order +
" \n City : " + city_order + " \n State: " + state_order +
" \n Zipcode: " + zipcode_order + " \n Phone: " + phone +
" \n Email: " + email_order + " \n ID: " + randID_order +
" \n SIM Card: " + ICCID_order)
}
});
// Give Alert if field not enter
function validate() {
if (document.workorder.name.value == "") {
alert("Please provide your Name!")
document.workorder.name.focus();
return false;
}
if (document.workorder.address.value == "") {
alert("Please provide your Address!")
document.workorder.address.focus();
return false;
}
if (document.workorder.city.value == "") {
alert("Please provide your City!")
document.workorder.city.focus();
return false
}
if (document.workorder.state.value == "-1") {
alert("Please select your State!")
document.workorder.state.focus();
return false
}
if (document.workorder.zipcode.value == " ") {
alert("Please provide your Zipcode!")
document.workorder.zipcode.focus();
return false;
}
if (document.workorder.phone.value == " ") {
alert("Please provide your Phone!")
document.workorder.zipcode.focus();
return false;
}
var email = document.workorder.emailid.value;
atpos = email.indexOf("#")
dotpos = email.lastIndexOf(".")
if (email == " " || atpos < 1 || (dotpos - atpos < 2)) {
alert("Please provide your Zipcode!")
document.workorder.emailid.focus();
return false;
}
console.log("validated");
return (true);
}
// Generate an random ID
function randomString() {
var string_length = 8;
var chars = "abcdefghijklmnopqrstuvwvxyz012345678";
var text = " ";
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
text += chars.substring(rnum, rnum + 1);
}
document.workorder.randomfield.value = text;
}
// Generate box with ID and CCID
function getData() {
var fs = require('fs');
var ICCID = require('./masterlist.json')
if (ICCID.length != 0) {
var index = Math.floor(Math.random() * ICCID.length);
var pickedID = ICCID[index];
ICCID.splice(index, 1); // This removes the picked element from the array
fs.writeFile("masterlist.json", JSON.stringify(ICCID), function(err) {
if (err) {
return consolo.log(err);
}
});
} else {
console.log("Sorry, There is no more ICCID to complete the form");
}
document.workorder.ID.value = pickedID
}
});
<html>
<head>
<title>Work Order Form</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script type="text/javascript" src="validate.js"></script>
</head>
<body>
<form action="#" name="workorder" id="form_id">
<table cellpadding="2" width="300" height="300" bgcolor=g reen align="center" cellspaceing="2">
<tr>
<td colspan=2>
<center>
<fontsize=4><b>Work Order Form</b>
</font>
</center>
</td>
</tr>
<tr>
<td>Name</td>
<td>
<input type="text" name="name" id="name" size="30" align="center">
</td>
</tr>
<tr>
<td>Address</td>
<td>
<input type="text" name="address" id="adress" size="30">
</td>
</tr>
<tr>
<td>City</td>
<td>
<input type="text" name="city" id="city" size="30">
</td>
</tr>
<tr>
<td>State</td>
<td>
<select name="state">
<option value="-1" selected>select..</option>
<option value="Alabam">AL</option>
<option value="Alaska">AK</option>
<option value="Arizona">AZ</option>
<option value="Arkansa">AR</option>
<option value="California">CA</option>
<option value="Colorado">CO</option>
<option value="Connecticut">CT</option>
<option value="Delaware">DE</option>
<option value="Florida">FL</option>
<option value="Georgia">GA</option>
<option value="Hawaii">HI</option>
<option value="Idaho">ID</option>
<option value="Illinois">IL</option>
<option value="Indiana">IN</option>
<option value="Iowa">IA</option>
<option value="Kansas">KS</option>
<option value="Kentucky">KY</option>
<option value="Louisiana">LA</option>
<option value="Maine">ME</option>
<option value="Maryland">MD</option>
<option value="Michigan">MI</option>
<option value="Minnesota">MN</option>
<option value="Mississpi">MS</option>
<option value="Missori">MO</option>
<option value="Montana">MT</option>
<option value="Nebraska">NE</option>
<option value="Nevada">NV</option>
<option value="New Hampshire">NH</option>
<option value="New Jersey">NJ</option>
<option value="New Mexico">NM</option>
<option value="New York">NY</option>
<option value="Nortj Carolina">NC</option>
<option value="North Dakota">ND</option>
<option value="Ohio">OH</option>
<option value="Oklahoma">OK</option>
<option value="Oregon">OR</option>
<option value="Pennsylvania">PA</option>
<option value="Rhode Island">RI</option>
<option value="South Carolina">SC</option>
<option value="South Dakota">SD</option>
<option value="Tennessee">TN</option>
<option value="Texas">TX</option>
<option value="Utah">UT</option>
<option value="Vermont">VT</option>
<option value="Virgina">VA</option>
<option value="Washington">WA</option>
<option value="West Virgina">WV</option>
<option value="Wisconsin">WI</option>
<option value="Wyoming">WY</option>
</select>
</td>
<tr>
<td>Zipcode</td>
<td>
<input type="text" name="zipcode" id="zipcode_id" size="30">
</td>
</tr>
<tr>
<td>Phone</td>
<td>
<input type="text" name="phone" id="phone_id" size="30">
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input type="text" name="email" id="emailid" size="30">
</td>
</tr>
<tr>
<td>
<input type="reset">
</td>
<td>
<button name="sumbit" type="submit" id="btn_id" onlick="randomString(); getData();">Submit</button>
</td>
</tr>
<tr>
<td>
<name="randomfield" id="generateID" value=" ">
</td>
<td>
<name="ID" id="ID" value=" ">
</td>
</tr>
</form>
</table>
</body>

When you sumbit() the form, you leave the page. The alert() never fires! Try changing the code to:
if (valid)
{
alert(" Name :" + name_order + " \n Address : " + address_order +
" \n City : " + city_order + " \n State: " + state_order+
" \n Zipcode: " + zipcode_order + " \n Phone: " + phone +
" \n Email: "+ email_order + " \n ID: " + randID_order +
" \n SIM Card: " + ICCID_order);
$("form[name='workorder']").submit();
}

instead of $(button).click() use $(form).submit for your listener
in your code the form does not have a post location. You can add a return false to the bottom of the submit anonymous function for now
you have a reference to a variable "phone" in your alert call that is not defined
$("form#form_id").submit(function() {
var valid = validate();
var name_order = $("#name").val();
var address_order = $("#address").val();
var city_order = $("#city").val();
var state_order = $("#state").val();
var zipcode_order = $("#zipcode_id").val();
var phone_order = $("#phone_id").val();
var email_order = $("#emailid").val();
var randID_order = $("#generateID").val();
var ICCID_order = $("#ID").val();
if (valid) {
// you don't need to manually submit it since we attached to the submit listener above instead of click
// $("form[name='workorder']").submit();
alert(" Name :" + name_order + " \n Address : " + address_order +
" \n City : " + city_order + " \n State: " + state_order +
" \n Zipcode: " + zipcode_order + " \n Phone: " + phone_order + // you had a bad reference here
" \n Email: " + email_order + " \n ID: " + randID_order +
" \n SIM Card: " + ICCID_order)
}
// return false until you put in a proper post location
return false;
});
I fixed all these in an example at https://jsfiddle.net/algorithmicMoose/n0t83ees/ with comments

Related

Add a string in a <td> using jquery and conditions

What do I want : When the user focus out the field, i would like to add a string in the depending of an other . The are in a table and the problem is that i have to build the string depending of the size of the table.
It would be really nice if you give some documentations to help me because im a bit lost..
HTML :
<table id="tableAssemblage" class="dataAssemblage" style="display: table;">
<thead>
<tr class="entete">
<td>
Type</td>
<td>
Nom</td>
</tr>
</thead>
<tbody>
<td class="centrer">
<select name="typ_element_1" id="typ_element_1"
class="obligatoryAssemblage typ_element">
<option value="" selected="selected"></option>
<option value="EDITION">EDITION</option>
<option value="ENCART">ENCART</option>
<option value="INCARTO">INCARTO</option>
<option value="INCPLUS">INCPLUS</option>
<option value="OPP">OPP</option>
<option value="SUPPLEMENTS" disabled="">SUPPLEMENTS</option>
</select>
</td>
<td class="centrer">
<input type="text" name="nom_element_1" id="nom_element_1" value=""
size="35" length="35" maxlength="35" class="obligatoryAssemblage
nomAssemblage">
</td>
The Table : result in my computer
The jQuery/JS :
$(".nomAssemblage").focusout(function(){
addApresFixNomElement();
});
function addSuffixNomElement(){
// Parametres
var rowCount = $('#tableAssemblage tr').length;
var typElem = $(".typ_element").val();
var nomAss = $(".nomAssemblage").val();
var Suffix;
var id;
// Switch
switch (typElem)
{
case 'EDITION':
for(id=1; id<rowCount; id++){
Suffix = "[EDI ->" + id + "]";
$(".nomAssemblage").append(Suffix);
}
break;
case 'ENCART':
break;
case 'INCARTO':
break;
case 'INCPLUS':
break;
case 'OPP':
break;
case 'SUPPLEMENTS':
break;
}
}
The result i want : This is what i want exaclty
You could use
$("#nom_element_" + id).val($("#nom_element_" + id).val() + " " + Suffix);
as $().append() is to append elements (have also improved the logic as well):
$(".nomAssemblage").focusout(function() {
addSuffixNomElement();
});
function addSuffixNomElement() {
// Parametres
var rowCount = $('#tableAssemblage tbody tr').length;
var typElem = $(".typ_element").val();
var nomAss = $(".nomAssemblage").val();
var Suffix = "";
var id = 1;
// Switch
switch (typElem) {
case 'EDITION':
Suffix = "[EDI ->" + id + "]";
break;
case 'ENCART':
Suffix = "[ENC ->" + id + "]";
break;
case 'INCARTO':
//Suffix = "[INCA ->" + id + "]";
break;
case 'INCPLUS':
//Suffix = "[INCP ->" + id + "]";
break;
case 'OPP':
//Suffix = "[OPP ->" + id + "]";
break;
case 'SUPPLEMENTS':
//Suffix = "[SUP ->" + id + "]";
break;
}
for (id = 1; id < rowCount; id++) {
$("#nom_element_" + id).val($("#nom_element_" + id).val().replace(/\[.*?\]/, '') + " " + Suffix);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableAssemblage" class="dataAssemblage" style="display: table;">
<thead>
<tr class="entete">
<td>
Type</td>
<td>
Nom</td>
</tr>
</thead>
<tbody>
<tr>
<td class="centrer">
<select name="typ_element_1" id="typ_element_1" class="obligatoryAssemblage typ_element">
<option value="" selected="selected"></option>
<option value="EDITION">EDITION</option>
<option value="ENCART">ENCART</option>
<option value="INCARTO">INCARTO</option>
<option value="INCPLUS">INCPLUS</option>
<option value="OPP">OPP</option>
<option value="SUPPLEMENTS" disabled="">SUPPLEMENTS</option>
</select>
</td>
<td class="centrer">
<input type="text" name="nom_element_1" id="nom_element_1" value="" size="35" length="35" maxlength="35" class="obligatoryAssemblage nomAssemblage">
</td>
<tr>
</tbody>
</table>

Calculate total sum of dynamically added items to a table

I would like to calculate the line total for each item using the itemPrice* Qty fields, the line amount is to be auto populated in the linePrice textbox. After which the grand total is then auto populated to the priceTotal field by summing up all the line prices.
I am having a challenge getting each Qty and itemPrice textbox value into my JavaScript function since the name(s) is/are Qty0, Qty1, Qty2... and itemPrice0, itemPrice1,.. depending on the added row, and also getting the final calculations into the respective textboxes.
Below is my code.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
return false;
return true;
}
$(document).ready(function() {
$(document).on("keyup", ".Qty", calculateTot);
$("button").click(function() {
addrow('tb')
});
});
function calculateTot() {
var sum = 0;
var price = document.getElementById('itemPrice').value;
var qtyPur = parseFloat(this.value);
$(".Qty").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
linePR = price * qtyPur;
}
});
$("#linePrice").val(linePR.toFixed(2));
calculateSum();
}
function calculateSum() {
var sum = 0;
$(".linePrice").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#priceTotal").val(sum.toFixed(2));
}
$(document).ready(function() {
var i = 1,
j = 1;
$("#add_row").click(function() {
if (i < 10) {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
$('#tab_add').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
j++;
$('#delete_row').show();
} else {
alert("You can only add upto a maximum of 10 items")
$('#add_row').hide();
}
});
$("#delete_row").click(function() {
if (i > 1) {
var r = confirm('Do you want to delete this item?');
if (r == true) {
$("#addr" + (i - 1)).html('');
i--;
$('#add_row').show();
}
} else {
alert("Entry cannot be deleted")
$('#delete_row').hide();
}
});
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<table class="table table-bordered table-hover" id="tab_add">
<tbody>
<tr>
<td colspan="2"><b>Customer Name</b></td>
<td colspan="1">
<select name="Per_Name[]" class="form-control">
<option value="">Select Customer</option>
<option value="2000001">John Doe</option>
<option value="2000002">Jane Doe</option>
<option value="2000003">Tom Harry</option>
<option value="2000004">Steve Jobs</option>
</select>
</td>
</tr>
<tr id='addr0'>
<td><b>1</b></td>
<td><b>Select Item</b></td>
<td colspan="1">
<select name="Sub_Name[]" class="form-control">
<option value="">Select Item</option>
<option value="1000001">Item A</option>
<option value="1000002">Item B</option>
<option value="1000003">Item C</option>
<option value="1000004">Item D</option>
</select>
</td>
<td><input type="text" name="itemPrice0" id="itemPrice0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" class="Qty form-control" onkeypress="return isNumberKey(event)" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
<th>
<span class="glyphicon glyphicon-plus"></span>
<span class="glyphicon glyphicon-minus"></span>
</th>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
<table class="table table-bordered table-hover">
<tr id="finRow">
<td colspan="2" width="75%"><b>TOTAL</b></td>
<td><input type="text" name="priceTotal" id="priceTotal" class="row-total form-control" disabled></td>
</tr>
</table>
In order to reduce the amount of DOM traversal that you have to do to accomplish this, I suggest adding data-* attributes to your elements so that you can get the index and use that to reference the other elements directly.
<td><input type="text" name="itemPrice0" id="itemPrice0" data-index="0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" data-index="0" class="Qty form-control" onkeypress="if(!isNumberKey(event)){return false;}" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" data-index="0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
Then in your $("#add_row").click(function() { function we add data-index='"+j+"' when creating the new elements ...
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' data-index='"+j+"' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' data-index='"+j+"' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' data-index='"+j+"' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
Finally, change your keyup handler to ...
$("#tab_add").on("keyup", ".Qty", function(e){
var qtyPur = parseFloat(this.value);
if (!isNaN(this.value) && this.value.length != 0) {
// this is where use use the data-index attribute to dynamically generate the target element ids
$("#linePrice"+$(this).data('index')).val(
parseFloat($("#itemPrice"+$(this).data('index')).val()) * qtyPur
);
}
calculateSum()
});
See Demo
This part of code will calculate linePrice of each row:
$("tr").each(function() {
if ($(this).children("td").length) {
$($($(this).children("td")[5]).children("input")[0]).val(
(($($($(this).children("td")[4]).children("input")[0]).val()) ? Number($($($(this).children("td")[4]).children("input")[0]).val()) : 0) *
(($($($(this).children("td")[3]).children("input")[0]).val()) ? Number($($($(this).children("td")[3]).children("input")[0]).val()) : 0)
)
}
});
function grosschanged_total1(a) {
var str = a;
var res = str.split("_");
//alert(res[2]);
var result = res[2];
var rate = parseFloat(document.getElementById("Gridview1_txtgross_" + result).value) * parseFloat(document.getElementById("Gridview1_txtrate_" + result).value);
var scale77 = 2;
// rate = roundNumberV2(rate, scale77);
var gresult = 0.00;
if(isNaN(rate)){
gresult= document.getElementById("Gridview1_txttotal_" + result).value = "";
} else{
gresult= document.getElementById("Gridview1_txttotal_" + result).value = parseFloat(Math.round(rate * 100) / 100).toFixed(2);
}
//GridView1_txtinvamt_0
var gfresult = parseFloat(gresult);
var ggresult = 0.00;
ggresult = gfresult + ggresult;
// $("[id*=lblGrandTotal]").html(ggresult);
//GridView1_txtdelinvnum_0 + GridView1_txtinvamt_0 = GridView1_txtgrosspt_0
// Calculate();
grosschanged_total1(a);
}
function Numerics(text) {
var regexp = /^[0-9]*$/;
if (text.value.search(regexp) == -1) {
text.value = text.value.substring(0, (text.value.length - 1));
alert('Numerics only allowed');
if (text.value.search(regexp) == -1)
text.value = "";
text.focus();
return false;
}
else
return true;
}

Javascript grade calculation

I am trying to create a grade calculator whereby; my students can calculate their grade based on grades achieved in set units. I have had an attempt, as you can see from my code below:
<script type="text/javascript">
var units = 3;
var ocr = 0;
var grade = "";
var feedback = "";
function runCert()
{
document.getElementById("o1").disabled=false;
document.getElementById("o2").disabled=false;
document.getElementById("o3").disabled=true;
document.getElementById("o1").style.backgroundColor="#CCFFCC";
document.getElementById("o2").style.backgroundColor="#CCFFCC";
document.getElementById("o3").style.backgroundColor="#FFCCCC";
units = 2;
}
function runScore()
{
ocr = 0;
function assistScore(con1)
{
if (document.getElementById("o1").disabled=false == "P") ocr = ocr + 21;
if (document.getElementById("o1").disabled=false == "M") ocr = ocr + 24;
if (document.getElementById("o1").disabled=false == "D") ocr = ocr + 27;
if (document.getElementById("o2").disabled=false == "P") ocr = ocr + 21;
if (document.getElementById("o2").disabled=false == "M") ocr = ocr + 24;
if (document.getElementById("o2").disabled=false == "D") ocr = ocr + 27;
if (document.getElementById("o3").disabled=false == "P") ocr = ocr + 14;
if (document.getElementById("o3").disabled=false == "M") ocr = ocr + 16;
if (document.getElementById("o3").disabled=false == "D") ocr = ocr + 18;
}
if (units == 2)
{
assistScore(document.getElementById("o1").value);
assistScore(document.getElementById("o2").value);
if (ocr >= 52)
{
ucas = 28;
grade = "D*";
feedback = "This is the highest grade available";
}
else if (ocr >= 50)
{
ucas = 24;
grade = "D";
feedback = "You are " + (50 - ocr) + " ocr points short of the next grade boundary";
}
else if (ocr >= 46)
{
ucas = 40;
grade = "M";
feedback = "You are " + (46 - ocr) + " ocr points short of the next grade boundary";
}
else
{
ucas = 8;
grade = "P";
feedback = "You are " + (42 - ocr) + " ocr points short of the next grade boundary";
}
}
alert("ocr Score: " + ocr + "\n\nocr Grade: " + grade + "\n\nUCAS Points: " + ucas + "\n\n" + feedback);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form >
<table width="933" height="251" border="1">
<tr>
<td colspan="3">OCR grade calculator </td>
<td width="199"> </td>
</tr>
<tr>
<td width="201">unit #</td>
<td width="217">name </td>
<td width="288">mark </td>
<td>your course</td>
</tr>
<tr>
<td style="width: 98px;">1</td>
<td style="width: 221px;">Fundamentals of IT</td>
<td><select id="o1" style="background: #CCFFCC;">
<option value="Select">Select</option>
<option value="P">P</option>
<option value="M">M</option>
<option value="D">D</option>
</select></td>
<td><input type="radio" name="coursetype" value="ocr" id="A" onclick="runCert()" />
Certificate (2 units)</td>
</tr>
<tr>
<td style="width: 98px;">2</td>
<td style="width: 221px;">Global Information</td>
<td><select id="o2" style="background: #CCFFCC;">
<option value="Select">Select</option>
<option value="P">P</option>
<option value="M">M</option>
<option value="D">D</option>
</select></td>
<td><input type="button" value="Calculate Score" onclick="runScore()" /></td>
</tr>
<tr>
<td style="width: 98px;">3</td>
<td style="width: 221px;">Cyber Security</td>
<td><select id="o3" style="background: #CCFFCC;">
<option value="Select">Select</option>
<option value="P">P</option>
<option value="M">M</option>
<option value="D">D</option>
</select></td>
<td> </td>
</tr>
</table>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
</form>
The issue that I have is that the scores do not total, nor does the final grade. Could someone take a look at it for me?
Getting values from options seemed kind of broken, fixed it (and also shortened the code a little to make it more readable: pen
<script type="text/javascript">
var units = 3;
var ocr = 0;
var ucas = 0;
var grade = "";
var feedback = "";
var o1
var o2
var o3
window.addEventListener("load", function(event) {
o1 = document.getElementById("o1");
o2 = document.getElementById("o2");
o3 = document.getElementById("o3");
})
function runCert()
{
o1.disabled=false;
o2.disabled=false;
o3.disabled=true;
o1.style.backgroundColor="#CCFFCC";
o2.style.backgroundColor="#CCFFCC";
o3.style.backgroundColor="#FFCCCC";
units = 2;
}
function runScore()
{
ocr = 0;
function assistScore(con1)
{
if (o1.disabled==false && o1.value == "P") ocr = ocr + 21;
if (o1.disabled==false && o1.value == "M") ocr = ocr + 24;
if (o1.disabled==false && o1.value == "D") ocr = ocr + 27;
if (o2.disabled==false && o2.value == "P") ocr = ocr + 21;
if (o2.disabled==false && o2.value == "M") ocr = ocr + 24;
if (o2.disabled==false && o2.value == "D") ocr = ocr + 27;
if (o3.disabled==false && o3.value == "P") ocr = ocr + 14;
if (o3.disabled==false && o3.value == "M") ocr = ocr + 16;
if (o3.disabled==false && o3.value == "D") ocr = ocr + 18;
}
if (units == 2)
{
assistScore(document.getElementById("o1").value);
assistScore(document.getElementById("o2").value);
if (ocr >= 52)
{
ucas = 28;
grade = "D*";
feedback = "This is the highest grade available";
}
else if (ocr >= 50)
{
ucas = 24;
grade = "D";
feedback = "You are " + (50 - ocr) + " ocr points short of the next grade boundary";
}
else if (ocr >= 46)
{
ucas = 40;
grade = "M";
feedback = "You are " + (46 - ocr) + " ocr points short of the next grade boundary";
}
else
{
ucas = 8;
grade = "P";
feedback = "You are " + (42 - ocr) + " ocr points short of the next grade boundary";
}
}
alert("ocr Score: " + ocr + "\n\nocr Grade: " + grade + "\n\nUCAS Points: " + ucas + "\n\n" + feedback);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form >
<table width="933" height="251" border="1">
<tr>
<td colspan="3">OCR grade calculator </td>
<td width="199"> </td>
</tr>
<tr>
<td width="201">unit #</td>
<td width="217">name </td>
<td width="288">mark </td>
<td>your course</td>
</tr>
<tr>
<td style="width: 98px;">1</td>
<td style="width: 221px;">Fundamentals of IT</td>
<td><select id="o1" style="background: #CCFFCC;">
<option value="Select">Select</option>
<option value="P">P</option>
<option value="M">M</option>
<option value="D">D</option>
</select></td>
<td><input type="radio" name="coursetype" value="ocr" id="A" onclick="runCert()" />
Certificate (2 units)</td>
</tr>
<tr>
<td style="width: 98px;">2</td>
<td style="width: 221px;">Global Information</td>
<td><select id="o2" style="background: #CCFFCC;">
<option value="Select">Select</option>
<option value="P">P</option>
<option value="M">M</option>
<option value="D">D</option>
</select></td>
<td><input type="button" value="Calculate Score" onclick="runScore()" /></td>
</tr>
<tr>
<td style="width: 98px;">3</td>
<td style="width: 221px;">Cyber Security</td>
<td><select id="o3" style="background: #CCFFCC;">
<option value="Select">Select</option>
<option value="P">P</option>
<option value="M">M</option>
<option value="D">D</option>
</select></td>
<td> </td>
</tr>
</table>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
</form>

Get the field-index of same-name-combos (select / dropdown), added after page-load

I want to get the field-index of same-names-field i.e. 'item_id[]'.
As I select/change an item from 'Item Name' drop-down, its combo-field-index should be shown in 'span' under 'Available' against this dropdown.
Actually the purpose of getting the index of current combo is to show Available-Quantity in 'Span' against this combo under 'Available'.
(dropdown field is named 'item_id[]', index is started from 0, counting from upper most drop down to the current one)
Please copy/paste all code along with Javascript, use 'Add Rows' link and force Javascript/jQuery to work for all rows (previous and newly added elements). Thanks.
EDITED:
In short, I need to alert() the current index of item-name-combo-field after using 'Add Row' link (onchange event). This is enough for my solution (and I will manage everything else).
CODE I HAVE USED:
But it works just if used for text-box not for combo AND only for elements which are loaded on page-load not for added (appended) elements using 'Add Row' link.
var my_field = $('select[name="item_id[]"]');
my_field.on('change', function() {
var index = my_field.index( this );
alert( this.value + ', ' + index );
});
<form id="form1" enctype="multipart/form-data" name="form1" method="post" action="">
<table width="41%" border="0" align="center" cellpadding="0" cellspacing="0" id="contentstable">
<tr>
<th width="35%" align="center">Item Name </th>
<th width="14%" align="center">Quantity </th>
<th width="26%" align="center">item Sr. # </th>
<th width="18%" align="center">Store Status </th>
<th width="18%" align="center">Mode </th>
<th width="7%" align="center">Available </th>
</tr>
<tr>
<td>
<select name="item_id[]" id="item_id[]" class="combo" style="width:326px;" onchange="showIssuableQty(this.value);">
<option value="0"> </option>
<option value="1">item-1 ( Model# BN004 ) </option>
<option value="2">item-2-check ( Model# FG-56 ) </option>
<option value="3">Item - 3 - Piston of Crane's Engine (Hitachi) Large size heavy duty ( Model# machine2-model-3CD ) </option>
</select>
</td>
<td>
<input name="quantity[]" type="number" id="quantity[]" value="" class="field_3" style="width:99px;">
</td>
<td>
<input name="item_sr_no[]" type="text" id="item_sr_no[]" value="" class="field_3" style="width:199px;">
</td>
<td>
<select name="store_status[]" class="combo" id="store_status[]" style="width:119px;">
<option value="New" selected="">New </option>
<option value="Repaired">Repaired </option>
<option value="Used">Used </option>
</select>
<td>
<select name="type[]" class="combo" id="type[]" style="width:119px;">
<option value="Consume" selected="">Consume </option>
<option value="Borrow">Borrow </option>
</select>
</td>
<td>
<span id="qty_avail">Qty-Here </span>
</td>
</tr>
<tr>
<td colspan="6">
<table width="100%">
<tr>
<td width="25%" style="text-align:left; vertical-align:top; font-size:17px">
<br>
<span "> <input name="add_rows " id="add_rows " type="number " value="1 " style="width:63px; " onkeypress="handle_addRows(event); "> Add Rows </span"> </td>
<td width="55%">
<p id="issuable_qty">Issuable Qty </p>
</td>
<td width="20%" class="submittd" style="text-align:right"> <br> <input name="save" type="submit" class="submit" id="addnewcategory" value="Save Record"> </td>
</tr>
</table>
</td>
</tr>
</tbody> </table>
</form>
Javascript Used:
<script>
/*var textboxes = $('select[name="item_id[]"]');
textboxes.on('change', function() {
var index = textboxes.index( this );
alert( this.value + ', ' + index );
});
alert('abc');*/
function addMoreRow() {
var tbl_name = document.getElementById("contentstable");
var rowCount = tbl_name.rows.length;
var row = tbl_name.insertRow(rowCount - 1);
var cell1 = row.insertCell(0);
cell1.innerHTML = " <select name=\"item_id[]\" class=\"combo\" id=\"item_id[]\" onchange=\"showIssuableQty(this.value);\" value=\"\" style=\"width:326px;\" > <option> </option> <option value='1'>item-1 ( Model# BN004 ) </option> <option value='2'>item-2-check ( Model# FG-56 ) </option> <option value='3'>Item - 3 - Piston of Crane's Engine (Hitachi) Large size heavy duty ( Model# machine2-model-3CD ) </option> </select>";
var cell2 = row.insertCell(1);
cell2.innerHTML = " <input name=\"quantity[]\" type=\"number\" class=\"input\" id=\"quantity[]\" value=\"\" style=\"width:99px;\" /> <input name=\"prev_quantity[]\" type=\"hidden\" class=\"input\" id=\"prev_quantity[]\" value=\"\" style=\"width:99px;\" />";
var cell3 = row.insertCell(2);
cell3.innerHTML = " <input name=\"item_sr_no[]\" type=\"text\" class=\"input\" id=\"item_sr_no[]\" value=\"\" style=\"width:199px;\" />";
var cell4 = row.insertCell(3);
cell4.innerHTML = " <select name=\"store_status[]\" class=\"combo\" id=\"store_status[]\" value=\"\" style=\"width:119px;\" > <option value='New' selected >New </option> <option value='Repaired'>Repaired </option> <option value='Used'>Used </option> </select> <input name=\"prev_store_status[]\" type=\"hidden\" class=\"input\" id=\"prev_store_status[]\" value=\"\" style=\"width:119px;\" />";
var cell5 = row.insertCell(4);
cell5.innerHTML = " <select name=\"type[]\" class=\"combo\" id=\"type[]\" value=\"\" style=\"width:119px;\" > <option value='Consume' selected >Consume </option> <option value='Borrow'>Borrow </option> </select>";
var cell6 = row.insertCell(5);
cell6.innerHTML = " <span class=\"qty_avail\"> </span>";
}
function addRows() {
var add_rows = document.getElementById('add_rows');
//alert(add_rows.value);
for ($i = 1; $i <= add_rows.value; $i++) {
addMoreRow();
}
}
function handle_addRows(e) {
if (e.keyCode === 13) {
e.preventDefault(); // Ensure it is only this code that runs
addRows();
}
}
var itemIds = new Array('1', '2', '3');
var itemNames = new Array('', '', '');
var newItems = new Array('2357', '452', '215');
var usedItems = new Array('12', '333', '57');
var toRepairItems = new Array('234', '65', '321');
var repairedItems = new Array('789', '3', '56');
var itemThreshold = new Array('34', '56', '67');
function showIssuableQty(item_id) { // This function is not working properly, see it later.
document.getElementById('issuable_qty').innerHTML = 'abc';
var item_index = itemIds.indexOf(item_id);
var strQtyMsg = 'Issuable Qty ( <b>' + (parseInt(newItems[item_index]) + parseInt(repairedItems[item_index]) + parseInt(usedItems[item_index])) +
' </b> )' + ' <br />' + 'New ( <b>' + newItems[item_index] + ' </b> ), Repaired ( <b>' + repairedItems[item_index] + ' </b> ), Used ( <b>' + usedItems[item_index] + ' </b> )';
if (parseInt(newItems[item_index]) + parseInt(repairedItems[item_index]) < parseInt(itemThreshold[item_index])) {
//if( parseInt(newItems[item_index]) + parseInt(repairedItems[item_index]) < 100 ){
strQtyMsg = strQtyMsg + ' <br />Qty. below threshold ( ' + itemThreshold[item_index] + ' ) ';
strQtyMsg = strQtyMsg + ' Request Items ';
alert('Qty. is below threshold! Please generate a request to purchase.');
}
document.getElementById('issuable_qty').innerHTML = strQtyMsg;
//alert(item_index);
}
</script>
your code could be much shorter.
you should only have one item per id, so I have changed the id names
in your html to classes.
for the select in your first bit of code you can move the selector
to become an argument of the function, this means the new change
selectors will be recognised after the dom has been updated.
your first table row making function has been removed and replaced
by simply copying the html into a variable and using that to
duplicate new rows.
your last function contents have been changed to numbers to
eliminate all of the string parsing and simplify
here's a working fiddle.
$('body').on('change', 'select.combo', function() {
var $this = $(this);
var index = $this.parent().parent('tr').index();
alert($this.val() + ', ' + index);
});
var rowTemplate = $('#contentstable tr').eq(1).html(); // make a copy of the standard row html content as defined in the html
rowTemplate = '<tr>' + rowTemplate + '</tr>';
function addRows() {
var add_rows = parseFloat($('input#add_rows').val());
for (var i, i = 1; i <= add_rows; i++) {
$('#panel').before(rowTemplate); // insert the standard row above the addrow area
}
}
function handle_addRows(e) {
if (e.keyCode === 13) {
e.preventDefault(); // Ensure it is only this code that runs
addRows();
}
}
var itemIds = [1, 2, 3];
var itemNames = ['', 0, 0, 0];
var newItems = ['', 2357, 452, 215];
var usedItems = ['', 12, 333, 57];
var toRepairItems = ['', 234, 65, 321];
var repairedItems = ['', 789, 3, 56];
var itemThreshold = ['', 34, 56, 67];
function showIssuableQty(item_id) { // This function is not working properly, see it later.
// $('#issuable_qty').html('abc');
var item_index = parseFloat(item_id); // parseInt(itemIds.indexOf(item_id));
var newAndRepaired = newItems[item_index] + repairedItems[item_index];
var strQtyMsg = 'Issuable Qty ( <b>' + (newAndRepaired + usedItems[item_index]) +
' </b> )' + ' <br />' + 'New ( <b>' + newItems[item_index] + ' </b> ), Repaired ( <b>' + repairedItems[item_index] + ' </b> ), Used ( <b>' + usedItems[item_index] + ' </b> )';
if (newAndRepaired < itemThreshold[item_index]) {
//if( parseInt(newItems[item_index]) + parseInt(repairedItems[item_index]) < 100 ){
strQtyMsg = strQtyMsg + ' <br />Qty. below threshold ( ' + itemThreshold[item_index] + ' ) ';
strQtyMsg = strQtyMsg + ' Request Items ';
alert('Qty. is below threshold! Please generate a request to purchase.');
}
if (item_index === 0) {
strQtyMsg = 'Issuable Qty ( </b> )';
}
$('#issuable_qty').html(strQtyMsg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" enctype="multipart/form-data" name="form1" method="post" action="">
<table width="41%" border="0" align="center" cellpadding="0" cellspacing="0" id="contentstable">
<tr>
<th width="35%" align="center">Item Name</th>
<th width="14%" align="center">Quantity</th>
<th width="26%" align="center">item Sr. #</th>
<th width="18%" align="center">Store Status</th>
<th width="18%" align="center">Mode</th>
<th width="7%" align="center">Available</th>
</tr>
<tr>
<td>
<select name="item_id[]" id="" class="item_id[] combo" style="width:326px;" onchange="showIssuableQty(this.value);">
<option value="0"></option>
<option value="1">item-1 ( Model# BN004 )</option>
<option value="2">item-2-check ( Model# FG-56 )</option>
<option value="3">Item - 3 - Piston of Crane's Engine (Hitachi) Large size heavy duty ( Model# machine2-model-3CD )</option>
</select>
</td>
<td>
<input name="quantity[]" type="number" id="" value="" class="quantity[] field_3" style="width:99px;">
</td>
<td>
<input name="item_sr_no[]" type="text" id="" value="" class="item_sr_no[] field_3" style="width:199px;">
</td>
<td>
<select name="store_status[]" class="combo store_status[]" id="" style="width:119px;">
<option value="New" selected="">New</option>
<option value="Repaired">Repaired</option>
<option value="Used">Used</option>
</select>
<td>
<select name="type[]" class="type[] combo" id="" style="width:119px;">
<option value="Consume" selected="">Consume</option>
<option value="Borrow">Borrow</option>
</select>
</td>
<td>
<span class="qty_avail">Qty-Here </span>
</td>
</tr>
<tr id='panel'>
<td colspan="6">
<table width="100%">
<tr>
<td width="25%" style="text-align:left; vertical-align:top; font-size:17px">
<br>
<span> <input name="add_rows" id="add_rows" type="number" value="1" style="width:63px; " onkeypress="handle_addRows(event); "> Add Rows </span>
</td>
<td width="55%">
<p id="issuable_qty">Issuable Qty</p>
</td>
<td width="20%" class="submittd" style="text-align:right">
<br>
<input name="save" type="submit" class="submit" id="addnewcategory" value="Save Record">
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
</form>

Submit button not working unless change input

I have a form calculator, when customer submit the form(input.php), it will open another page display the results(output.php target _blank). However, when they want to use the same page(input.php) to get the result again, the submit button not working anymore, unless they change some value in the input field, and for the drop down menu, the submit button won't work, even you changed the drop down value.
Can someone please help me to fix the problems? thanks. I just want the button enabled all the time, here is the partially code from input.php.
<form name="form1" action="output.php" method="post" target="_blank">
<table id="distax" width="750">
<th colspan="6">F. Discount & Taxes</th>
<tr>
<td width="120"><b><input type="radio" name="discountmu" id="disc" value="-" />Discount (-)<br /> <input type="radio" name="discountmu" id="mu" value="+" />Markup (+)</b></td>
<td width="80">% <input type="text" name="discmuv" size="3" value="0"></td>
<td width="120"><b>2. Tax Goods:</b></td>
<td width="80">% <input type="text" name="txgood" size="3" value="0" onkeyup="data_change(this);"></td>
<td width="120"><b>3. Tax Services:</b><br />(for items in G)</td>
<td width="*">% <input type="text" name="txservice" size="3" value="0" onkeyup="data_change(this);"></td>
</tr>
<table id="extra" width="750">
<th colspan="6">E. Extras</th>
<tr>
<td width="170"><b>1. Extra railing (total):</b></td>
<td width="70"><input type="text" name="extrail" size="2" value="0" onkeyup="data_change(this);">ft</td>
<td width="110"><b>2. Custom Color: </b></td>
<td width="*"><select size="1" value="<?=$_SESSION['name']?> " name="R4" id="R4" onchange="showme()">
<option selected value="noSS">Sand Stone (Ral 1019)</option>
<option value="noEW">Euro White (Ral 9010)</option>
<option value="noQG">Quartz Grey (Ral 8014)</option>
<option value="noJB">Java Brown (Ral 8014)</option>
<option value="yes">Custom</option>
</select>
<input type="text" id="color1other" name="color1other" style=" position:relative;display:none;" Size=20 value="enter custom color here">
</td>
</tr>
<tr>
<td width="170"> <b>3. Height adjustment [ft // cm]:</b></td>
<td width="*">
<select size="1" name="D8">
<option value="1.125">+2'6" // +76cm</option>
<option value="1.1">+2'0" // +61cm</option>
<option value="1.075">+1'6" // +46cm</option>
<option value="1.05">+1'0" // +30cm</option>
<option value="1.025">+0'6" // +15cm</option>
<option selected value="1">0</option>
<option value="0.985">-0'6" // -15cm</option>
<option value="0.97">-1'0" // -30cm</option>
<option value="0.955">-1'6" // -46cm</option>
<option value="0.94">-2'0" // -61cm</option>
<option value="0.925">-2'6" // -76cm</option>
<option value="0.91">-3'0" // -91cm</option>
</select>
</td>
<td width="110"><b>4. Freight (Sea/Land/Air): </b></td>
<td width="*">
<input type="text" id="freight" name="freight" Size=12 value="0"><b>USD</b>
</td>
</tr>
<input type="Submit" Value="Get your quote"> as
<input type="radio" value="detail" checked name="report">Dealer <input type="radio" name="report" value="short"> Client version in English
</form>
thanks for the reply, here is the code for the javascript, didn't see anything related to the submit button
//Date: 05/27/2009 Edited by EG
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
var val3=document.form1.load.value;
//Date: 07/27/2009 Edited by EG
//self.location=self.location + '&cat=' + val + '&load=' + val3;
//self.location='webcalc_input.php?PHPSESSID=' + ssidjs + '&cat=' + val + '&load=' + val3;
self.location='webcalc_input.php?cat=' + val + '&load=' + val3;
}
function reload3(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
var val2=form.subcat.options[form.subcat.options.selectedIndex].value;
var val3=document.form1.load.value;
//Date: 07/27/2009 Edited by EG
self.location= 'webcalc_input.php?cat=' + val + '&cat3=' + val2 + '&load=' + val3;
//self.location='webcalc_input.php?PHPSESSID=' + ssidjs + '&cat=' + val + '&cat3=' + val2 + '&load=' + val3;
}
function data_change(field) {
var check = true;
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for (var i = 0; i < field.value.length; ++i) {
var new_key = value.charAt(i); //cycle through characters
if (((new_key < "0") || (new_key > "9")) && !(new_key == "") && (new_key != ".")) { //Included . to enable decimal entry
check = false;
break;
}
}
//apply appropriate colour based on value
if (!check) {
field.style.backgroundColor = "red";
}
else {
field.style.backgroundColor = "white";
}
}
function validateEmpty(fld) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "The required field has not been filled in.\n"
} else {
fld.style.background = 'White';
}
return error;
}
The text input contains a javascript function which you don't show in your code called data_change(). If I understand the question, its likely that that function is disabling the submit button and enabling it when the text changes. This is only an assumption without seeing your javascript code.
enter code here
Find the definition of the data_change() function and look for something relating to the submit button and comment it out.
You may remove the onkeyup="data_change(this);" from the <input> tag, but that could break other functionality!

Categories

Resources