I wrote a class for simple booking system. Data is kept in an array and all the edit and delete operations are performed to this array using functions inside that class. So placed buttons to perform edit and delete. How can I call a method from my class to the onclick event of a button. Please check the following code.
Class file
/**
* Class for handling general insert, update, delete
* oprations for a room booking system.
*/
var bookingSystem = function (){
this.editMode = false;
this.editIndex = false;
// option data for Number of persons drop down
this.numPersonsOpts = [
{name : 1, val : 1},
{name : 2, val : 2},
{name : 3, val : 3},
{name : 4, val : 4}
];
// Sample data to show initially
this.bookingData = [
{name : "John", roomType : "AC", numPersons : 3},
{name : "Mishal", roomType : "Non AC", numPersons : 1}
];
var self = this; // get a reference to this.
/**
* Prepare and show options for dropdown
* #param string selectorId id of the dropdown
* #param object optionData array object contains name and value for the options
*/
this.showOptions = function (selectorId, optionData){
var optsStr = "";
for (var i=0; i<optionData.length; i++) {
optsStr += '<option value='+optionData[i].val+'>'+optionData[i].name+'</option>';
};
document.getElementById(selectorId).innerHTML = optsStr;
}
/**
* To save and update data
*/
this.saveBooking = function (){
var name = document.getElementById("bookingName").value;
if(name){
var singleEntry = {
name : name,
roomType : document.querySelector('input[name="roomType"]:checked').value == 1? 'AC' : 'Non AC',
numPersons : document.getElementById("numPersonSelect").value
}
if(self.editMode){
if(typeof(self.editIndex) == 'number'){
self.bookingData[self.editIndex] = singleEntry;
self.editIndex = false;
}
self.editMode = false;
}else{
self.bookingData.push(singleEntry);
}
document.getElementById("bookingName").value = '';
self.renderTemplate();
}
}
/**
* To edit a particular item
* #param number index array index to edit
*/
self.edit = function (index){
self.editIndex = index;
self.editMode = true;
document.getElementById("bookingName").value = self.bookingData[self.editIndex].name;
document.querySelector('input[name="roomType"][value="1"]').checked = self.bookingData[self.editIndex].roomType == 'AC'? true: false;
document.querySelector('input[name="roomType"][value="2"]').checked = self.bookingData[self.editIndex].roomType == 'Non AC'? true: false;
for(var i=0; i<this.numPersonsOpts.length; i++){
document.getElementById("numPersonSelect").options[i].selected = false;
}
document.getElementById("numPersonSelect").options[(self.bookingData[self.editIndex].numPersons)-1].selected = true;
}
/**
* To delete a particular item
* #param number index array index to delete
*/
self.deleteItem = function (index){
self.bookingData.splice(index,1);
self.renderTemplate();
}
/**
* To preapre table content and show it.
*/
this.renderTemplate = function (){
var template = '';
if(self.bookingData.length > 0){
for(var i= 0; i< self.bookingData.length; i++){
template += '<tr>';
template += '<td>'+self.bookingData[i].name+'</td>';
template += '<td>'+self.bookingData[i].roomType+'</td>';
template += '<td>'+self.bookingData[i].numPersons+'</td>';
template += '<td><button type="button" onclick = "edit('+i+')">Edit</button></td>';
template += '<td><button type="button" onclick = "deleteItem('+i+')">Delete</button></td>';
template += '</tr>';
}
}else{
template += '<tr>';
template += '<td colspan="2"> No Data Found.</td>';
template += '</tr>';
}
document.getElementById("renderTable").innerHTML = template;
}
}
General code for initializing it.
var bs = new bookingSystem(); // Create object for bookingSystem
var init= function(){
bs.showOptions('numPersonSelect',bs.numPersonsOpts); // Show number of persons option
// Save Button event
var btn = document.getElementById("saveBookingBtn");
if(btn.addEventListener){
btn.addEventListener('click',bs.saveBooking);
}else{
btn.attachEvent('onclick',bs.saveBooking);
}
bs.renderTemplate();
}
function edit(index){
bs.edit(index);
}
function deleteItem(index){
bs.deleteItem(index);
}
init() is called from body onload event. Following is the html code.
<body onload="init()">
<form>
<div class="formRow">
<label>Name : </label>
<input type="text" id="bookingName" name="bookingName" value="">
</div>
<div class="formRow">
<label>AC/NO : </label>
<input type="radio" value="1" name="roomType" checked="checked"> AC
<input type="radio" value="2" name="roomType"> Non AC
</div>
<div class="formRow">
<label>Number of Persons</label>
<select name="numPerson" id="numPersonSelect">
</select>
</div>
<div>
<button type="button" id="saveBookingBtn">Save</button>
</div>
</form>
<div id="renderArea"></div>
<table>
<td>Name</td>
<td>Room Type</td>
<td>Person(s)</td>
<td>Edit</td>
<td>Delete</td>
<tbody id="renderTable"></tbody>
</table>
</body>
This code is working fine. But here I created edit and deleteItem methods to call the actual edit and delete methods wrote in the class. How to use that methods from class directly to onclick event. Like this <button onclick="bs.edit()">Edit</button>
$(function(){
var productManagement = function() {
var products = [
{id:1, name: 'samsung galaxy', price: 6000, description: 'samsung galaxy mobile phone'},
{id:2, name: 'apple', price: 10000, description: 'apple mobile phone'},
{id:3, name: 'nokia', price: 5000, description: 'nokia mobile phone'},
{id:4, name: 'motorola', price: 7000, description: 'motorola mobile phone'}
];
var selectedProducts = {};
var $this = this;
this.displayProducts = function() {
$.each(products, function(k, product){
$('.content').append($this.getProductInfo(product));
});
}
this.getProductInfo = function(product) {
var html = '<div class="item" id="' + product.id + '">';
html += '<table><tr><td>Name</td><td>: ' + product.name + '</td></tr>';
html += '<tr><td>Price</td><td>: ' + product.price + '</td></tr>';
html += '<tr><td>Description</td><td>: ' + product.description + '</td></tr>';
html += '<tr><td colspan="2"><button class="addToCart">Add To Cart</td></tr></table>'
html += '</div>';
return html;
}
this.delegate = function() {
$('body').delegate('.addToCart', 'click', function(){
var id = $(this).closest('div').attr('id');
if( selectedProducts[id] == undefined) {
selectedProducts[id] = 1;
}else{
selectedProducts[id]++;
}
// selectedProducts.push(id);
$('.content').hide();
$('.cart').show();
$this.showCart();
});
$('body').delegate('#continueShopping', 'click', function(){
$('.content').show();
$('.cart').hide();
});
$('body').delegate('.remove', 'click', function(){
var id = $(this).closest('tr').attr('id');
$this.removeFromSelected(id);
});
}
this.removeFromSelected = function(productId){
$.each(selectedProducts, function(pid, numberOfItems){
if( pid == productId) {
delete selectedProducts[pid];
return false;
}
});
$this.showCart();
}
this.showCart = function() {
var html = '<table><tr><th>Name</th><th>Unit Price</th><th>No of Items</th><th>Total Price</th><th>Action</th></tr>';
var total = 0;
$.each(selectedProducts, function(productId,numberOfItems){
var productInfo = $this.getProduct(productId);
html += '<tr id="' + productId + '"><td>' + productInfo.name + '</td><td>' + (productInfo.price) + '</td><td>'+ numberOfItems + '</td><td>' + (productInfo.price * numberOfItems) + '</td><td><button class="remove">Remove</button></td></tr>';
total += productInfo.price;
});
html += '</table>';
html += '<br /><br />Grand Total:' + total;
$('#cartItems').empty();
$('#cartItems').append(html);
}
this.getProduct = function(productId) {
var found = {};
$.each( products, function(id, product){
if( product.id == productId) {
found = product;
return false;
}
})
return found;
}
}
var PM = new productManagement();
PM.delegate();
PM.displayProducts();
})
.header {
background-color:#E0E8FF;
padding:5px;
text-align:center;
}
.content {
padding-left:15%;
padding-top:40px;
width:100%;
overflow:auto
}
.cart {
padding-left:15%;
padding-top:40px;
width:100%;
}
.footer {
background-color:#E0E8FF;
text-align:center;
}
.item {
width:25%;
height:150px;
overflow:auto;
border:1px solid black;
float:left
}
The function which you are calling is not exist in the context for delete when document loaded. By defining the function as global function, it is working.
/**
* Class for handling general insert, update, delete
* oprations for a room booking system.
*/
var bookingSystem = function (){
this.editMode = false;
this.editIndex = false;
// option data for Number of persons drop down
this.numPersonsOpts = [
{name : 1, val : 1},
{name : 2, val : 2},
{name : 3, val : 3},
{name : 4, val : 4}
];
// Sample data to show initially
this.bookingData = [
{name : "John", roomType : "AC", numPersons : 3},
{name : "Mishal", roomType : "Non AC", numPersons : 1}
];
var self = this; // get a reference to this.
/**
* Prepare and show options for dropdown
* #param string selectorId id of the dropdown
* #param object optionData array object contains name and value for the options
*/
this.showOptions = function (selectorId, optionData){
var optsStr = "";
for (var i=0; i<optionData.length; i++) {
optsStr += '<option value='+optionData[i].val+'>'+optionData[i].name+'</option>';
};
document.getElementById(selectorId).innerHTML = optsStr;
}
/**
* To save and update data
*/
this.saveBooking = function (){
var name = document.getElementById("bookingName").value;
if(name){
var singleEntry = {
name : name,
roomType : document.querySelector('input[name="roomType"]:checked').value == 1? 'AC' : 'Non AC',
numPersons : document.getElementById("numPersonSelect").value
}
if(self.editMode){
if(typeof(self.editIndex) == 'number'){
self.bookingData[self.editIndex] = singleEntry;
self.editIndex = false;
}
self.editMode = false;
}else{
self.bookingData.push(singleEntry);
}
document.getElementById("bookingName").value = '';
self.renderTemplate();
}
}
/**
* To edit a particular item
* #param number index array index to edit
*/
self.edit = function (index){
self.editIndex = index;
self.editMode = true;
document.getElementById("bookingName").value = self.bookingData[self.editIndex].name;
document.querySelector('input[name="roomType"][value="1"]').checked = self.bookingData[self.editIndex].roomType == 'AC'? true: false;
document.querySelector('input[name="roomType"][value="2"]').checked = self.bookingData[self.editIndex].roomType == 'Non AC'? true: false;
for(var i=0; i<this.numPersonsOpts.length; i++){
document.getElementById("numPersonSelect").options[i].selected = false;
}
document.getElementById("numPersonSelect").options[(self.bookingData[self.editIndex].numPersons)-1].selected = true;
}
/**
* To delete a particular item
* #param number index array index to delete
*/
self.deleteItem = function (index){
console.log("called once");
self.bookingData.splice(index,1);
self.renderTemplate();
}
/**
* To preapre table content and show it.
*/
this.renderTemplate = function (){
var template = '';
if(self.bookingData.length > 0){
for(var i= 0; i< self.bookingData.length; i++){
template += '<tr>';
template += '<td>'+self.bookingData[i].name+'</td>';
template += '<td>'+self.bookingData[i].roomType+'</td>';
template += '<td>'+self.bookingData[i].numPersons+'</td>';
template += '<td><button type="button" onclick = "return callEdit('+i+')">Edit</button></td>';
template += '<td><button type="button" onclick = "return callDelete('+i+')">Delete</button></td>';
template += '</tr>';
}
}else{
template += '<tr>';
template += '<td colspan="2"> No Data Found.</td>';
template += '</tr>';
}
document.getElementById("renderTable").innerHTML = template;
}
this.init= function(){
console.log("called");
self.showOptions('numPersonSelect',self.numPersonsOpts); // Show number of persons option
// Save Button event
var btn = document.getElementById("saveBookingBtn");
if(btn.addEventListener){
btn.addEventListener('click',self.saveBooking);
}else{
btn.attachEvent('onclick',self.saveBooking);
}
self.renderTemplate();
}
}
var bs = new bookingSystem(); // Create object for bookingSystem
bs.init();
window.callEdit = function(index){
bs.edit(index);
}
window.callDelete = function(index){
bs.deleteItem(index);
}
check this example here
Related
This is the code I used for my shopping cart. When I use this code the problem is that when I click the clear button, and then I add another item, the previous Item that I cleared came back
I have tried to move around the saveCart function so it will properly do its job, but there are still no progress in solving the problem
This is the buttons to buy the Item ( I only show the button since probably the effect is only at here )
<input type="button" name="" value="B U Y" class="buyBut add-to-cart" data-name="Avocado & Brownie Cake" data-price="150000">
<input type="button" name="" value="B U Y" class="buyBut add-to-cart" data-name="Strawberry & Watermelon Cake" data-price="65000">
This is the space to show the items and the clear button
<table id="show-cart">
<br>
</table>
<br>
<button id="clear-cart" onClick="clearCart()">Clear Cart</button>
This is the JQuery ( I use JQuery 3.3.1.min )
$(".add-to-cart").click(function(event){
event.preventDefault();
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
addItemToCart(name, price, 1);
displayCart();
});
function displayCart(){
var cartArray = listCart();
var output ="";
for (var i in cartArray){
output +=
"<tr>"
+"<td class='itemName'>"
+cartArray[i].name
+"</td>"
+"<td class='itemPrice'>"
+"Rp "
+cartArray[i].price
+"</td>"
+"<td>"
+" "
+"</td>"
+"<td class='itemCount'>"
+cartArray[i].count
+"</td>"
+"<td style='width:20px;'>"
+"</td>"
+"<td>"
+"<span class='sub-item' data-name='"+cartArray[i].name+"'>-</span>"
+"</td>"
+"<td style='width:12px;'>"
+"</td>"
+"<td>"
+"<span class='delete-item' data-name='"+cartArray[i].name+"'>×</span>"
+"</td>"
+"</tr>"
}
$("#show-cart").html(output);
$("#total-cart").html( totalCart() );
$("#cart-count").html( countCart() );
saveCart();
}
$("#show-cart").on("click", ".delete-item", function(event) {
var name = $(this).attr("data-name");
removeItemFromCartAll(name);
displayCart();
});
$("#show-cart").on("click", ".sub-item", function(event) {
var name = $(this).attr("data-name");
removeItemFromCart(name);
displayCart();
});
This is the Javascript
var cart = [];
var Item = function(name, price, count){
this.name = name;
this.price = price;
this.count = count;
}
// adding item to cart
function addItemToCart(name, price, count) {
for (var i in cart) {
if (cart[i].name === name ) {
cart[i].count += count;
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
saveCart();
}
// Removes 1 Item From Cart
function removeItemFromCart(name){
for (var i in cart) {
if (cart[i].name === name){
cart[i].count --;
if (cart[i].count === 0){
cart.splice(i, 1)
}
break;
}
}
saveCart();
}
// Clear 1 Object From Cart
function removeItemFromCartAll(name){
for (var i in cart) {
if (cart[i].name === name){
cart.splice(i,1);
break;
}
}
saveCart();
}
// Clear The Cart
function clearCart(){
cart = [];
document.getElementById("show-cart").innerHTML = "";
saveCart();
document.getElementById("total-cart").innerHTML = "0";
}
// Shows Total Count Of Item
function countCart(){
var totalCount = 0;
for (var i in cart){
totalCount += cart[i].count;
}
return totalCount;
}
// Shows Total Price
function totalCart(){
var totalCost = 0;
for (var i in cart){
totalCost += cart[i].price * cart[i].count
}
return totalCost;
saveCart();
}
// Returns an array
function listCart(){
var cartCopy = [];
for (var i in cart){
var item = cart[i];
var itemCopy = {};
for (var p in item){
itemCopy[p] = item[p];
}
cartCopy.push(itemCopy);
}
return cartCopy;
}
function saveCart(){
localStorage.setItem("shoppingCart", JSON.stringify(cart));
}
function loadCart(){
cart = JSON.parse(localStorage.getItem("shoppingCart"));
}
loadCart();
displayCart();
I expected the output that when the clear button is clicked, and I add an item, the item shown is only 1 and the previous item in the cart before I clicked is gone.
Sorry, I can not read your code, there is too much to say, and I guess your mistake comes from bad management on the addressing of tables and their elements.
I adapted one of my old code to match it to your work; this is a big technical gap for you, but I think it will be useful for you to program on better rails :)
HTML part:
`
<div id="Bt_BUY">
<button data-price="150000" >Avocado & Brownie Cake</button>
<button data-price="65000" >Strawberry & Watermelon Cake</button>
</div>
<table id="show-cart">
<thead>
<tr>
<th>name</th>
<th>price</th>
<th>count</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button id="clear-cart" >Clear Cart</button>
`
JS part
`
"use strict"
const Buy_obj = {
List : [],
DisplayTable : null,
add( x_name, x_price, x_count ) {
let idx = this.List.findIndex( e=>e.name=== x_name);
if (idx>=0)
{ this.List[idx].count += x_count; }
else
{ this.List.push( { 'name' : x_name, 'price' : x_price, 'count' : x_count } ) }
this.saveList();
this.drawTable();
}
,
clear(){
this.List.length = 0;
this.saveList();
this.drawTable();
}
,
remove( x_name ) {
let idx = this.List.findIndex( e=>e.name=== x_name);
if (idx>=0) {
this.List[idx].count--;
if (this.List[idx].count <= 0)
{ this.List.splice(idx,1) }
}
this.saveList();
this.drawTable();
}
,
saveList() {
localStorage.setItem("shoppingCart", JSON.stringify(this.List));
}
,
loadList() {
let ls_list = localStorage.getItem("shoppingCart");
if ( ls_list)
{ this.List = JSON.parse(ls_list); }
}
,
initialise( $xTable ) {
this.DisplayTable = $xTable;
this.loadList();
this.drawTable();
}
,
drawTable() {
this.DisplayTable.innerHTML = "";
this.List.forEach(e=>{
let
T_row = this.DisplayTable.insertRow(-1),
T_cell_0 = T_row.insertCell(0),
T_cell_1 = T_row.insertCell(1),
T_cell_2 = T_row.insertCell(2);
T_cell_0.textContent = e.name;
T_cell_1.textContent = e.price;
T_cell_2.textContent = e.count;
})
}
}
// *************************** Main *****************************
Buy_obj.initialise ( document.querySelector('#show-cart tbody') );
document.querySelector('#Bt_BUY').onclick = function(e) {
if (!e.target.matches('button')) return;
e.stopPropagation();
Buy_obj.add( e.target.textContent, e.target.dataset.price, 1 );
}
document.querySelector('#clear-cart').onclick = function(e) {
Buy_obj.clear();
}
`
Im developing a webapplication which uses struts,when i try the code on my system which im currently developing,then its working fine but when i deploy it on live server its not calling the Javascript function which also uses c:forEach inside it.
I dont know what i am doing wrong,i do know that theres a lot of questions regarding this but i tried everything and none of them works for my scenario.This is my Jsp file.
<body>
<logic:equal name="menu" value="package">
<h2><span>Packages</span></h2>
<span class="dropdown place">
<a class="dd_btn" href="javascript:void(0);" >Action</a>
<ul class="subdrop">
<li><a onclick="display('addPackDiv')" href="javascript:void(0);">Create New</a></li>
<li><a onclick="setPackage();" href="javascript:void(0);">Edit</a></li>
<li><a onclick="return delPackage();" href="javascript:void(0);">Delete</a></li>
<li><a onclick="return exportPackages();" href="javascript:void(0);">Export</a></li>
<li><a onclick="return featurePackages('feature');" href="javascript:void(0);">Feature</a></li>
<li><a onclick="return featurePackages('unfeature');" href="javascript:void(0);">UnFeature</a></li>
</ul>
</span>
</logic:equal>
<script type="text/javascript">
function setPackage(){
alert("in setpackage");
var ids = "";
var chbxs = document.forms[0].actionCheckBox;
if (chbxs.length != undefined) {
for (i = 0; i < chbxs.length; i++)
{
if (chbxs[i].type == 'checkbox' && chbxs[i].checked)
{
var cname = chbxs[i].value;
if (!cname)
continue;
if (ids == "")
ids = cname;
else
ids += "," + cname + "";
}
}
if (ids == null || ids == "") {
jAlert("Please select one item to edit");
return;
}
if (ids.split(",").length > 1) {
jAlert("Select only one item to edit.");
return;
}
} else { //If Not Node List.
try {
ids = chbxs.value;
} catch (err) {
}
}
//alert("step 1 "+ids);
/* collection reset */
document.getElementById('updateCollection').innerHTML = '';
var updateCollectionSel = document.getElementById('updateCollectionSel');
updateCollectionSel.innerHTML = '';
var innCollectionHtml = '';
<c:forEach var="CollectionDTO" items="${requestScope.allCollectionList}">
innCollectionHtml += "<option value='${CollectionDTO.collectionId}'>${CollectionDTO.collectionName}</option>";
</c:forEach>
updateCollectionSel.innerHTML = innCollectionHtml;
//alert("innCollectionHtml "+innCollectionHtml);
//END
//alert("step 2");
/* program reset */
document.getElementById('updateProgram').innerHTML = '';
var updateProgramSel = document.getElementById('updateProgramSel');
updateProgramSel.innerHTML = '';
var innProHtml ='';
<c:forEach var="ProgramDTO" items="${requestScope.allProgramList}">
innProHtml += "<option value='${ProgramDTO.programid}'>${ProgramDTO.name}</option>";
</c:forEach>
updateProgramSel.innerHTML = innProHtml;
//alert("innProHtml "+innProHtml);
//END
// alert("step 3");
/* channel reset */
document.getElementById('updateChannel').innerHTML = '';
var updateChannelSel = document.getElementById('updateChannelSel');
updateChannelSel.innerHTML = '';
var innChannelHtml = '';
<c:forEach var="SMSChannelDTO" items="${requestScope.allChannelList}">
innChannelHtml += "<option value='${SMSChannelDTO.channelId}'>${SMSChannelDTO.name}</option>";
</c:forEach>
updateChannelSel.innerHTML = innChannelHtml;
//alert("innChannelHtml "+innChannelHtml);
//END
//alert("step 4");
var packageId = ids;
var server = '<%= request.getServerName()%>';
if (server == 'localhost') {
server = server + ":" + '<%= request.getServerPort()%>';
}
<c:forEach var="packageDTO" items="${requestScope.packageList}">
if (packageId == '${packageDTO.packageId}') {
<c:forEach var="DistributorDTO" items="${requestScope.displayDistributor}">
var allDistName1= '${DistributorDTO.email_id}';
document.getElementById(allDistName1).checked = false;
document.getElementById("prepaidprice"+allDistName1).value='0.0';
document.getElementById("postpaidprice"+allDistName1).value='0.0';
</c:forEach>
document.getElementById('updatePackageName').value = '${packageDTO.name}';
document.getElementById('updatePackageImg1').value = '${packageDTO.image}'
document.getElementById('updatefeaturedImage').value = '${packageDTO.featuredImage}';
<%--document.getElementById('packImg').src = 'http://'+server+'/SMS/'+'${packageDTO.image}';--%>
/* refill remaining channel list */
var packagesChannelIdArr = new Array(${fn:length(packageDTO.channelList)});
var i = 0;
<c:forEach var="SMSChannelDTO" items="${packageDTO.channelList}">
packagesChannelIdArr[i] = '${SMSChannelDTO.channelId}';
i++;
</c:forEach>
setChannels(packagesChannelIdArr);
//END
/* refill remaining program list */
var packagesEventIdArr = new Array(${fn:length(packageDTO.programList)});
var j = 0;
<c:forEach var="ProgramDTO" items="${packageDTO.programList}">
packagesEventIdArr[j] = '${ProgramDTO.programid}';
j++;
</c:forEach>
setPrograms(packagesEventIdArr);
//END
/* refill remaining collection list */
var packagesCollectionIdArr = new Array(${fn:length(packageDTO.collectionList)});
var k = 0;
<c:forEach var="CollectionDTO" items="${packageDTO.collectionList}">
packagesCollectionIdArr[k] = '${CollectionDTO.collectionId}';
k++;
</c:forEach>
setCollection(packagesCollectionIdArr);
//END
/* fill programs */
var x = document.getElementById('updateProgram');
<c:forEach var="ProgramDTO" items="${packageDTO.programList}">
x.innerHTML += "<option value='${ProgramDTO.programid}'>${ProgramDTO.name}</option>";
</c:forEach>
//END
/* fill channels */
var y = document.getElementById('updateChannel');
<c:forEach var="SMSChannelDTO" items="${packageDTO.channelList}">
y.innerHTML += "<option value='${SMSChannelDTO.channelId}'>${SMSChannelDTO.name}</option>";
</c:forEach>
//END
/* fill collection */
var z = document.getElementById('updateCollection');
<c:forEach var="CollectionDTO" items="${packageDTO.collectionList}">
z.innerHTML += "<option value='${CollectionDTO.collectionId}'>${CollectionDTO.collectionName}</option>";
</c:forEach>
//END
<c:forEach var="DistributorDTO" items="${requestScope.displayDistributor}">
var allDistName= '${DistributorDTO.email_id}';
<c:forEach var="DistributorDTO" items="${packageDTO.distributorListForPack}">
var packdist='${DistributorDTO.email_id}';
if(allDistName === packdist){
document.getElementById("prepaidprice"+packdist).value='${DistributorDTO.prepaidprice}';
document.getElementById("postpaidprice"+packdist).value='${DistributorDTO.postpaidprice}';
document.getElementById(packdist).checked = true;
}
</c:forEach>
</c:forEach>
document.getElementById('updateDescription').value = "${packageDTO.description}";
document.getElementById('packImgName').value = '${packageDTO.image}';
document.getElementById('updatePackageImg1').style.display = 'inline';
document.getElementById('updatePrice').value = '${packageDTO.subscriptionPrice}';
document.getElementById('updateCurrency').value = '${packageDTO.priceUnit}';
document.getElementById('updateSubscriptionPeriod').value = '${packageDTO.subscriptionPeriod}';
var distributorType= '${packageDTO.distributorType}';
if(distributorType === "List distributors"){
document.getElementById('edit_pack_dist_dropdown').value ="List distributorsdisp";
}else{
document.getElementById('edit_pack_dist_dropdown').value = '${packageDTO.distributorType}';
}
document.getElementById('updatePostpaidPrice').value = '${packageDTO.updatePostpaidPrice}';
document.getElementById('updatePostPaidCurrency').value = '${packageDTO.updatePostPaidCurrency}';
document.getElementById('updateUnit').value = '${packageDTO.periodUnit}';
display('editPackDiv');
<%-- document.getElementById('updateFeatured').checked = <c:if test="${packageDTO.featured == 1}">true</c:if><c:if test="${packageDTO.featured == 0}">false</c:if>; --%>
} else if (packageId == '' || packageId == 'Select') {
document.getElementById('updatePackageName').value = '';
document.getElementById('packImgName').value = '';
document.getElementById('updatePackageImg1').style.display = 'none';
document.getElementById('updateDescription').value = '';
deselectChannelIds();
document.getElementById('packImg').src = '';
document.getElementById('updatePrice').value = '';
document.getElementById('updateCurrency').value = 'INR';
document.getElementById('updateSubscriptionPeriod').value = '';
document.getElementById('edit_pack_dist_dropdown').value = '';
document.getElementById('updatePostpaidPrice').value = '';
document.getElementById('updatePostPaidCurrency').value = '';
document.getElementById('updateUnit').value = 'day';
//document.getElementById('updateFeatured').checked = false;
}
</c:forEach>
return false;
}
I get Uncaught ReferenceError: setPackage() is not defined error in chrome console.
Please do help me on this.
I am trying to make this work with the help of jQuery docs but not success so far.
I have two boxes paynow and payfull that has 0 initial value but I am filling these boxes dynamically (jQuery) with product prices.
Now I have to update these values further with select option to discount the price (multiply with data-percent). This is the HTML.
<select class="discount">
<option data-percent="0">Select Discount Coupon</option>
<option data-percent="5">ABCD</option>
<option data-percent="10">EFGH</option>
<option data-percent="15">IJKL</option>
</select>
<span class="price" id="paynow">$0.00</span>
<span class="price" id="payfull">$0.00</span>
EDIT: jQuery code
$(document).ready(function() {
// For Calculator
function Cost_Calculator() {
var Currency = '$';
var messageHTML = 'Please contact us for a price.';
function CostFilter(e) {
return e;
}
//Calculate function
function calculate() {
//Blank!
var CalSaveInfo = [];
$('#cost_calc_custom-data, #cost_calc_breakdown').html('');
//Calculate total
var calCost = 0;
var calculate_class = '.cost_calc_calculate';
$('.cost_calc_active').each(function() {
//Calculation
calCost = calCost + parseFloat($(this).data('value'));
//Add to list
var optionName = $(this).attr('value');
var appendName = '<span class="cost_calc_breakdown_item">' + optionName + '</span>';
var optionCost = $(this).attr('data-value');
var appendCost = '<span class="cost_calc_breakdown_price">' + Currency + optionCost + '</span>';
if (optionCost != "0") {
var appendItem = '<li>' + appendName + appendCost + '</li>';
}
//hidden data
var appendPush = ' d1 ' + optionName + ' d2 d3 ' + optionCost + ' d4 ';
$('#cost_calc_breakdown').append(appendItem);
CalSaveInfo.push(appendPush);
});
//Limit to 2 decimal places
calCost = calCost.toFixed(2);
//Hook on the cost
calCost = CostFilter(calCost);
var CustomData = '#cost_calc_custom-data';
$.each(CalSaveInfo, function(i, v) {
$(CustomData).append(v);
});
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
}
//Calculate on click
$('.cost_calc_calculate').click(function() {
if ($(this).hasClass('single')) {
//Add cost_calc_active class
var row = $(this).data('row');
//Add class to this only
$('.cost_calc_calculate').filter(function() {
return $(this).data('row') == row;
}).removeClass('cost_calc_active');
$(this).addClass('cost_calc_active');
} else {
// Remove class if clicked
if ($(this).hasClass('cost_calc_active')) {
$(this).removeClass('cost_calc_active');
} else {
$(this).addClass('cost_calc_active');
}
}
//Select item
var selectItem = $(this).data('select');
var currentItem = $('.cost_calc_calculate[data-id="' + selectItem + '"]');
var currentRow = currentItem.data('row');
if (selectItem !== undefined) {
if (!$('.cost_calc_calculate[data-row="' + currentRow + '"]').hasClass('cost_calc_active'))
currentItem.addClass('cost_calc_active');
}
//Bring in totals & information
$('#cost_calc_breakdown_container, #cost_calc_clear_calculation').fadeIn();
$('.cost_calc_hide').hide();
$('.cost_calc_calculate').each(function() {
calculate();
});
return true;
});
$('#cost_calc_clear_calculation').click(function() {
$('.cost_calc_active').removeClass('cost_calc_active');
calculate();
$('#cost_calc_breakdown').html('<p id="empty-breakdown">Nothing selected</p>');
return true;
});
}
//Run cost calculator
Cost_Calculator();
});
How about this one:
var totalPayNowPrice=parseFloat($('#paynow').text());
var totalPayFullPrice=parseFloat($('#payfull').text());
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
});
Just put the $ sign in you spans after the numbers, in order to parse function would work.
JSFIDDLE
UPDATE
From another point I think there is a better solution to use prototype and store you current prices in spans inside global variable, then you can use them wherever you want. Here the pseudo prototype for your use, if you`d like just customize it for you using:
function Test(){
this.totalPayNowPrice=1;//the is 1 only for check code working
this.totalPayFullPrice=1;
}
Test.prototype={
init: function(){
var scope=this;
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((scope.totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((scope.totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
},
updatePaynowPrice:function(newPrice){
this.totalPayNowPrice=totalPayNowPrice;
},
updatePayfullPrice:function(newPrice){
this.totalPayFullPrice=totalPayNowPrice;
}
}
you can use
$(document).ready(function(){
// get price from #paynow (just a number)
var getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
var getPayfull = $('#payfull').text().match(/\d+/);
$('.discount').on('change', function(){
// get data-percent from selected option
var discount = parseFloat($(this).find('>option:selected').attr('data-percent'));
//alert(discount +'///'+ getPaynow+'///'+ getPayfull);
//update price for #paynow and #payfull
$('#paynow').text('$'+parseFloat(getPaynow - (getPaynow * discount / 100)));
$('#payfull').text('$'+parseFloat(getPayfull - (getPayfull * discount / 100)));
});
});
Working Demo
in your code you can update prices after this part of code
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
//get price from #paynow (just a number)
getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
getPayfull = $('#payfull').text().match(/\d+/);
My code works fine for the first time but the second time, my object functions returns undefined.
_MANAGE = new Object()
//----------------------------- BG ------------------------------//
var saveBg = {
name : "bg",
url : "AN URL",
data : {
ID :function($this){ return $this.parents("tr").data("id") },
name :function($this){ return $this.parents("tr").find(".name").val() }
}
}
//----------------------------------------------------------------------//
//------------------------- SAVE FUNCTION ------------------------------//
var saveButton = [saveBg];
$(".buttonSave").on("click", function(){
console.log(saveBg);
var buttonName = $(this).data("name");
_MANAGE.saveButton(saveButton, buttonName, $(this));
})
//----------------------------------------------------------------------//
//------------------------- SAVE BUTTON ------------------------------//
_MANAGE.saveButton = function(saveButton, buttonName, $this_button){
for(var i = 0; i < saveButton.length; i++){
if(buttonName == saveButton[i]["name"]){
for(var param in saveButton[i]["data"]){
if(typeof(saveButton[i]["data"][param]) == "function"){
saveButton[i]["data"][param] = saveButton[i]["data"][param]($this_button);
} else {
saveButton[i]["data"][param] = $(saveButton[i]["data"][param]).val();
}
}
if(!saveButton[i]["success"]){
saveButton[i]["success"] = function() {
$this_button.children()
.hide()
.replaceWith("<span style='font-size:0.7em;''>Saved</span>").fadeIn("slow");
setInterval(function(){
$this_button.children().hide().replaceWith('<span class="icon-floppy"> </span>').fadeIn("slow");
}, 1500);
}
}
_MANAGE.ajaxButton(saveButton[i]);
}
}
}
//----------------------------------------------------------------------//
//------------------------- ASYNC FUNCTION ------------------------------//
_MANAGE.ajaxButton = function(ajaxButton) {
var stringData = "";
if(ajaxButton.data){
var loop = 0;
for(var param in ajaxButton["data"]){
if(loop == 0){
stringData += param + "=" + ajaxButton["data"][param];
} else {
stringData += "&" + param + "=" + ajaxButton["data"][param];
}
loop++;
}
}
if(ajaxButton.url && ajaxButton.success && stringData != "") {
$.ajax({
url : ajaxButton.url,
data : stringData,
dataType : "text",
success : ajaxButton.success
});
}
}
<!--THE TABLE -->
<tr data-id="4">
<td><b>4</b></td>
<td><input class="name" type="text" value="A VALUE"></td>
<td>
<!-- THE BUTTON -->
<div class="buttonSave" data-name="bg">
<span class="icon-floppy"></span>
</div>
</td>
</tr>
How to give Input tag Attribute type button value at Runtime in Meteor JS as shown below:
newButton = document.createElement('input');
newButton.value = ''; - Here value i need like as i.e , val ="{{btnValue}}"
I'm not familiar with Meteor JS, so please offer any suggestions.
Html Code I need like as below in Runtime JS:
// Manually Creating button
<input type="button" id="no" val ="{{btnValue}}">
My HTML Code :
<head>
<title>TICTACTOE App 1.3</title>
</head>
<body>
{{> uname}}
{{> main}}
{{> games }}
</body>
<template name="uname">
<h1>Welcome to TICTACTOE App</h1>
<p id="pname"><b>User Name :</b> <input type="text" id="uname" ></p>
</template>
<template name="main">
<p id="pno"><b>Layout Number :</b> <input type="text" id="no" ></p>
<div name="main"></div>
</template>
<template name="games">
{{#each game}}
<div>{{turn}} </div>
<div> {{wturn}}</div>
<div>{{bval}}</div>
{{/each}}
</template>
Meteor JS:
Counts = new Meteor.Collection('count');
TurnData= new Meteor.Collection('tdata');
BtnValues= new Meteor.Collection('btnvalues');
var x = "X";
var o = "O";
var Whoseturn = "";
var no;
var newButton;
var count = 0;
var IsWin = false;
var IsTurn = true;
var val = "";
var ButtonValue= "";
var btnval;
if (Meteor.isClient)
{
Template.main.helpers
({
btnValue: function()
{
return BtnValues.findOne();
}
});
Template.main.events
({
'click input' : function ()
{
// template data, if any, is available in 'this'
var name = document.getElementById('uname');
console.log(name.value);
var btnid = event.currentTarget.id;
ButtonValue = btnid;
btnval = document.getElementById(btnid);
console.log(btnid);
if(btnval.value == '' && btnid != "no" )
{
calculateTurn();
console.log(Whoseturn);
btnval.value = Whoseturn;
var myBtnData = BtnValues.findOne();
BtnValues.update( {_id: myBtnData._id},{ $set:{bval : btnval} });
}
}
});
Template.main.events
({
'keydown input#no' : function ()
{
// template data, if any, is available in 'this'
if (event.which == 13)
{
// 13 is the enter key event
console.log("You pressed enter key");
no = document.getElementById('no');
count = 0;
var myTurnData = Counts.findOne();
Counts.update( {_id: myTurnData._id},{ $set:{turn : count } });
if(no.value != '')
{
document.getElementById('pname').style.visibility = 'hidden';
document.getElementById('pno').style.visibility = 'hidden';
UI();
}
}
}
});
}
function UI()
{
console.log("*** UI() ***");
for(var i = 1 ; i <= no.value ; i++)
{
//var body=document.getElementsByTagName('body')[0];
var body = document.getElementsByName('main')[0];
for(var j = 1 ; j <= no.value ; j++)
{
newButton = document.createElement('input');
newButton.type = 'button';
newButton.id = 'btn'+i+j;
newButton.value = '';////Here value i need like as val ="{{btnValue}}
body.appendChild(newButton);
}
var newline = document.createElement('br');
body.appendChild(newline) ;
}
}
function calculateTurn()
{
var myTurnData = Counts.findOne();
count = myTurnData.turn;
console.log("count="+count);
count = count + 1;
console.log("updated count="+count);
Counts.update( {_id: myTurnData._id},{ $set:{turn : count } });
if(count <= 9)
{
var TData = TurnData.findOne();
IsTurn = true;
if(count % 2 == 0)
{
Whoseturn = o ;
TurnData.update( {_id: TData._id},{ $set:{wturn : Whoseturn } });
}
else
{
Whoseturn = x ;
TurnData.update( {_id: TData._id},{ $set:{wturn : Whoseturn } });
}
}
else
{
IsTurn = false;
console.log(" >= 9");
}
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
Counts.insert({turn : count});
TurnData.insert({wturn : Whoseturn});
BtnValues.insert({bval : val});
});
}