In this code javascript function is taking from[1] as argument in displayDatePicker('from[1]', false, 'dmy', '-'). When I clone this (second) row using jquery, all my input and select names get incremented but javascript function is still taking from[1] as argument. I want to ask how to change this from[1] to from[2] and so on
<tr>
<td width="19%" align="right" ><input type="text" id="roomcat" name="roomcat[1]" value="Deluxe" /></td>
<td width="1%" align="center" > </td>
<td width="15%" align="left" ><select class="f" name="roomtype[1]" id="roomtype">
<option value="">Please Select</option>
<option value="Single">Single</option>
<option value="Double">Double</option>
<option value="Triple">Triple</option>
<option value="Extra">Extra</option>
</select></td>
<td width="7%" align="left" ><input type="text" id="cfit" name="cfit[1]" /></td>
<td width="8%" align="left" ><input type="text" id="cgit" name="cgit[1]" /></td>
<td width="7%" align="center" ><input type="text" id="rfit" name="rfit[1]" /></td>
<td width="8%" align="center" ><input type="text" id="rgit" name="rgit[1]" /></td>
<td width="10%" align="center" >
<input class="f" style="width:70px" type="text" size="12" name="from[1]" id="from" value="<?php if($mode==1)
{
echo $from;
}
else
{
echo "From";
}?>" readonly="readonly" />
<i.m.g alt="Pick a date" src="js/date.g.i.f" border="0" width="17" height="16" />
</td>
<td width="10%" align="center" >
<input style="width:70px" class="f" type="text" size="12" name="to[1]" id="to" value="<?php if($mode==1)
{
echo $to;
}
else
{
echo "To";
}?>" readonly="readonly" />
<i.m.g alt="Pick a date" src="js/date.g.i.f" border="0" width="17" height="16" />
</td>
<td width="15%" align="left" > </td>
</tr>
Jquery Code is
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#table2 tbody>tr:last').clone(true);
row.find("input:text").each(function(){
this.name = this.name.replace(/\[(\d+)\]$/, function(str,p1){
return '[' + (parseInt(p1,10)+1) + ']';
});
})
row.find("select").each(function(){
this.name = this.name.replace(/\[(\d+)\]$/, function(str,p1){
return '[' + (parseInt(p1,10)+1) + ']';
});
})
row.insertAfter('#table2 tbody>tr:last');
return false;
});
});
Drop the id attributes in your <input>s, you don't need them and having duplicate ids just leaves you with invalid HTML and strange problems. If you're using them for styling, use classes instead. If you need them for something else, then you'll have to fix them when you copy so that you don't end up with duplicate ids.
Now we can clean up your cloning a little bit. When you're cloning your row, you don't need to parse the number in brackets, you can just ask the table how many rows it has and add one to get the new number:
var n = $('#table2 tbody>tr').length + 1;
then your replace calls simplify to this:
this.name.replace(/\[(\d+)\]$/, '[' + n + ']');
Also, you can use a multiple-selector to iterate through the <input>s and the <select>s at the same time:
row.find('input:text, select').each(...)
You're changing the same attribute in both cases so there's no need for two identical loops.
Using javascript:displayDatePicker(...) in your <a> isn't necessary. You can use jQuery to bind to clicks on those <a>s by adding a class to them:
<a class="datepicker">...</a>
and then binding a callback to them using click and a closest/find combination inside the callback will let you find the corresponding <input>:
$('a.datepicker').click(function() {
var $input = $(this).closest('td').find('input[type=text]');
displayDatePicker($input.attr('name'), false, 'dmy', '-'));
});
You're using clone so the event handlers on the cloned elements will be copied so you don't have to mess around with delegate or the dynamic versions of on.
Here's a demo with simplified HTML: http://jsfiddle.net/ambiguous/yEaw6/
From what I have understood from the first paragraph in your question..
Will this help?
var cells = $('td'); //Select row/cells here
$.each(cells, function(index, cell){
//index corresponds to index of current cell in set of matched cells
});
Related
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/
I have to add values of inputs in each row in corresponding textbox (under the heading total) using jquery. I used jQuery as below. class 'value' used for inputs to be typed and class 'values' used for the values displayed (1st two colums).
jQuery code is given below:
jQuery(document).ready(function($) {
var $total = $('#total_mark_<?php echo $student['student_code'];?>'),
$value = $('.value');
$values = $('.values');
$value.on('input', function(e) {
var total = 0;
var t=0;
$value.each(function(index, elem) {
if(!Number.isNaN(parseFloat(this.value, 10)))
total = total + parseFloat(this.value, 10);
});
$values.each(function(index, elem) {
t = t + parseFloat(this.value, 10);
});
total=total+t;
$total.val(Math.round(total));
});
});
When I use this code, I am getting an output only in the last textbox(total-textbox in last row only), where all the values (all input fields)summed up and total is showing in a textbox only.
How to add values of inputs in each row in corresponding textbox using jQuery to show output in corresponding "total"textbox?
I created one demo here, from this demo you can check how to traverse throw DOM element and how to get values from it.
$( document ).ready(function() {
// Traverse throw all rows
$('.student_marks tbody tr').each(function(){
// Get current row
var student = $(this);
var total_points = 0;
$(student).find('.marks').each(function(){
total_points+=parseInt($(this).val());
})
$(student).find('.total').html(total_points);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<table class="table student_marks" >
<thead>
<tr>
<th>Student Name</th>
<th>Math</th>
<th>History</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">John</td>
<td><input value="50" readonly class="marks"/></td>
<td><input value="50" readonly class="marks"/></td>
<td class="total"></td>
</tr>
<tr>
<td class="name">Mac</td>
<td><input value="60" readonly class="marks"/></td>
<td><input value="50" readonly class="marks"/></td>
<td class="total"></td>
</tr>
<tr>
<td class="name">Sena</td>
<td><input value="40" readonly class="marks"/></td>
<td><input value="70" readonly class="marks"/></td>
<td class="total"></td>
</tr>
<tr>
<td class="name">Devy</td>
<td><input value="80" readonly class="marks"/></td>
<td><input value="90" readonly class="marks"/></td>
<td class="total"></td>
</tr>
</tbody>
</table>
</div>
Hard one to explain in the title, but a bit of code says it all:
<tr class="">
<td>
<input value="9" name="set[122][order]"></input>
<input class="set-id" type="hidden" value="1" name="set[122][ex_id]"></input>
</td>
<td>
<input value="0.00" name="set[122][weight]"></input>
</td>
<td> … </td>
<td>
<img class="deleteRowButton" border="0" title="Toggle Delete Set" alt="Delete Set" src="mysite/images/icons/png/delete-3x.png"></img>
</td>
</tr>
I have a bit of jQuery code that is activated when the img (deleteRowButton) is clicked:
$('.deleteRowButton').click (function() {
$(this).parents("tr").toggleClass( "deleteSet" );
var id = $('.set-id', $(this).closest('td')).val(); // this bit not working
$('.editWoForm').append('<input type="hidden" name="deleteSet[]" value="' + id + '" />');
});
The deleteRowButton code basically just inserts a hidden input tag at the bottom of my form, so i have the ability to process these to remove entries from db.
BUT, what I need to do is grab the value from set[], so in this example 122. It can come from any of the inputs, as the whole tr is related to one entry. 122 is the db id, so that's what I need to grab.
So ideally, when the user clicks on the deleteRowButton, it generates and inserts:
<input type="hidden" name="deleteSet[]" value="122" />
Thanks in advance!
Solution
Thanks to #ArunPJohny for the assistance.
$('.deleteRowButton').click (function() {
var $tr = $(this).parents("tr").toggleClass( "deleteSet" );
var id = $tr.find('.set-id').attr('name').match(/\d+/)[0];
if($tr.hasClass( "deleteSet" )){
$('.editWoForm').append('<input type="hidden" name="deleteSet[]" value="' + id + '" />');
}
else{
$('input[name="deleteSet[]"][value="' + id + '"]').remove();
}
});
This will get the id, append a hidden input field with said id as the value, then if the button is pressed again (to toggle the delete state) the hidden input field is removed.
One way here is to fine the set-id element which is within the current tr element. what you are trying to do is to find an set-id which is within the td which contains the clicked deleteRowButton.
$('.deleteRowButton').click(function() {
//use closest instead of parents
var $tr = $(this).closest("tr").toggleClass("deleteSet");
//find the set-id within the current tr
var id = $tr.find('.set-id').attr('name').match(/\d+/)[0];
//$('.editWoForm').append('<input type="hidden" name="deleteSet[]" value="' + id + '" />');
$('#log').text(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr class="">
<td>
<input value="9" name="set[122][order]"/>
<input class="set-id" type="hidden" value="1" name="set[122][ex_id]"/>
</td>
<td>
<input value="0.00" name="set[122][weight]"/>
</td>
<td> … </td>
<td>
<img class="deleteRowButton" border="0" title="Toggle Delete Set" alt="Delete Set" src="mysite/images/icons/png/delete-3x.png"/>
</td>
</tr>
<tr class="">
<td>
<input value="9" name="set[123][order]"/>
<input class="set-id" type="hidden" value="2" name="set[123][ex_id]"/>
</td>
<td>
<input value="0.00" name="set[123][weight]"/>
</td>
<td> … </td>
<td>
<img class="deleteRowButton" border="0" title="Toggle Delete Set" alt="Delete Set" src="mysite/images/icons/png/delete-3x.png"/>
</td>
</tr>
</table>
<div id="log"></div>
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(); });
I have a form, which I'm using autofill using jquery in the first textfield. This textfield is called "producto1".
What I want is that when user write the information in "producto1" automatically load the content in "marca1", the content in this field will be loaded from my database.
This is my code:
<table width="100%" border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td width="545"><div align="center">
<input name="producto1" type="text" class="textfield4" id="producto1" value="" size="65" />
</div></td>
<td width="385"><div align="center">
<input name="marca1" type="text" class="textfield5" id="marca1" size="10" maxlength="5" onKeyPress="return handleEnter(event);">
</div></td>
<td width="385"><input name="cantidad1" type="text" class="textfield5" id="textfield2" size="10" maxlength="5" onKeyPress="return handleEnter(event);"></td>
</tr>
</table>
The information that will be displayed at the "marca1" field will be loaded from my database, but my problem is that I don't know how to populate automatically this second field using ajax.
// JS File
$(document).ready(function(){
$("#producto1").keyup(function(){
$.post('/path-to/marca.php',
{
text: $(this).val()
},
function(data) {
$('#marca1').val(data.returns);
},
'json');
});
});
// PHP File
$sql = $mysqli->query("SELECT marca_name
FROM marca
WHERE marca_name
LIKE '%" . $mysql->real_escape_string($_POST['text']) . "%'");
while($row = $sql->fetch_assoc($sql))
$returns[] = $row['marca_name'];
echo json_encode("returns" => implode(",", $returns));