I am brand new to JavaScript and HTML, and am trying to make a rehersal booking app which collects the info needed and displays it in a table on the same page.
I have been trying for hours on end to get it to work with various methods and I feel like it's just getting worse. I have probably made some silly mistakes but I cant seem to work out what I need to change to make it work.
Here is my HTML:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>White Noise Studios - Home</title>
<script type="text/javascript" src="Homepage.js"></script>
<style>
body, html
{
height: 100%;
background: url(Media/background.png);
background-size: cover;
}
</style>
</head>
<body>
<header style="color:white;font-family:'Calibri'">
<h1> Rehearsal Bookings</h1>
<p>Please let us know what gear you require in order for us to have the room ready for you. Leave the equipment section blank if you wish to bring your own gear. </p>
</header>
<form name="booking" id="booking">
<table style="color:white;font-family:'Yu Gothic UI Semibold'">
<tr>
<td><form action="Homepage.html"><input type="image" src="Media/homebutton.png"></form></td>
<td><form action="Homepage.html"><input type="submit" value="Book My Rehearsal"></form></td>
<td>Artist Name:</td><td><input type="text" name="Artist" size="50" id="Artist" /></td>
<td>Contact Number:</td><td><input type="text" name="Contact" size="50" id="Contact" /></td>
</tr>
<td>Equipment Needed:</td>
<td><label>Microphone</label>
<select id = "Microphone" name="Microphone">
<option value = "0">0</option>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select></td>
<td><label>Guitars</label>
<select id = "Guitar" name="Guitar">
<option value = "0">0</option>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select></td>
<td><label>Bass</label>
<select id = "Bass" name="Bass">
<option value = "0">0</option>
<option value = "1">1</option>
<option value = "2">2</option>
</select></td>
<td><label>Drums</label>
<select id = "Drums" name="Drums">
<option value = "0">None</option>
<option value = "1">Mapex Mars 5 Piece Full Kit</option>
<option value = "2">Ludwig LC17611 5 Piece Acoustic Kit</option>
<option value = "3">Roland TD 25KV V-Drums Kit</option>
</select></td>
<td><label>Amp</label>
<select id = "Amp" name="Amp">
<option value = "0">None</option>
<option value = "1">Marshall DSL100H</option>
<option value = "2">Marshall MG100GFX</option>
<option value = "3">Mesa Boogie triple Rectifier 100w</option>
</select></td> </tr>
<tr>
<td>Date:</td><td><input type="date" name="Date" id="Date" /></td>
</tr>
<tr>
<td>Time:</td><td><input type="time" name="Time" id="Time" /></td>
</tr>
</table>
</form>
<input type="submit" name="Book" value="Book my Rehearsal">
<button id="cancel" name="Cancel" onclick="myFunction()" value="Reset form">Cancel</button>
<hr/>
<div id="table">
</div>
<body>
<body style=”font-family:”arial black”; >
And my JavaScript:
var ArtistField, ContactField, MicrophoneSelect, GuitarSelect, BassSelect, DrumsSelect, AmpSelect, DateSelect, TimeSelect, BookSelect, CancelSelect;
var Booking = function (Artist, Contact, Microphone, Guitar, Bass, Drums, Amp, Date, Time ) {
this.Artist = Artist;
this.Contact = Contact;
this.Microphone = Microphone;
this.Guitar = Guitar;
this.Bass = Bass;
this.Drums = Drums;
this.Amp = Amp;
this.Date = new Date ;
this.Time = Time;
};
function myFunction() {
document.getElementById("booking").reset();
}
var Bookings = []
Booking.prototype.tableRow = function(){
var tr = "<tr><td>" + this.Artist + "</td><td>" +
this.Contact + "</td><td>" + this.Microphone +
"<tr><td>" + this.Guitar + "<tr><td>" + this.Bass + "<tr><td>" + this.Drums + "<tr><td>" + this.Amp +"<tr><td>"
+ this.getDate() + "</td><td>" + this.Time+ "</td><td>" + "</td></tr> ";
return tr;
};
Booking.prototype.getDate = function(){
return this.Date.toDateString();
};
var clickBook = function() {
addbooking(ArtistField, ContactField, MicrophoneSelect, GuitarSelect, BassSelect, DrumsSelect, AmpSelect, DateSelect, TimeSelect,);
showTable();
};
var showTable = function(){
var tableDiv = document.getElementById("table"), table = "<table border='1'>" +
"<thead><th>Artist</th><th>Contact</th><th>Microphone</th><th>Guitar</th><th>Bass</th><th>Drums</th><th>Amp</th</thead>";
for(var i=0, j=Bookings.length; i<j; i++){
var appt = Bookings[i];
table += appt.tableRow();
}
table+="</table>";
tableDiv.innerHTML = table;
};
window.onload = function(){
ArtistField = document.getElementById("Artist");
ContactField = document.getElementById("Contact");
MicrophoneSelect = document.getElementById("Microphone");
GuitarSelect = document.getElementById("Guitar");
BassSelect = document.getElementById("Bass");
DrumsSelect = document.getElementById("Drums");
AmpSelect = document.getElementById("Amp");
DateSelect = document.getElementById("Date");
TimeSelect = document.getElementById("Time");
//var roleChoice = roleField.options[roleField.selectedIndex].text;
Book = document.getElementById("Book");
Book.onclick = clickBook();
showTable();
};
Related
I have a design related question.
I have a bill to add product. One product is added per line.
One Product added per line image
When I add a product, I also display its warranty in the Warranty column:
Selected product shows warranty in Warranty Column
But when I add any other product, I cannot display its Warranty.
Cannot Display Warranty in subsequent products
My HTML where dropdown options are coming dynamically:
<tbody style="border: 1px solid rgba(0,0,0,0.35); height: 34px; line-height: 34px;">
<tr class="text-center">
<td>
<select id="myDropdown" name="bill_product[]" onChange="dropdownTip(this.value)">
<option disabled selected value="">Select Product</option>
<option id="1" value="31/01/2020">Product #1</option>
<option id="2" value="31/01/2030">Product #2</option>
<option id="3" value="31/01/2040">Product #3</option>
</select>
</td>
<td>
<input name="txtbox" type="text" id="txtbox" />
</td>
<td>
<button type="button" class="btn btn-danger btn-xs disabled">
<i class="fa fa-times"></i>
</button>
</td>
</tr>
</tbody>
My JS for adding row to bill:
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr class='text-center'>");
var cols = "";
cols += '<td><select name="bill_product[]"><option disabled selected value="">Select Product</option><cms:pages masterpage="product.php"><option value="<cms:show k_page_id />"><cms:show k_page_title /></option></cms:pages></select></td>';
cols += '<td><input type="text" id="txtbox" name="txtbox" /></td>';
cols += '<td><button type="button" class="ibtnDel btn btn-danger btn-xs"><i class="fa fa-times"></i></button></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
My Code to display the warranty end date:
$(document).ready(function() {
$("#myDropdown").change(function() {
var selectedValue = $(this).val();
$("#txtbox").val(selectedValue);
});
});
ISSUE: I am unable to display the value of the warranty date on any product after the first one.
Please help.
P.S.: I am using CouchCMS to dynamically bring my values to the option tag of select.
Here's the solution I propose, I get rid off not-native JS by the way, it allows it to fit with any solution :
<tbody style="border: 1px solid rgba(0,0,0,0.35); height: 34px; line-height: 34px;">
<tr class="text-center">
<td>
<select id="myDropdown" name="bill_product[]" onChange="dropdownTip(this.value)">
<option disabled selected value="">Select Product</option>
<option id="1" value="31/01/2020">Product #1</option>
<option id="2" value="31/01/2030">Product #2</option>
<option id="3" value="31/01/2040">Product #3</option>
</select>
</td>
<td>
<input name="txtbox" type="text" id="txtbox" />
</td>
<td>
<button type="button" class="btn btn-danger btn-xs disabled">
Delete
</button>
</td>
</tr>
</tbody>
// Line removal
let delBtns = document.querySelectorAll(".del-btn");
[].forEach.call(delBtns, function(delBtn){
delBtn.addEventListener('click', function(event){
let line = event.target.dataset.line;
let lineToRemove = document.querySelector("#line-"+line);
lineToRemove.remove();
})
});
// Input update
let productDropDowns = document.querySelectorAll("select");
[].forEach.call(productDropDowns, function(dropDown){
dropDown.addEventListener('change', function(event){
let line = event.target.dataset.line;
document.querySelector('#line-'+line+' input').value = event.target.value;
})
});
// New line button
let count = 0;
let newLineButton = document.querySelector("#newLineTrigger");
newLineButton.addEventListener('click', function(){
count++;
let tableBody = document.querySelector('tbody');
let newLine = document.createElement('tr');
newLine.id = 'line-' + count;
tableBody.appendChild(newLine);
newLine = document.querySelector('#line-' + count);
let col1 = document.createElement('td');
let select = document.createElement('select');
select.id = 'drop' + count;
select.dataset.line = count;
select.addEventListener('change', function(event){
let line = event.target.dataset.line;
document.querySelector('#line-'+line+' input').value = event.target.value;
})
for(let i=0; i<3; i++){
let option = document.createElement('option');
option.value = i;
option.innerText = 'option ' + i;
select.appendChild(option);
}
col1.appendChild(select);
let col2 = document.createElement('td');
let textBox = document.createElement('input');
textBox.id = 'textBox'+count;
textBox.name = 'textBox'+count;
col2.appendChild(textBox);
let col3 = document.createElement('td');
let newDelBtn = document.createElement('button');
newDelBtn.className = "del-btn";
newDelBtn.dataset.line = count;
newDelBtn.innerText = "Delete";
newDelBtn.addEventListener('click', function(event){
let line = event.target.dataset.line;
let lineToRemove = newLine;
lineToRemove.remove();
});
col3.appendChild(newDelBtn);
newLine.appendChild(col1);
newLine.appendChild(col2);
newLine.appendChild(col3);
tableBody.appendChild(newLine);
});
I don't see the triggerring element '#addrow' which adds the row. Could you update the fiddle to include this button, please?
The ids for all warranty input field is same, which is "txtbox". You can use the counter variable to have separate ids for all warranty fields.
I am trying to take my form which outputs to a text area on the same page and have it only show any enabled fields. You can see it at my JSFiddle here, Right now, when you click the "Combine" button it outputs all 4 categories even though two are disabled by default.
So it will output:
Optional Detail:
Default Detail:
Optional Selection:
Default Selection:
But I want it to look like this if the details toggles are unchecked:
Default Detail:
Default Selection:
Here's my script:
function convertForm() {
var detailToggle = document.getElementById("detailToggle").value;
var basicDetail = document.getElementById("basicDetail").value;
var selectOne = document.getElementById("selectOne").value;
var selectTwo = document.getElementById("selectTwo").value;
var output = "";
output += "Optional Detail: " + detailToggle + "\n";
output += "Default Detail: " + basicDetail + "\n";
output += "Optional Selection: " + selectOne + "\n";
output += "Default Selection: " + selectTwo + "";
document.getElementById("output3").value = output;
}
function toggle(checkboxID, toggleID) {
var checkbox = document.getElementById(checkboxID);
var toggle = document.getElementById(toggleID);
updateToggle = checkbox.checked ? toggle.disabled=false :
toggle.disabled=true;
}
function ResetForm() {
document.getElementById("detailToggle").disabled = true;
document.getElementById("selectOne").disabled = true;
}
And the HTML:
<table width="100%" height=" " border="0"><tr>
<td width=550 valign=top>
<form name="Form3" onsubmit="return false;" action="">
Toggle detail:
<input type="checkbox" id="ChecktoggleDetail" class="formArea"
name="Toggledetail" onClick="toggle('ChecktoggleDetail', 'detailToggle')">
<input type="text" class="formArea" name="details"
id="detailToggle" placeholder="Toggle field" disabled required>
<br>
Detail:
<br>
<input type="text" class="formArea" name="Basicdetail" id="basicDetail"
placeholder="Some detail" maxlength="25" required>
<br>
Selection 1:
<input type="checkbox" id="CheckselectOne" class="formArea"
name="detailsgiven" onClick="toggle('CheckselectOne', 'selectOne')">
<br>
<select type="drop" class="formArea" name="Selectone" id="selectOne"
disabled required>
<option value="" disabled selected>...</option>
<option value="Option One">Option 1</option>
<option value="Option Two">Option 2</option>
</select>
<br>
Selection 2:
<br>
<select type="drop" class="formArea" name="Selecttwo" id="selectTwo"
required>
<option value="" disabled selected>...</option>
<option value="Option One">Option 1</option>
<option value="Option two">Option 2</option>
</select>
<br>
</td>
<td valign="top">
<table border="0" height="200" ><tr><td valign="top" height=200>
<textarea type="textarea" class="formArea" name="form3output" id="output3"
onclick="this.focus();this.select()" cols="70" rows="10" placeholder=""
required></textarea><br>
</td></tr>
<tr><td valign=top>
<div class="btn-group">
<button value="Combine" onclick="convertForm()"
id="combine3">Combine</button>
</div>
<br>
<div class="btn-group2">
<button type="reset" value="Reset form" onclick="ResetForm();">Reset
form</button> <br>
</div>
</form>
</td></tr></table>
I am still new to Javascript, I am guessing there is some variable to insert, but am not sure what it is. Any help is appreciated.
You May Try For This:
Here I just check the disabled property of the element, if element is not disabled then i added text to output,
function convertForm() {
var detailToggle = document.getElementById("detailToggle").value;
var basicDetail = document.getElementById("basicDetail").value;
var selectOne = document.getElementById("selectOne").value;
var selectTwo = document.getElementById("selectTwo").value;
debugger;
var output = "";
if(!document.getElementById("detailToggle").disabled){
output += "Optional Detail: " + detailToggle + "\n";
}
if(!document.getElementById("basicDetail").disabled){
output += "Default Detail: " + basicDetail + "\n";
}
if(!document.getElementById("selectOne").disabled){
output += "Optional Selection: " + selectOne + "\n";
}
if(!document.getElementById("selectTwo").disabled){
output += "Default Selection: " + selectTwo + "";
}
document.getElementById("output3").value = output;
}
function toggle(checkboxID, toggleID) {
var checkbox = document.getElementById(checkboxID);
var toggle = document.getElementById(toggleID);
updateToggle = checkbox.checked ? toggle.disabled=false : toggle.disabled=true;
}
function ResetForm() {
document.getElementById("detailToggle").disabled = true;
document.getElementById("selectOne").disabled = true;
}
For More info visit me on:
https://jsfiddle.net/66qpfyhh/8/
Use below javascript to check element is disabled first then append in variable
Check updated fiddle : https://jsfiddle.net/yogesh078/66qpfyhh/1/
function convertForm() {
var detailToggle = document.getElementById("detailToggle");
var basicDetail = document.getElementById("basicDetail");
var selectOne = document.getElementById("selectOne");
var selectTwo = document.getElementById("selectTwo");
var output = "";
if (!detailToggle.disabled) {
output += "Optional Detail: " + detailToggle.value + "\n";
}
if (!basicDetail.disabled) {
output += "Default Detail: " + basicDetail.value + "\n";
}
if (!selectOne.disabled) {
output += "Optional Selection: " + selectOne.value + "\n";
}
if (!selectTwo.disabled) {
output += "Default Selection: " + selectTwo.value + "";
}
document.getElementById("output3").value = output;
}
function toggle(checkboxID, toggleID) {
var checkbox = document.getElementById(checkboxID);
var toggle = document.getElementById(toggleID);
updateToggle = checkbox.checked ? toggle.disabled = false : toggle.disabled = true;
}
function ResetForm() {
document.getElementById("detailToggle").disabled = true;
document.getElementById("selectOne").disabled = true;
}
This code snippet can solve your problem.
function convertForm() {
var detailToggle = document.getElementById("detailToggle").value;
var basicDetail = document.getElementById("basicDetail").value;
var selectOne = document.getElementById("selectOne").value;
var selectTwo = document.getElementById("selectTwo").value;
if(document.getElementById("detailToggle").disabled)
detailToggle='';
if(document.getElementById("selectOne").disabled)
selectOne='';
var output = "";
output += "Optional Detail: " + detailToggle + "\n";
output += "Default Detail: " + basicDetail + "\n";
output += "Optional Selection: " + selectOne + "\n";
output += "Default Selection: " + selectTwo + "";
document.getElementById("output3").value = output;
}
function toggle(checkboxID, toggleID) {
var checkbox = document.getElementById(checkboxID);
var toggle = document.getElementById(toggleID);
updateToggle = checkbox.checked ? toggle.disabled=false : toggle.disabled=true;
}
function ResetForm() {
document.getElementById("detailToggle").disabled = true;
document.getElementById("selectOne").disabled = true;
}
<table width="100%" height=" " border="0"><tr>
<td width=550 valign=top>
<form name="Form3" onsubmit="return false;" action="">
Toggle detail:
<input type="checkbox" id="ChecktoggleDetail" class="formArea"
name="Toggledetail" onClick="toggle('ChecktoggleDetail', 'detailToggle')">
<input type="text" class="formArea" name="details"
id="detailToggle" placeholder="Toggle field" disabled required>
<br>
Detail:
<br>
<input type="text" class="formArea" name="Basicdetail" id="basicDetail"
placeholder="Some detail" maxlength="25" required>
<br>
Selection 1:
<input type="checkbox" id="CheckselectOne" class="formArea"
name="detailsgiven" onClick="toggle('CheckselectOne', 'selectOne')">
<br>
<select type="drop" class="formArea" name="Selectone" id="selectOne" disabled required>
<option value="" disabled selected>...</option>
<option value="Option One">Option 1</option>
<option value="Option Two">Option 2</option>
</select>
<br>
Selection 2:
<br>
<select type="drop" class="formArea" name="Selecttwo" id="selectTwo" required>
<option value="" disabled selected>...</option>
<option value="Option One">Option 1</option>
<option value="Option two">Option 2</option>
</select>
<br>
</td>
<td valign="top">
<table border="0" height="200" ><tr><td valign="top" height=200>
<textarea type="textarea" class="formArea" name="form3output" id="output3"
onclick="this.focus();this.select()" cols="70" rows="10" placeholder="" required> </textarea><br>
</td></tr>
<tr><td valign=top>
<div class="btn-group">
<button value="Combine" onclick="convertForm()" id="combine3">Combine</button>
</div>
<br>
<div class="btn-group2">
<button type="reset" value="Reset form" onclick="ResetForm();">Reset form</button> <br>
</div>
</form>
</td></tr></table>
I am adding dynamic row to table. But when adding new row, I want to replace some string on new row. But it is not working.
<table id="testTable">
<tr id="row_1">
<td>
<select onchange="changeCustomCategory(this.value,'1');" id="_cid" name="_cid[0]" >
<option value="">--Select Product--</option>
<option value="test">Test</option>
</select>
<input type="text" onchange="_doVariation(1);" value="1" id="_qty" name="_qty[0]"/>
<input type="text" class="textfield" value="0.00" id="item1_total" name="item1_total" readonly>
</td>
</tr>
</table>
<input type="hidden" value="1" id="total_row">
<input type="button" onclick="addRow()" value="Add Row">
This is my HTML code.
function addRow(){
var total_row = document.getElementById("total_row").value;
var _previousId = parseInt(total_row);
var new_id = parseInt(total_row) + 1;
document.getElementById("total_row").value = new_id;
var table = document.getElementById("testTable");
jQuery("#"+ table.rows[0].id).clone().appendTo("#testTable");
var totalTableRow = table.rows.length;
var currentRow = table.rows[totalTableRow-1];
currentRow.id = "row_"+new_id;
currentRow.innerHTML = currentRow.innerHTML.replace('_cid\['+ new_id-1 +'\]','_cid['+new_id+']');
currentRow.innerHTML = currentRow.innerHTML.replace(new RegExp("changeCustomCategory(this.value,'"+_previousId+"')","g"),'changeCustomCategory(this.value,'+new_id+')');
currentRow.innerHTML = currentRow.innerHTML.replace('_doVariation('+_previousId+')','_doVariation('+new_id+')');
}
You can perform your changes as the following:
//....
var newRow = jQuery("#"+ table.rows[0].id).clone().appendTo("#testTable");
//Change1
newRow.attr('name', '_cid['+new_id+']');
//Change2:
newRow.find('select').removeAttr('onchange').change(function() {
changeCustomCategory(this.value, new_id);
});
//Change3:
newRow.find('input:first').removeAttr('onchange').change(function() {
_doVariation(new_id);
});
//....
Demo: https://jsfiddle.net/4c0v2d50/
I would suggest sticking to jquery functions and not mixing too much with plain javascript. It makes it easier to code and follow.
I believe this is what your trying to do:
change HTML
id="_cid" name="_cid[0]"//change in select to
class="_cid" name="_cid[]"//_cid[] will automatically increment
id="_qty" name="_qty[0]"//same in input
class="_qty" name="_qty[]"
//you should also change
id="item1_total"
class="item1_total"
Javascript
function addRow(){
var new_id = $("#total_row").val() + 1;
$("#total_row").val(new_id);
var $currentRow = $("#testTable tr:first").clone();
$("#testTable").append(currentRow);
$currentRow.attr(id,"row_"+new_id);
$currentRow.find('select').attr('onclick',"changeCustomCategory(this.value,'"+new_id+"')");
$currentRow.find('._qty').attr('onchange','_doVariation('+new_id+')');
}
Removed the inline binding and bound to the element in the logic. Started changing the first thing you were trying to do with a regex. You can see how you like this approach.
jQuery(function($) {
//cache selectors
var $total_row = $("#total_row"),
$table = $("#testTable");
$(".addRow").on('click', function addRow() {
var total_row = $total_row.val(),
_previousId = parseInt(total_row),
new_id = _previousId + 1;
$total_row.val(new_id);
var $new_row = $table.find("tr").eq(0).clone();
$new_row.attr("id", "row_"+ new_id);
$new_row.find("select").attr("name", "_cid["+ (new_id - 1) +"]");
$table.append($new_row);
// currentRow.innerHTML = currentRow.innerHTML.replace('_cid\[' + new_id - 1 + '\]', '_cid[' + new_id + ']');
// currentRow.innerHTML = currentRow.innerHTML.replace(new RegExp("changeCustomCategory(this.value,'" + _previousId + "')", "g"), 'changeCustomCategory(this.value,' + new_id + ')');
// currentRow.innerHTML = currentRow.innerHTML.replace('_doVariation(' + _previousId + ')', '_doVariation(' + new_id + ')');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="testTable">
<tr id="row_1">
<td>
<select onchange="changeCustomCategory(this.value,'1');" id="_cid" name="_cid[0]">
<option value="">--Select Product--</option>
<option value="test">Test</option>
</select>
<input type="text" onchange="_doVariation(1);" value="1" id="_qty" name="_qty[0]" />
<input type="text" class="textfield" value="0.00" id="item1_total" name="item1_total" readonly>
</td>
</tr>
</table>
<input type="hidden" value="1" id="total_row">
<input type="button" value="Add Row" class="addRow">
function addRow(){
var total_row = parseInt(document.getElementById("total_row").value);
var _previousId = parseInt(total_row);
var new_id = parseInt(total_row) + 1;
var total_row = $("#total_row").val();
var _previousId = parseInt(total_row);
var new_id = parseInt(total_row) + 1;
$("#total_row").val(new_id);
var currentRow = $("#testTable tr:first").clone();
$("#testTable").append(currentRow);
$(currentRow).find('#_cid').attr("name","_cid["+new_id+"]");
$(currentRow).find('#_qty').attr("name","_qty["+new_id+"]");
$(currentRow).attr("id","row_"+new_id);
$(currentRow).find('#_cid').attr('onclick',"changeCustomCategory(this.value,'"+new_id+"')");
$(currentRow).find('#_qty').attr('onclick','_doVariation('+new_id+')');}
Working fiddle.
The id attribute should be unique so you could replace the duplicate ones by class attributen example :
<select class="_cid" name="_cid[0]" >
<input type="text" value="1" class="_qty" name="_qty[0]"/>
Better if you could avoid the inline-event onclick() and the overriding of parameters in every clone and define a general event one time and it will work for all the element, example :
$('body').on('change','._cid', function(){
//You code here
})
You don't need to increment the names you have just to leave the array signs empty [] and it will be incremented automatically, example :
<select class="_cid" name="_cid[]" >
<input type="text" value="1" class="_qty" name="_qty[]"/>
Hope this helps.
$(function(){
$('body').on('change','._cid', function(){
var id_number = $(this).parents('tr').attr('id').split('_')[1];
changeCustomCategory($(this).val(),id_number);
})
$('body').on('change','._qty', function(){
var id_number = $(this).parents('tr').attr('id').split('_')[1];
_doVariation(id_number);
})
})
function addRow()
{
var new_id = $('.row').length + 1;
var new_row = $("#testTable tr:first").clone().attr('id','row_'+new_id);
$("#testTable").append(new_row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="testTable">
<tr id="row_1" class="row">
<td>
<select class="_cid" name="_cid[]" >
<option value="">--Select Product--</option>
<option value="test">Test</option>
</select>
<input type="text" value="1" class="_qty" name="_qty[]"/>
<input type="text" class="textfield" value="0.00" class="item1_total" name="item1_total" readonly>
</td>
</tr>
</table>
<input type="button" onclick="addRow()" value="Add Row">
Im getting uncaught type error for estimateCost, also im having issues with how to double the price with spouse. I'm suppose to have an alert window that displays the estimate cost based on selections made from city, number of days, and other options. TY!
<html>
<head>
<script language="JavaScript">
var city_prices = new Array();
city_prices["New York City"] = 0;
city_prices["Boston"] = 0;
city_prices["San Francisco"] = 200;
city_prices["Los Angeles"] = 200;
// getCityPrice() finds the price based on the city .
// Here, we need to take user's the selection from radio button selection
function getCityPrice() {
var cityPrice = 0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["form1"];
//Get a reference to the cake the user Chooses name=radCity":
var selectedCity = theForm.elements["radCity"];
//Here since there are 4 radio buttons selectedCity.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCity.length; i++) {
//if the radio button is checked
if (selectedCity[i].checked) {
//we set cityPrice to the value of the selected radio button
//i.e. if the user choose NYC we set to 0
//by using the city_prices array
//We get the selected Items value
//For example city_prices["New York City".value]"
cityPrice = city_prices[selectedCity[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cityPrice
return cityPrice;
}
var number_days = new Array();
number_days["3"] = 450;
number_days["4"] = 600;
number_days["5"] = 750;
number_days["6"] = 900;
number_days["7"] = 1050;
number_days["8"] = 1350;
number_days["9"] = 1500;
number_days["10"] = 1650;
number_days["11"] = 1800;
number_days["12"] = 1950;
number_days["13"] = 2100;
number_days["14"] = 2250;
number_days["15"] = 2400;
//This function finds the day price based on the
//drop down selection
function getDayPrice() {
var dayPrice = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the select id="selNumberDays"
var selectedDays = theForm.elements["selNumberDays"];
//set dayPrice equal to value user chose
//For example number_days["3".value] would be equal to 450
dayPrice = number_days[selectedDays.value];
//finally we return dayPrice
return dayPrice;
}
//chksFirst() finds the candles price based on a check box selection
function chksFirst() {
var chkFirst = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkFirst"
var includeFirst = theForm.elements["chkFirst"];
//If they checked the box set first class to 500
if (includeFirst.checked == true) {
chkFirst = 500;
}
//finally we return the firstClass
return chkFirst;
}
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse() {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalPrice = getCityPrice() + getDayPrice() +
chksFirst() + chksSpouse();
alert(totalPrice);
}
</script>
</head>
<body>
<table align="left" width="600px" border="0" cellpadding="5px">
<tr>
<td>
<form name="form1" id="form1">
<table border="0">
<tr>
<td width="300px"><strong>Last Name: </strong>
</td>
<td width="300px">
<input type="text" name="txtFirstName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>First Name: </strong>
</td>
<td>
<input type="text" name="txtLastName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>Nationality: </strong>
</td>
<td>
<select name="selNationality">
<option value="amer">USA</option>
<option value="can">Canada</option>
<option value="mex">Mexico</option>
<option value="ger">Germany</option>
<option value="fra">France</option>
</select>
</td>
</tr>
<tr>
<td><strong>City you wish to visit: </strong>
</td>
<td>
<input type="radio" name="radCity" value="New York City" />New York City
<br />
<input type="radio" name="radCity" value="Boston" />Boston
<br />
<input type="radio" name="radCity" value="San Francisco" />San Francisco ($200 surcharge)
<br />
<input type="radio" name="radCity" value="Los Angeles" />Los Angeles ($200 surcharge)
<br/>
</td>
</tr>
<tr>
<td><strong>Number of days ($150 per day): </strong>
</td>
<td>
<select name="selNumberDays" id="selNumberDays">
<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">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</td>
</tr>
<tr>
<td><strong>Other options: </strong>
</td>
<td>
<input type="checkbox" name="chkFirst" id="chkFirst" />First Class Only ($500 surcharge)
<br />
<input type="checkbox" name="chkSpouse" id="chkSpouse" />Traveling with Spouse (All costs doubled)
<br />
</td>
</tr>
<tr>
<td align="right">
<input type="button" value="Give me an estimate!" onClick="estimateCost()" id="estimateCost" />
</td>
<td align="left">
<input type="reset" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
On the button input with the onClick="estimateCost()" code, remove the id="estimateCost". It's causing the error for some reason. You should really be using an onClick listener though instead of an inline onclick:
Inline onclick JavaScript variable
For the total with spouse, you might want to rework it to something like this where you pass the pre-spouse price into the chksSpouse function and use it's return as the total price.
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse(totalPrice) {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var preSpouseTotal = getCityPrice() + getDayPrice() + chksFirst();
var totalPrice = chksSpouse(preSpouseTotal);
alert(totalPrice);
}
I am trying to add two functions calculate1() and calculate2(). Both functions are taking values from function populate(). Is the code wrong? Once I enter an amount on both functions, the result is total amount undefined.
<form>
Car:
<select id="slct1" name="slct1" onchange="populate('slct1','slct2')">
<option value=""></option>
<option value="Fiat">Fiat</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
Type of Car:
<select id="slct2" name="slct2">
</select>
<label> Amount <input style="width:10%" type="number" name="amount1" id="amount1" onkeyup="result()"/> (g) </label>
<label> Total <input style="width:10%" type="number" name="answer1" id="answer1"/></label>
<input type="reset" name="Reset" value="Reset" onclick="rstFunction()"/>
<br><br><br>
<hr>
<br>
</form>
<!--Starts 2 selection-->
<form>
Food:
<select id="slct1a" name="slct1a" onchange="populate('slct1a','slct2a')">
<option value=""></option>
<option value="Fiat">Fiat</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
Type of Food:
<select id="slct2a" name="slct2a">
</select>
<label> Amount <input style="width:10%" type="number" name="amount2" id="amount2" onkeyup="result()"/> (g) </label>
<label> Total <input style="width:10%" type="number" name="answer2" id="answer2"/></label>
<input type="reset" name="Reset" value="Reset" onclick="rstFunction()"/>
<br><br><br>
<hr>
<br>
<p id="ansCAL"></p>
</form>
<input type="reset" onclick="resetFunctions()" value="Reset">
</script>
var t = total1 + total2;
function result() {
document.getElementById('ansCAL').value = calculate1() + calculate2();
}
function populate(select1, select2)
{
var Brand1 = document.getElementById(select1);
var Brand2 = document.getElementById(select2);
Brand2.innerHTML = "";
if(Brand1.value == "Fiat")
{
var optionArray = ["|","4000|Uno","5000|Ritmo","6000|Panda"];
}
else if(Brand1.value == "Dodge")
{
var optionArray = ["|","4000|Avanger","5000|Challengere","6000|Charger"];
}
else if(Brand1.value == "Ford")
{
var optionArray = ["|","7000|Mustang","8000|Shelby","focus|Focus"];
}
for(var option in optionArray)//the options within the optionArray
{
var pair = optionArray[option].split("|");//in tha variable pair is stored both value and label
var newOption = document.createElement("option");// option in the bracket is used to create new options or you can insert divs paragraph etc
newOption.value = pair[0];//pair 0 gives the value
newOption.innerHTML = pair[1];//pair 1 gives the label
Brand2.options.add(newOption);
}
}
function calculate1() {
Brand1 = document.getElementById('slct1').value;
Brand2 = document.getElementById('slct2').value;
multi=document.getElementById('amount1').value;
total1=parseInt((Brand2)*multi/100);
document.getElementById('answer1').value=total1;
document.getElementById("ansCAL").innerHTML = "<br>Total amount " + t;
}
function calculate2() {
Brand1 = document.getElementById('slct1a').value;
Brand2 = document.getElementById('slct2a').value;
multi=document.getElementById('amount2').value;/*to change accordingly amount1*/
total2=parseInt(((Brand2)*multi)/100);
document.getElementById('answer2').value=total2;/*to change accordingly amount1*/
document.getElementById("ansCAL").innerHTML = "<br>Total amount " + t;
}
function resetFunctions() {
//using the array forEach method on the form
Array.prototype.forEach.call(document.forms,function(el,idx,array){
//the method parameters are element, index and the array
// we loop through all the forms and invoking reset()
el.reset();
});
result();
}
function rstFunction()
{
document.getElementById("ansCAL").innerHTML = "<br>Total amount" + result().value;
}
</script>
The answer was to increase the total in every calculate function. Example (total + total1). Removed the variable t and declared the totals in the printout section.