This is my code
<table id="cont">
<tr>
<td><input type="text" name="no" id="no"/></td>
<td><input type="text" name="qty" id="qty"/></td>
</tr>
</table>
This is my jQuery Code
$(document).ready(function() {
var no="";
$('#no').keyup(function(){
no = $("#no").val();
for(var i=1; i<no; i++)
{
++j;
$('<tr class="field"><td></td><td><input name="qty[]" type="text" id="qty[0]" /></td></tr>').fadeIn('slow').appendTo('#cont');
}
});
if(i==1)
{
$('.field').remove();
}
});
I would like to create and remove row dynamically depending on an input field(no id) and it works fine upto 19 but if i input 20 then it create 20 with extra 1 row as well as i remove zero from 20 then it should be kept 2 rows but it display all rows(21).
How can i solve it , Please any help?
The main problem with your code is you only ever add rows. Here's a solution that provides a bit of timeout after keyup, then replaces all the rows. It's not entirely clear what your overall objective is with this UI.
Note that top row is wrapped in <thead> and <tbody> is used for data rows:
var row = '<tr class="field"><td>Row text</td><td><input name="qty[]" type="text" /></td></tr>';
var num_rows=0;
$('#no').keyup(function () {
num_rows= $(this).val();;
if (!isNaN(num_rows)) {/* make sure is a number, can add extra condition to limit number*/
setTimeout(createRows, 300);/* slight delay to give user time to type*/
} else {
alert('numbers only please')
}
});
function createRows(){
var rowHtml='';
for ( i=0;i<num_rows;i++){
rowHtml+=row;
}
$('#cont tbody').html( rowHtml)
}
Demo:http://jsfiddle.net/H4MHs/
EDIT: I suspect that this approach is completely off track from what you really want, but follows your methodology. Since objective was never spelled out that's all we can go on
You will probably want to convert the value from your field into an integer using parseInt before you use it in the loop.
I'm pretty sure jQuery's .val() will always return a string.
I have the feeling that this is what you need:
Html:
Number of field:<div id='nbElem'></div>
<table id="cont">
<tr>
<td><input type="text" name="no" id="no"/></td>
<td id='field'></td>
</tr>
</table>
Js:
$('#no').keyup(function(){
var $val = parseInt($(this).val(),10);
var $nbQtity = $('.qtity').length;
if($val <= $nbQtity){
for(var i = $val; i < $nbQtity; i++){
$('#q_'+i).remove();
}
}else{
for(var i = $nbQtity; i < $val; i++){
$('<input name="qty[]" class="qtity"'
+' type="text" id="q_'+i+'" />')
.fadeIn('slow')
.appendTo('#field');
}
}
$('#nbElem').text($val);
});
http://jsfiddle.net/pYtbs/
This is the simplest and the easiest way of adding rows
<table id="options-table">
<tbody>
<tr>
<td>Input-Box-One</td>
<td>Input-Box-Two</td>
<td></td>
</tr>
<tr>
<td><input type="text" name="input_box_one[]" /></td>
<td><input type="text" name="input_box_one[]" /></td>
<td><input class="del" type="button" value="Delete" /></td>
</tr>
<tr>
<td><input type="text" name="input_box_one[]" /></td>
<td><input type="text" name="input_box_one[]" /></td>
<td><input class="add" type="button" value="Add More" /></td>
</tr>
</tbody>
If we want more rows then we have to add new row to the table.
Put this code in script
$('.add').live('click',function(){
$(this).val('Delete');
$(this).attr('class','del');
var appendTxt = "<tr><td><input type="text" name="input_box_one[]" /></td><td><input type="text" name="input_box_two[]" /></td><td><input class="add" type="button" value="Add More" /></td></tr>";
$("tr:last").after(appendTxt); });
Delete a row from Table.
$('.del').live('click',function(){
$(this).parent().parent().remove(); });
Related
I have following Code which doesn't seems to work correctly when i added the script to add the values in the total that are shown in the total text box
<tbody id='table'>
<tr class="crow">
<td style='width:150px;'>1</td>
<td style='width:350px;'>
<select class="form-control FID" required name="FID[]">
<?php
$options="<option value='' Amount='0' >Select</option>";
foreach($data["challan"] as $row){
$options.="<option value='{$row["FID"]}' Amount='{$row["Amount"]}'>{$row["Feetype"]}</option>";
}
echo $options;
?>
</select>
</td>
<td>
<input type="text" name="Amount[]" class="form-control Amount" required>
</td>
<td>
<input type="button" value="Remove" class="btn btn-link btn-xs rmv" required>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td ><input type='button' class='btn btn-link add' value='+Add Row'></td>
<td colspan="2" class="text-right">Total</td>
<td><input type="text" name="grand_total" id="grand_total" class="form-control" required=""></td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("body").on("click",".add",function(){
var i=1;
$(".crow").each(function(){
i++;
});
var options="<?php echo $options; ?>";
var row='<tr class="crow"> <td>'+i+'</td> <td> <select class="form-control FID chosen" required name="FID[]">'+options+'</select></td><td> <input type="text" name="Amount[]" class="form-control Amount" required> </td></td><td> <input type="button" value="Remove" class="btn btn-link btn-xs rmv" required> </td></tr>';
$("#table").append(row);
});
$("body").on("click",".rmv",function(){
if(confirm('Are You Sure?')){
$(this).parents('tr').remove();
}
});
$("body").on("change",".FID",function(){
var p=$(this).find(":selected").attr("Amount");
$(this).closest("tr").find(".Amount").val(p);
});
$("body").on("keyup",".Amount",function(){
var Amount=Number($(this).val());
$(this).closest("tr").find(".total").val(Amount*1);
grand_total();
});
function grand_total(){
var tot=0;
$(".total").each(function(){
tot+=Number($(this).val());
});
$("#grand_total").val(tot);
}
});
</script>
I want to get little help that How can show the total amount in the total box, it will add all the values that are shown in the total column to show total in total text box at the end. i try to use the code but some how script doesn't seems to work correctly.
Thanks
I do not use jQuery ( always find it doesn't work as expected ) but with some simple vanilla Javascript this is fairly straightforward, no doubt some of what I wrote here you will be able to port into your jQuery code if you need to but the following example seems to work as you need it to. There are comments in the code to describe what is occurring but essentially a delegated event listener is bound to the document itself ( alternatively it could be the table ) and all button clicks and mouse events are delegated to the correct component thanks to event bubbling.
To help identify which buttons are clicked and the task they are to perform I simply added a dataset attribute to each, other than that the HTML is as per the original though obviously the select menu has been hardcoded with dummy data though the hardcoded row number was replaced with a css counter. Hope you find something of value in the following...
const d=document;
const total=d.querySelector('input[name="grand_total"]');
d.addEventListener('click',e=>{
/* Add new row */
if( e.target.classList.contains('btn-link') && e.target.dataset.action=='add' ){
let tbody=d.querySelector('tbody#table');
let tr=tbody.querySelector('tr:first-of-type');
/* clone the first table row and clear any values previously entered */
let clone=tr.cloneNode( true );
clone.querySelector('input[name="Amount[]"]').value='';
/* add the new row to the table. */
tbody.appendChild( clone );
}
/* Remove existing row - NOT first row though! */
if( e.target.classList.contains('btn-link') && e.target.dataset.action=='remove' ){
if( d.querySelectorAll('tbody#table tr').length > 1 ){
// We need to identify the value entered into 'Amount[]' so that we can remove
// it from the total.
let value=e.target.closest('tr').querySelector('input[name="Amount[]"]').value;
// find and remove the button's parent row
// using closest to move UP the DOM until it finds the TR node.
d.querySelector('tbody#table').removeChild( e.target.closest('tr') );
// subtract this value from the total
total.value-=parseFloat( value )
}
}
});
// tally up all numbers entered by iterating through all input elements
// with the name Amount[]
d.addEventListener('keyup',e=>{
let col=d.querySelectorAll('input[name="Amount[]"]');
// convert nodelist to an array and use regular array methods (map & reduce)
// to return the sum
total.value=[...col]
.map(n=>n.value > 0 ? n.value : 0)
.reduce((a,b)=>parseFloat(a) + parseFloat(b));
});
html{counter-reset:rows}
tr{counter-increment:rows}
tbody td{border:1px dotted grey;padding:0.25rem}
tbody tr td:first-of-type::before{content:counter(rows);display:table-cell}
tfoot td{background:grey;padding:0.5rem;color:white}
<table>
<tbody id='table'>
<tr class='crow'>
<td style='width:150px;'></td>
<td style='width:350px;'>
<select class='form-control FID' required name='FID[]'>
<option value=1>banana
<option value=2>giraffe
<option value=3>hercules
<option value=4>didgeridoo
<option value=5>womble
</select>
</td>
<td>
<input type='text' name='Amount[]' class='form-control Amount' required />
</td>
<td>
<input data-action='remove' type='button' value='Remove' class='btn btn-link btn-xs rmv' required />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td><input data-action='add' type='button' class='btn btn-link add' value='+Add Row' /></td>
<td colspan='2' class='text-right'>Total</td>
<td><input type='text' name='grand_total' class='form-control' required /></td>
</tr>
</tfoot>
</table>
Am having table data (retrieve data from mysql table and fetch in to table). table contains several records.I want to display checked checkbox value with input box value and checkbox when i clicking button in php. Checked checkbox value and checked input has deen displayed correctly using join function. but checked with checkbox is not showing correctly. In my code, when i clicking button all checked check values are displayed. my problem to display only checked checkbox with checkbax using join function.
My table:
<table border="0" cellpadding="10" cellspacing="1" width="500" class="tblListForm">
<tr class="listheader">
<td></td>
<td>Username</td>
<td>First Name</td>
<td>Last Name</td>
<td>Permissions</td>
<td>CRUD Actions</td>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
if($i%2==0)
$classname="evenRow";
else
$classname="oddRow";
?>
<tr class="<?php if(isset($classname)) echo $classname;?>">
<td><input type="checkbox" class="chk_id" name="chk_id" id="chk_id" value="<?php echo $row["userId"]; ?>" /></td>
<td><?php echo $row["userName"]; ?></td>
<td><input type="text" name="firstName" class="firstName" id="firstName" value="<?php echo $row["firstName"];?>" /></td>
<td><?php echo $row["lastName"]; ?></td>
<td><input type="checkbox" name="grant" class="grant" id="grant" value="Y" /></td>
<td><img alt='Edit' title='Edit' src='images/edit.png' width='15px' height='15px' hspace='10' /> <img alt='Delete' title='Delete' src='images/delete.png' width='15px' height='15px'hspace='10' /></td>
</tr>
<?php
$i++;
}
?>
</table>
<input type="button" id="save_value" name="save_value" value="Save" />
my jquery code what i have tried:
$('#save_value').click(function () {
alert("Checkbox running");
var chk_id = [];
var firstName = [];
var grant = [];
$.each($("input[ id='chk_id']:checked"), function () {
chk_id.push($(this).val());
firstName.push($(this).parent().parent().find("#firstName").val());
grant.push($(this).parent().parent().find($("#grant").is(':checked'));
});
alert(chk_id);
alert(firstName);
alert(grant);
});
Here,
am getting checked checkbox and checked input value. my problem to dispaly the checked checkbox with check value.
Thanks#
You made a few small mistakes:
You can't have multiple elements with the same ID, IDs must be unique. So I removed all duplicate IDs from your HTML (id="chk_id",id="firstName",id="grant") and in your JS, used the classes instead.
You missed a closing bracket in grant.push($(this).parent().parent().find($(".grant").is(':checked')));.
.find($(".grant").is(':checked')) isn't working as you expect, and also not necessary.
Use this instead: .find(".grant:checked").
And finally, the reason why your alert showed two values whether the checkboxes were checked or not: grant.push( ... ); always pushes something into the array, if the jQuery-selector matched nothing and would return false, that value would still be pushed into the array.
In fact, if you correct all three points above, and don't check the permission checkbox, the value in the array will be undefined. If you do check the box, it will be Y.
So, in order to make it work, you just have to put the grant.push( ... ); inside an if-clause, where you check for ".grant:checked":
if ($p.find(".grant:checked").length) {grant.push($p.find(".grant:checked").val());}
- $p stands for $(this).parent().parent(), I stored a reference in a var.
- .length checks if the length of the returned object is greater than 0. Without it, the if-clause would still always be true, because jQuery still returns an object (with value undefined).
See code snippet below for a demo:
$('#save_value').click(function() {
var chk_id=[], firstName=[], grant=[];
$.each($("input[class='chk_id']:checked"),function() {
var $row = $(this).parent().parent();
chk_id.push($(this).val());
firstName.push($row.find(".firstName").val());
if ($row.find(".grant:checked").length) {grant.push($row.find(".grant:checked").val());}
});
console.log(chk_id, firstName, grant);
});
table,input[type=button] {float:left;} /*ONLY SO console.log() DOESN'T COVER BUTTON*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="0" cellpadding="0" cellspacing="0" width="500" class="tblListForm">
<tr class="listheader"><td></td><td>Username</td><td>First Name</td><td>Last Name</td><td>Permissions</td></tr>
<tr class="evenRow">
<td><input type="checkbox" class="chk_id" name="chk_id" value="4" /></td>
<td>sardhar</td>
<td><input type="text" name="firstName" class="firstName" value="sardhar" /></td>
<td>mohamed</td>
<td><input type="checkbox" name="grant" class="grant" value="Y" /></td>
</tr>
<tr class="oddRow">
<td><input type="checkbox" class="chk_id" name="chk_id" value="3" /></td>
<td>fg</td>
<td><input type="text" name="firstName" class="firstName" value="vb" /></td>
<td>vb</td>
<td><input type="checkbox" name="grant" class="grant" value="Y" /></td>
</tr>
</table>
<input type="button" id="save_value" name="save_value" value="Save" />
jsfiddle: https://jsfiddle.net/3utno9at/
In my project it has an interface(designation.php) which has a form. When a user enters a 'designation code'(which is a primary key) and click the 'update' button, the
remaining fields should be filled accordingly. I understand that Ajax will be needed for this.
but the problem is, i'm done with retrieving the result only as a single row from the database by using following query. but, this is not my objective.
while($row = mysqli_fetch_assoc($run1)) {
echo "<tr id='tr'>";
foreach($row AS $cell) echo "<td>$cell</td>";
echo "</tr>\n";
}
Following is the 'designation.php'..
<form action="crud.php" method="post">
<table>
<th >DESIGNATION</th>
<tr>
<td >Designation Code</td>
<td ><input type="text" name="des_code" /></td>
</tr>
<tr>
<td >Designation</td>
<td><input type="text" name="desig" /></td>
</tr>
<tr>
<td >Salary Code</td>
<td><input type="text" name="s_code" /></td>
</tr>
<tr>
<td >Salary Scale</td>
<td><input type="text" name="s_scale" /></td>
</tr>
<tr>
<td >Salary point </td>
<td><input type="text" name="s_point" /></td>
</tr>
<tr>
<td>Date</td>
<td > <input type="date" name="date" /></td>
</tr>
<tr>
<td><input type="submit" name="update" value="Update" /></td>
</tr>
</table>
I attempted many solutions but have not gotten the intended result. Any help is appreciated.
$(document).ready(function(){
("#form1").submit(function({
var id=<?php echo $_POST['des_code']; ?>;
$.ajax({
url: 'update.php',
type:'POST',
data: {id:id},
success : function (data)
{
var a=data.split('[BRK]');
$("#s_scale").val(a[0]);
// like wise store all your fields..
}
})
})
upadte.php will contain
$id=$_POST['id']; //designation id from jqyery
$q=mysqli_query("your goes here..");
while($row = mysqli_fetch_array($q))
{
$cell=$row[0];
$cell.="[BRK]".$row[1];
$cell.="[BRK]".$row[2];
}
echo $cell;
give id to your text field so from jquery you can add value directly.. and give form id also so you can fire onsubmit event...
i didn't try this code but hope it will work fine...
To transfer more than one value use json!
Jquery Code::
$(function(){
id="XXXX";
$("form").on("submit",function(e){
e.preventDefault();
$.getJson("update.php",{"id":id},function(response){
$("#value1").val(response.value1);
$("#value2").val(response.value2);
// like wise store all your fields..
})
})
})
Update.php::
$q=mysqli_query("your query");
$row = mysqli_fetch_array($q);
echo json_encode($row);
$row will be an array containing value1, value2 and so on!!
I wanted to put a checkbox autosum on my website so that anyone who check a box and submit, the values (Points) of those check box are automatically added to my total sum (on home page actually)
I have found this code so far for java script.
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td> <input name="sum_m_1" value="25" type="checkbox" id="sum_m_1" onclick="UpdateCost()"> </td>
<td> ResponseOption_1 </td>
</tr>
<tr>
<td> <input name="sum_m_2" value="15" type="checkbox" id="sum_m_2" onclick="UpdateCost()"> </td>
<td> ResponseOption_2 </td>
</tr>
</table>
<input type="text" id="totalcost" value="">
With JAVASCRIPT:
<script type="text/javascript">
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i=1; i<3; i++) {
gn = 'sum_m_'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
document.getElementById('totalcost' ).value = sum.toFixed(2);
}
window.onload=UpdateCost
</script>
This will add up the values but i wanted to add by checking check boxes --> Submit --> collect the data --> add to my main total.
Any helps would be much appreciated.
Simple changes:
Add a button "calculate cost".
Removed the onclick events from the checkboxes and added the onclick event to the button instead.
Note that "window.onload=UpdateCost" is still there because what you want ideally is for the total cost to be displayed properly as 0.00 when the page loads.
HTML
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td> <input name="sum_m_1" value="25" type="checkbox" id="sum_m_1"> </td>
<td> ResponseOption_1 </td>
</tr>
<tr>
<td> <input name="sum_m_2" value="15" type="checkbox" id="sum_m_2"> </td>
<td> ResponseOption_2 </td>
</tr>
</table>
<input type="text" id="totalcost" value="">
<input type="button" value="update cost" onclick="UpdateCost();">
JavaScript
<script type="text/javascript">
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i=1; i<3; i++) {
gn = 'sum_m_'+i;
elem = document.getElementById(gn);
if (elem. checked == true) { sum += Number(elem. value); }
}
document.getElementById('totalcost' ).value = sum.toFixed(2);
}
window.onload=UpdateCost
</script>
Hope that's the kind of thing you wanted, let me me know what you think.
I have a table with a column on prices and the next column is a check box to mark whether that item was paid. I was wondering how I could populate the text box with the amount when the check box is clicked.
Code:
<table>
<tr>
<td>Procedure</td>
<td>Amount</td>
<td align="center"><input type="checkbox"></td>
<input type="text" size="20" value="" class="currency">
</tr>
</table>
HTML
<table>
<tr>
<td>Procedure</td>
<td>Amount</td>
<td align="center">
<input type="checkbox">
</td>
<td>
<input type="text" size="20" value="" class="currency">
</td>
</tr>
</table>
JavaScript/jQuery:
$(function() {
$('table input[type="checkbox"]').change(function() {
var input = $(this).closest('td').next('td').find('input');
if ($(this).is(':checked')) {
var amount = $(this).closest('td').prev('td').text();
input.val(amount);
} else {
input.val('');
}
});
});
See a working example at: http://jsfiddle.net/KTQgv/2/.
Some code you can expand on:
<input type="checkbox" rel="textbox1" name="banana"/>
<textarea id="textbox1" ></textarea>
JS/jQuery:
$('input:checkbox').click(function(){
var tb = "#"+$(this).attr('rel');
if($(this).is(":checked"))
$(tb).append(this.name + "\n");
});
Fiddle: http://jsfiddle.net/maniator/hxkX3/
Semantically, a checkbox isn't really the best control to choose to initiate an action. I would have an edit or pay (something actionable) button/icon which initiates the action of allowing the user to enter a value.
However for the purposes of your example, the click event of the checkbox is enough to be able to change the contents of your table cell from the displayed text (if any) to a textbox.
Given
<td id="row_1">Unpaid</td>
Using
$('#row_1').html('<input type="text" name="txtRow1" />');
is simplistic, but enough to enable the user to type in a value which could then be posted to the server during a save action.