I am developing some ticket selling program, where I made an auto calculating ticket price. I put the total price into a <span> tag. I'm trying to put it on <input> tag so it will be easier to pass the value into controller, but it doesn't work. I've already searching for the solution but it never comes to end. This is what my blade looks like:
<table class="text-center table-bordered" style="width:100%;">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr class="quantz">
<td class="product-quantity">
<input type="hidden" name="price[]" class="price" id="price" size="5px" readonly value="25000">
<input type="number" onchange="update();return false;" name="qty" value="1" min="1" id="quant" class="fl qty-text" >
</td>
<td class="product-total">
<span id="demo">IDR 25.000,-</span>
</td>
</tr>
<tr>
<td><h3><small>Your Cart Total - </small></h3></td>
<td><h3><input type="hidden" name="totalz" value=""><span id="sub_total">IDR 25.000,-</span></h3></td>
</tr>
</tbody>
</table>
and this is what i wrote in my jquery to get the value:
<script>
function update() {
var total = 0;
var fees = 0;
var total_fees = 0;
var tax_fix = 0;
var with_fee = 0;
var discount_amt = 0;
var no_fee= 0;
var tax= 0;
$("#form-ui tr.quantz").each(function(i,o){
if($(o).find("#quant").val()>=0){
total += $(o).find("#quant").val() * $(o).find(".price").val();
$(o).find("#demo").html(rupiah($(o).find("#quant").val() * $(o).find(".price").val()));
}
});
console.log()
fees = (total*1);
total_fees = total+fees ;
no_fee = total;
with_fee = total + total_fees;
//sub total
$("#st").val(total);
$("#sub_total").html(rupiah(total));
//convinence_fee
if(total == 0){
fees = 0;
total_fees = 0;
}
$("#fee").val(fees);
$("#conv").html(rupiah(fees));
//total_paid
$("#total_price").val(total_fees);
$("#total_paid").html(rupiah(total_fees));
$("#hide_price").val(total_fees);
}
$("#form_payment tr.quantity").change(update);
function rupiah(value){
value += '';
x = value.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return 'IDR ' + x1 + x2 + ",-";
};
</script>
is there any solution regarding this problem? should I put something in my script or my controller?
Possible with JQuery, jQuery supports chaining objects return.
In HTML :
<span id="demo">IDR 25.000,-</span>
<input id="totalz" type="hidden" name="totalz" value="">
In JS :
var data = $('#demo').html();
$('#total').val(data);
Make sure that, you have single id demo, total, if you have multiple id with same attribute, then it will conflict with JavaScript
Related
I am fairly new to javascript so any assistance is appreciated. I am trying to collect 2 related inputs from a user and display the array object as a table. When the inputs are submitted however, the array is displaying as undefined. I am not sure where I am going wrong. Any suggestions?
I have tried different methods of collecting the inputs off the form but none seem to work.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Example:</title>
<script type="text/javascript">
var flights = [];
function add(ele) {
flights.push(number, miles);
render();
document.getElementById("number").value = "";
document.getElementById("miles").value = "";
}
function render() {
document.getElementById("mydiv").innerHTML = "";
thelisthtml = "";
for(i = 0; i< flights.length; i++)
thelisthtml += "<div class='card' id="+ i +"><div class='card-body'>";
thelisthtml += "Flight " + (i+1) + " : " + flights[i] + " " + "<button type='submit' onclick = 'clearToDo(this)' id="+ i +">Remove From List</button>";
document.getElementById("mydiv").innerHTML = thelisthtml;
}
function calculateStatus(){
var totalMiles = Number(document.getElementById("totalMiles").value);
if (miles < 9999){
tr = document.getElementById("table").rows[1];
tr.style.backgroundColor = "yellow";
}
if (miles >= 10000 && miles <= 24999){
tr = document.getElementById("table").rows[2];
tr.style.backgroundColor = "yellow";
}
if (miles >= 25000){
tr = document.getElementById("table").rows[3];
tr.style.backgroundColor = "yellow";
}
}
function refreshPage() {
window.location.reload();
}
</script>
</head>
<body>
<br>
<table id="table" border ="1">
<tr>
<th>Medallion Status</th>
<th>Level</th>
</tr>
<tr>
<td>Bronze</td>
<td> < 10000 miles</td>
</tr>
<tr>
<td>Silver</td>
<td> < 25000 miles</td>
</tr>
<tr>
<td>Gold</td>
<td> > 25000</td>
</tr>
</table>
<h1><strong>Traveler Information </strong></h1><br> <br>
Flight Number: <input type="text" id="number" name="number" value="" />
<br> <br>
Miles Flown: <input type="text" id="miles" name="miles" value=""/> <br>
<br>
<input type="submit" value="Add Flight" id="go" onclick="add(this)"/>
<p>----------------------------</p>
<table>
<thead>
<tr>
<th>Flight</th>
<th>Miles</th>
</tr>
<thead>
<tbody>
<tr class="col-md-6" id="mydiv"></tr>
</tbody>
</table>
<input type="reset" id="reset" name="Reset" value="Reset"
onclick="refreshPage()" /> <br> <br> <br>
<br> <br>
</body>
</html>
the expected result is the array will display in a table as the user enters information. the actual result is the array is undefined.
There are several issues but the answer to your question about how to fix the flights array containing undefined is to change
function add(ele) {
flights.push(number, miles);
render();
document.getElementById("number").value = "";
document.getElementById("miles").value = "";
}
to
function add() {
const numberElem = document.getElementById("number");
const milesElem = document.getElementById("miles");
flights.push(numberElem.value, milesElem.value);
render();
numberElem.value = "";
milesElem.value = "";
}
In your original add function you are pushing number and miles onto the flights array but number and miles are undefined variables so you are pushing undefined and undefined onto the flights array.
To also fix the other issues I'd suggest replacing your add and render functions with the follow
function add() {
const numberElem = document.getElementById("number");
const milesElem = document.getElementById("miles");
flights.push({
number: numberElem.value,
miles: milesElem.value});
render();
numberElem.value = "";
milesElem.value = "";
}
function render() {
const tbody = document.querySelector('#outputTable tbody');
tbody.innerHTML = flights.map((flight, i) => {
return ''
+ '<tr>'
+ '<td>'
+ flight.number
+ '</td>'
+ '<td>'
+ flight.miles
+ '</td>'
+ '<td>'
+ `<button type='button' onclick="clearToDo(${i})">`
+ 'Remove From List'
+ '</button>'
+ '</td>'
+ '</tr>';
}).join('');
}
and changing your second <table> to <table id="outputTable">.
I have a button that the user clicks on to add a new row to the bottom of an input table. I would like this to also increment the id. So the next row would have desc2, hours2, rate2 and amount2 as the id. Is there a way to do this in the JavaScript function.
Also - just want to check my logic on this. After the user completes the filled out form, I will be writing all the data to a mysql database on two different tables. Is this the best way to go about this? I want the user to be able to add as many lines in the desc_table as they need. If this is the correct way to be going about this, what is the best way to determine how many lines they have added so I can insert into the db table using a while loop?
JS file:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}
HTML:
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Thank you!
Check this code.After appending the row it counts the number of rows and and then assigns via if condition and incremental procedure the id's:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
for(var i=1;i<rows.length;i++){
if(rows[i].children["0"].children["0"].id.match((/desc/g))){
rows[i].children["0"].children["0"].id='desc'+i;
}
if(rows[i].children["1"].children["0"].id.match((/hours/g))){
rows[i].children["1"].children["0"].id='hours'+i;
}
if(rows[i].children["2"].children["0"].id.match((/rate/g))){
rows[i].children["2"].children["0"].id='rate'+i;
}
if(rows[i].children["3"].children["0"].id.match((/amount/g))){
rows[i].children["3"].children["0"].id='amount'+i;
}
}
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Please change variable names for more descriptive. :)
Example solution...
https://jsfiddle.net/Platonow/07ckv5u7/1/
function new_line() {
var table = document.getElementById("desc_table");
var rows = table.getElementsByTagName("tr");
var row = rows[rows.length - 1];
var newRow = rows[rows.length - 1].cloneNode(true);
var inputs = newRow.getElementsByTagName("input");
for(let i=0; i<inputs.length; i++) {
inputs[i].id = inputs[i].name + rows.length;
}
var textarea = newRow.getElementsByTagName("textarea")[0];
textarea.id = textarea.name + rows.length;
table.appendChild(newRow);
}
Note that I removed/edited below fragment.
x.style.display = "";
r.parentNode.insertBefore(x, r);
You could do this a lot easier with jquery or another dom manipulation language, but with vanilla JS here's an example of simply looping through the new row's inputs & textarea and incrementing a counter to append.
var count = 1;
function new_line() {
count++;
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
// update input ids
var newInputs = Array.from(x.getElementsByTagName('input'))
.concat(Array.from(x.getElementsByTagName('textarea')));
newInputs.forEach(function(input) {
var id = input.getAttribute('id').replace(/[0-9].*/, '');
input.setAttribute('id', id + count);
});
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
When I click table row, that row value will display the below text box, then I click + button to copy the first row values and insert new row and place value correctly.
When I click edit button # that value again place to first row. How to find that row index. How to get the particular ID?
<script>
function insRow()
{
var x=document.getElementById('scrolltable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var code=document.getElementById('code').value;
var product=document.getElementById('product_name').value;
var qty=document.getElementById('quantity').value;
var rate=document.getElementById('amount').value;
var amount=document.getElementById('total').value;
var inp1 = new_row.cells[0].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = code;
var inp2 = new_row.cells[1].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = product;
var inp3 = new_row.cells[2].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = qty;
var inp4 = new_row.cells[3].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = rate;
var inp5 = new_row.cells[4].getElementsByTagName('input')[0];
inp5.id += len;
inp5.value = amount;
var button = new_row.cells[5].getElementsByTagName('input')[0];
button.value = "#";
button.onclick = function(it) {editRow(it)};
//cell4.appendChild(inp4);
x.appendChild( new_row );
document.getElementById('code').value='';
document.getElementById('product_name').value='';
document.getElementById('quantity').value='';
document.getElementById('amount').value='';
document.getElementById('total').value='';
document.getElementById('code').focus();
}
function deleteRow(row)
{
r=row.parentNode.parentNode;
r.parentNode.removeChild(r);
}
function editRow(evt) {
var x=document.getElementById('scrolltable');
//var l1 = evt.target.parentNode.parentNode;
//alert(l1);
var errorList = "";
var l=x.rows.length;
//var l=x.rowsIndex;
var y=l-1;
alert(l);
//alert("code"+y);
var code=document.getElementById('code'+y).value;
var product=document.getElementById('product_name'+y).value;
var qty=document.getElementById('quantity'+y).value;
var rate=document.getElementById('amount'+y).value;
var amount=document.getElementById('total'+y).value;
document.getElementById('code').value=code;
document.getElementById('product_name').value=product;
document.getElementById('quantity').value=qty;
document.getElementById('amount').value=rate;
document.getElementById('total').value=amount;
var i = evt.target.parentNode.parentNode.rowIndex;
document.getElementById('scrolltable').deleteRow(i);
}
</script>
My HTML code is:
<table class="table table-striped table-bordered dTableR" id="scrolltable">
<thead>
<tr>
<th width="10%">Code</th>
<th width="40%">Product</th>
<th width="10%">Total Qty</th>
<th width="10%">Rate</th>
<th width="12%">Amount</th>
<th width="10%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="code" class="span10" id="code" /></td>
<td><input type="text" name="product_name" class="span12" id="product_name" /></td>
<td><input type="text" name="quantity" class="span10" onBlur="calculate(this.value)" id="quantity" maxlength="8"/></td>
<td><input type="text" name="amount_name" class="span10" id="amount" /></td>
<td><input type="text" name="total_name" class="span10" id="total" maxlength="8" /></td>
<td><input type="button" id="addmorePOIbutton" style="width:25px;" value="+" onClick="insRow()"/>
<input type="button" id="delPOIbutton" style="width:25px;" value="-" onClick="deleteRow(this)"/></td>
</tr>
</tbody>
You can use jQuery for edit function :
First change
button.onclick = function(it) {editRow(it)};
to
button.onclick = function() {editRow(this)};
and change below function
function editRow(evt)
{
var $tr = $(evt).parents('tr'); // get parent tr
// put all values in top row
$('#code').val($tr.find('input[id^=code]').val());
$('#product_name').val($tr.find('input[id^=product_name]').val());
$('#quantity').val($tr.find('input[id^=quantity]').val());
$('#amount').val($tr.find('input[id^=amount]').val());
$('#total').val($tr.find('input[id^=total]').val());
// remove clicked tr
$tr.remove();
}
Working jsfiddle
Note : Please add jQuery js file to your html page.
since you are using jquery(as you have tagged this question with jquery), you can use index() function form jquery (http://api.jquery.com/index/).
Here is an updated (http://jsfiddle.net/6yXMF/) jsfiddle.
Which alerts index of the tr from which the input button is clicked.
Currently there are some issues in insertion and deletion or rows in your code. After resolving the issues you just can use the index function as demoed in
insRow() function.
Let me know if you have any queries.
This is for generating the table.
function makeTable()
{
var row_num = 20;
var cell_num = 4;
var tab = document.createElement('table');
tab.setAttribute('id','newtable');
var tbo = document.createElement('tbody');
tbo.setAttribute('id','tabody');
var cont;
for(var c = 0 ; c < row_num ; c++)
{
var row = document.createElement('tr');
for(var k = 0 ; k < cell_num ; k++)
{
var cell = document.createElement('td');
if (k > 0)
{
cont = document.createElement("input");
cont.setAttribute('type','text');
}
else
{
cont = document.createTextNode("0" + (c+1));
}
cell.appendChild(cont);
row.appendChild(cell);
}
tbo.appendChild(row);
}
tab.appendChild(tbo);
document.body.appendChild(tab);
tab.setAttribute("align", "top-left");
}
This function is used to show the data in alert box but I want to retrieve document.getElementById('hide').value............
function GetCellValues()
{
var rows = document.getElementsByTagName('tr');
var str = '';
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ', ';
}
}
document.getElementById('hide').value = str;
I want to retrieve only this hidden control (i.e-"hide") in php.
alert(document.getElementById('hide').value);
}
window.onload = function()
{
makeTable();
};
</script>
</head>
<body>
<h1><u>PROJECT</u> :</h1>
<input type="button" value="Alert" onclick = "GetCellValues()">
I want to retrieve this id in php
<input type="hidden" id="hide" /> <br />
<div id="mytable">
<table id = "project" border = "1" width ="60%" class = "newtable" cellpadding="10" cellspacing="0">
<tr>
<th align="center" width ="200px">Sl.No.</th>
<th align="center" width ="200px">Project Name</th>
<th align="center" width ="200px">ChangeDate</th>
<th align="center" width ="200px">Changed By</th>
</tr>
</table>
</div>
</body>
Note: I want to retrieve the hidden control through id in php ##
I want the total php code to retrieve this hidden control data(i.e-input type="hidden" id="hide") because I'm a beginner
You have to add a name to your input so for example:
<input type="hidden" id="hide" name="foo" />
To retrieve the value in php after POST form submission you can do this:
<?php $var1 = $_POST["foo"]; ?>
Can you please replace this line
<input type="hidden" id="hide" />
to
<input type="hidden" id="hide" name="hide" />
and use $_POST["hide"] in you php script.
Input field must have some name to access it
<input type="hidden" id="hide" name="hide" />
do normal fetch
$name = $_POST['hide'];
add name property to input type and value you want to get into you php
<input type="hidden" id="hide" name="flag" value="1" />
and to retrieve the value in php after POST form
$var1 = $_POST["flag"];
I need to display the percentage each input value contains out of the full dataset.
So if the user inputs 3, 2 and 1. The "percent" inputfield should show "50, 30 and 20"
The thing is, i dont know how many inputs the form will get. It could be from 1 to any number.
The source html code is created by a partial view i created. The output is:
<table>
<tr>
<th>Name</th><th>Distributiob key</th><th>Percent</th>
</tr>
<tr>
<td>
House 1
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_0__DistributionKey" name="LightPhysicalEntities[0].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_0__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 2
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_1__DistributionKey" name="LightPhysicalEntities[1].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_1__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 3
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_2__DistributionKey" name="LightPhysicalEntities[2].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_2__Percent" readonly=readonly />
</td>
</tr>
First field in the table is the title or name. Second is where the user punches in distribution number. Third is the readonly field with the calculated percentage.
The calculation should be done in javascript, but i cant quite crack the nut on how to get started, getting the inputs and setting the outputs.
A function like this should help (this will round down the percentages- replace the Math.floor if you want to handle differently):
function calcPcts() {
var distributions = $("[id$=DistributionKey]");
// Get the base first
var base = 0;
distributions.each(function () {
base += window.parseInt($(this).val(), 10);
});
// Now calculate the percentages of the individual ones
distributions.each(function () {
var input = $(this),
val = window.parseInt($(this).val(), 10),
pct = (val === 0) ? val : Math.floor((val / base) * 100);
$("#" + input.attr("id").replace("DistributionKey", "Percent")).val(pct);
});
}
If you add a class to the input fields you can use jQuery to get the number of items with that class. Then you can get the values and perform your calculations.
Here is an example:
var inputCount = $(".inputfield").length;
$("input[type='text']").change(function() {
var total = GetTotal();
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
if (total != 0) {
var percent = inputValue / total;
$('#LightPhysicalEntities_' + i + '__Percent').val(percent);
}
}
});
function GetTotal() {
var total = 0;
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
total += parseInt(inputValue);
}
return total;
}
Here is an example of the script working: http://jsfiddle.net/ZWuQr/