Why table id is not identified by getElementById() - javascript

Hi I am trying to get the id of my table and calculate the number of rows in my table.
I used this code
var table =document.getElementById("test");
var i = table.rows.length;
This doesnot work for me when I use window.onload It works. This my working function
window.onload = function() {
var table =document.getElementById("test");
var i = table.rows.length;
}
Now I need this i variable used in another function. How to make this i variable global. Any problem with my code?
Can some one help me code?
Edit 01
<table id="test">
<thead>
<tr>
<td style="width:80px;"><img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/employee.svg"></td>
<td style="width:35px;"><img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/start_time.svg"></td>
<td style="width:35px;"><img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/id.svg"></td>
<td style="width:145px;"><img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/Description.svg"></td>
<td style="width:45px;"><img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/Type.svg"></td>
<td style="width:45px;"> <img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/qty_prch.svg"></td>
<td style="width:45px;"> <img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/qty_used.svg"></td>
<td style="width:70px;"> <img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/Price.svg"></td>
<td style="width:70px;"> <img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/discount.svg"></td>
<td style="width:70px;"> <img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/Tax.svg"></td>
<td style="width:70px;"> <img src="http://localhost/elfanto/elfanto_billing/assets/img/ticket_page/Total_01.svg"></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="employee[]" value="" style="width:80px;" />
</td>
<td>
<input type="text" name="start_time[]" value="" style="width:35px;" />
</td>
<td>
<input type="text" name="pid[]" onChange="get_values(this.value)" value="" style="width:35px;" />
</td>
<td>
<input type="text" name="description[]" id="description1" value="" style="width:145px;" />
</td>
<td>
<input type="text" name="type[]" id="type1" style="width:45px;" />
</td>
<td>
<input type="text" name="qty_prch[]" id="qty_prch1" style="width:45px;" />
</td>
<td>
<input type="text" name="qty_used[]" id="qty_used1" style="width:45px;" />
</td>
<td>
<input type="text" name="price[]" id="price1" style="width:70px;" />
</td>
<td>
<input type="text" name="discount[]" id="discount1" style="width:70px;" />
</td>
<td>
<input type="text" name="tax[]" id="tax1" style="width:70px;" />
</td>
<td>
<input type="text" name="total[]" id="total1" style="width:70px;" />
</td>
</tr>
</tbody>
</table>
I need to use that variable i in this following javascript
function displayResult()
{
document.getElementById("test").insertRow(-1).innerHTML = '<td><input type="text" name="employee[]" value="" style="width:80px;"/></td><td><input type="text" name="start_time[]" value="" style="width:35px;"/></td><td><input type="text" name="pid[]" onChange="get_values(this.value)" style="width:35px;"/></td><td><input type="text" name="description[]" id="description[x]" value="" style="width:145px;"/></td><td><input type="text" id="type[x]" value="" style="width:45px;"/></td><td><input type="text" id="qty_used[x]" value="" style="width:45px;"/></td><td><input type="text" value="" style="width:45px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td>';
}
function get_values(val)
{
$.ajax({
url: baseurl+'admin/billing/getdetails',
type: 'post',
data : {val:val},
success: function (response) {
if(response!="")
{
var json=jQuery.parseJSON(response);
$('#description1').val(json.description);
$('#type1').val(json.type);
$('#qty_used1').val(json.cost);
}
},
error: function(response){
alert("error");
}
});
}

I would slightly change the setup... :)
Change all the numbered ids to unnumbered classes (also in the displayResult function)
id="description1" --> class="description"
id="type1" --> class="type"
...
function displayResult() {
var row = document.getElementById("test").insertRow(-1);
row.innerHTML = '<td><input type="text" name="employee[]" value="" style="width:80px;"/></td><td><input type="text" name="start_time[]" value="" style="width:35px;"/></td><td><input type="text" name="pid[]" style="width:35px;"/></td><td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td><td><input type="text" class="type" value="" style="width:45px;"/></td><td><input type="text" class="qty_used" value="" style="width:45px;"/></td><td><input type="text" value="" style="width:45px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td>';
}
Remove the "onChange" attribute from the newly inserted row and instead use a "global" change handler on the table using event delegation - (methods used in the change handler: .closest(), .index())
$(function() {
$('#test').on('change', 'input[name="pid[]"]', function() {
var indexOfTheChangedRow = $(this).closest("tr").index();
get_values(this.value, indexOfTheChangedRow);
});
});
Change the signature of get_values() to accept an additional parameter - the index of the changed row
function get_values(val, rowIndex) {
//...
}
Change the success handler of the ajax call to use the new layout
$.ajax({
url: baseurl + 'admin/billing/getdetails',
type: 'post',
data: {
val: val
},
success: function (indexOfTheChangedRow, response) {
if (response != "") {
var json = jQuery.parseJSON(response),
rowToUpdate = $("#test tr:nth-child(" + (indexOfTheChangedRow + 1) + ")");
// add the changed row as the context to restrict the search for the classes to this one row only
$('.description', rowToUpdate).val(json.description);
$('.type', rowToUpdate).val(json.type);
$('.qty_used', rowToUpdate).val(json.cost);
}
}.bind(window, rowIndex),
error: function (response) {
alert("error");
}
});
I'm using .bind() to "pin" the clicked row index to this ajax request (the success handler).
Now you can add as many rows as you want and you won't have to mess around with numbered ids :)

Is there anything stopping you from having this other function inside the onload closure as well?
window.onload = function() {
var table = document.getElementById("test"),
i = table.rows.length,
doStuff = function () {
// has access to i
},
doMoreStuff = function () {
// also has access to i
},
get_values = function () {
// also has access to i
};
document.getElementsByName("pid[]")[0].addEventListener("change", get_values);
}
Edit: You can remove your onChange attribute from the HTML and add an event handler in your JavaScript

You can declare the scope of variable as global.
var i = null;
window.onload = function() {
var table =document.getElementById("test");
i = table.rows.length;
}

Related

How to get select option value inside table with cell id by Javascript

Using JSP I add table row with cells containing select option when add button is clicked. I need to get the selected option values from table cells to Javascript. Below I have added by JSP and code..
Javascript
var maxID=0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.cells[0].id = "staffno_add"+ ++maxID;
x.cells[1].id = "name_add"+ maxID;
x.cells[2].id = "desig_add"+ maxID;
x.cells[3].id = "curloc_add"+ maxID;
x.cells[1].style.visibility="hidden";
x.cells[2].style.visibility="hidden";
x.cells[3].setAttribute('onchange', 'getData(this)');
x.cells[2].setAttribute('onchange', 'getData1(this)');
return x;
}
function addRow(i) {
//var button=[];
var k=i.rowIndex;
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[parseInt(k)];
r.parentNode.insertBefore(getTemplateRow(), r);
}
var y1=null;
var y2=null;
function getData(dropdown) {
y1=dropdown.id;
y2=y1[10];
alert("desig_add"+y1[10]);
alert('curloc_add'+y2);
var get_id = document.getElementById('curloc_add'+y2).getElementsByClassName("getit")[0].innerText;//need my selected option value here...
alert(get_id);
document.getElementById("desig_add"+y2).style.visibility = "visible";
}
function getData1(dropdown1) {
y1=dropdown1.id;
y2=x1[9];
alert("name_add"+y1[9]);
document.getElementById("name_add"+y2).style.visibility = "visible";
}
JSP
<form name="myform">
<tr id="templateRow" style="display:none">
<td>
<input type="text" readonly>
</td>
<td>
<input type="text" readonly>
</td>
<td>
<select class="getit">
<option value="">None</option>
<%for(x1=0;x1<arrList.size();x1++){%>
<option value="<%=arrList.get(x1)%>"><%=arrList.get(x1)%></option>
<%}%>
</select>
</td>
<td>
<select >
<option value="">None</option>
<%for(x1=0;x1<lenList.size();x1++){%>
<option value="<%=lenList.get(x1)%>"><%=lenList.get(x1)%></option>
<%}%>
</select>
</td>
<td><input type="text" readonly></td>
<td><input type="text" class="datepicker" style="background-color:
#fffa90"/></td>
<td>
<input type="text" readonly>
</td>
<td>
<input type="text" class="datepicker" style="background-color: #fffa90"/>
</td>
<td><input type="text" class="datepicker" style="background-color:
#fffa90"/></td>
</tr>
<input type="hidden" id="total" name="total">
</form>
<tr onclick="addRow(this,);">
<td>
<input type = "button" id="insert" value="Add" >
</td>
</tr>`
I am new to JSP and Javascript.. I want get selected option value in script.

Jquery AJAX submit next row only on ajax success with no loop - possible counter?

I'm working with loops and arrays. I want to submit table rows that are checked and wait for ajax success before next row is submitted. I tried a few things but no luck on getting only the rows I need. I could probably sort it out on the php side but I'd like it to be correct up front for changes later.
This article got me on the right track with a counter: stack: Ajax counter.
JS
$(document).ready(function () {
//submit boxes
$("#clickMe").click(sendrow);
// find and send boxes
num = 0;
function sendrow() {
var boxes = $("input[class='box' ]:checked").length; //get count of boxes
var values = $("input[class='box' ]:checked").map(function() {
x = this.name;
//alert( x);
}).get();
if (boxes >= 0 && num <= boxes) { //must be some boxes*/
//alert('boxes='+boxes+' num='+ num );
//$("tr:has(input[name='row1']:checked)").each(function() {
//rowData( num ); // gar rows
////////////////////////////////////////////////////////////////
var data = {};
//START ROW LOOP
//alert(' row num='+ num );
$("tr:has(input[name='row" + num + "']:checked)").each(function() {
var feild = this;
var values = "";
//START FEILD LOOP
$('input', this).each(function() {
data[this.name] = this.value;
// data = $(this).val();
//alert( $(this).val() );
});
//values = values.substring(1) ; //sneek peek data
// alert(data);
}); // get forms
//////////////////////////////////////////////////////////
//ajax works
$.ajax({
url: "postdata.php",
data: {
data: data
},
type: 'post',
// dataType: 'json',
// contentType: "application/x-www-form-urlencoded",
success: function(data) {
$('#success').append(data);
num++
//alert('num success ='+ num);
var next = num;
//alert('num increment ='+ num);
sendrow();
//alert(data);
}
});
} //end if num< boxes
else {
'num' + num + ' was met, no more rows';
}
}; // end function
}); //end document
HTML
<form action="" method="POST" name="postForm">
<table width="200" border="1" cellspacing="1" cellpadding="1">
<tr>
<td><span class="style1">
<input type="checkbox" class="select_all" />
.Select_all </span>
</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td>
<input name="ClickMe" type="button" id="clickMe" value="Submit" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="box" name="row0" />
</td>
<td>
<input value="0-image here" type="text" name="brd" class='item' />
</td>
<td>
<input value="0-title here" type="text" name="mfg" class='item' />
</td>
<td>
<input value="0-Category here" type="text" name="pcat" class='item' />
</td>
<td>
<input value="0-Store cat here" type="text" name="scat" i class='item' />
</td>
<td>
<input value="0-Condition here" type="text" name="cond" class='item' />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="box" name="row1" />
</td>
<td>
<input value="1-image here" type="text" name="brd" class='item' />
</td>
<td>
<input value="1-title here" type="text" name="mfg" class='item' />
</td>
<td>
<input value="1-Category here" type="text" name="pcat" class='item' />
</td>
<td>
<input value="1-Store cat here" type="text" name="scat" i class='item' />
</td>
<td>
<input value="1-Condition here" type="text" name="cond" class='item' />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="box" name="row2" />
</td>
<td>
<input value="2-1mage here" type="text" name="brd" class='item' />
</td>
<td>
<input value="2-title here" type="text" name="mfg" class='item' />
</td>
<td>
<input value="2-Category here" type="text" name="pcat" class='item' />
</td>
<td>
<input value="2-Store cat here" type="text" name="scat" class='item' />
</td>
<td>
<input value="2-Condition here" type="text" name="cond" class='item' />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="box" name="row3" />
</td>
<td>
<input value="3-1mage here" type="text" name="brd" class='item' />
</td>
<td>
<input value="3-title here" type="text" name="mfg" class='item' />
</td>
<td>
<input value="3-Category here" type="text" name="pcat" class='item' />
</td>
<td>
<input value="3-Store cat here" type="text" name="scat" class='item' />
</td>
<td>
<input value="3-Condition here" type="text" name="cond" class='item' />
</td>
</tr>
<td>
<input type="checkbox" class="box" name="row4" />
</td>
<td>
<input value="4-1mage here" type="text" name="brd" class='item' />
</td>
<td>
<input value="4-title here" type="text" name="mfg" class='item' />
</td>
<td>
<input value="4-Category here" type="text" name="pcat" class='item' />
</td>
<td>
<input value="4-Store cat here" type="text" name="scat" class='item' />
</td>
<td>
<input value="4-Condition here" type="text" name="cond" class='item' />
</td>
</tr>
</table>
here is an alternative using your code (untested) that uses an index as a counter.
// your code redone with a counter.
$(document).ready(function () {
//submit boxes
$("#clickMe").click(function () {
var boxes = $("input[type='checkbox' ]:checked");
sendrow(boxes, 0);
});
});
function sendrow(boxes, index) {
if (boxes.length == 0 || index >= boxes.length) {
// no rows checked or all rows processed.
return;
}
var currentRow = $(boxes[index]).closest("tr");
// load data
var data = {};
currentRow.find("input[type='text']").each(function () {
data[this.name] = this.value;
});
//ajax works
$.ajax({
url: "postdata.php",
data: {
data: data
},
type: 'post',
currentProcess: {rows:boxes, currentIndex:index},
success: function (data) {
$('#success').append(data);
var nextIndex = ++this.currentProcess.currentIndex;
var boxes = this.currentProcess.rows;
if (nextIndex < boxes.length) {
sendrow(boxes, nextIndex);
}
}
});
}
Ok, I got this working in my environment (Visual Studio) so I had to make some adjustment to the ajax but you should be able to convert it back to yours.
Basically, I get all to rows that are checked then add a class to mark which ones should be processed. When I send a row off, I change the class to processing and when it is done, I remove the class and call sendrow to process the next row.
Also, take note how I passed the row from the request to the success function to to removed the processing class.
I added a cell with the name of "status" so I could stuff proof that it hit the server in it.
$(document).ready(function () {
//submit boxes
$("#clickMe").click(function () {
var boxes = $("input[class='box' ]:checked");
// add class to see what has to be processed
boxes.closest("tr").addClass("waiting");
sendrow();
});
});
// process rows
function sendrow() {
var boxes = $(".waiting");
if (boxes.length == 0) {
// we are done
return;
}
var $row = $(boxes[0]);
$row.removeClass("waiting").addClass("processing");
var row = $row.html();
//ajax works
$.ajax({
url: "WebService1.asmx/GetADate",
data: JSON.stringify( {s:row}),
type: 'post',
contentType: "application/json; charset=utf-8",
dataType: "json",
rowprocessed:{ arow:$row},
success: function (data, status) {
var rp = this.rowprocessed.arow;
rp.find("[name='status']").val(data.d);
rp.removeClass('processing')
sendrow();
},
error: function (one, two) {
debugger;
}
});
}

Autocomplete isn't working

I have a problem with my autocomplete. When I use the first one input text will be used for autocomplete but when I use add function that I create to append the same element like the first one it doesn't work.
Here is my code:
<script>
$(document).ready(function(){
$("#addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="med" name="customFieldName[]" value="" placeholder="รายชื่อยา" /> <input type="text" class="code" name="customFieldValue[]" value="" placeholder="Input Value" /> Remove</td></tr>');
});
$("#customFields").on('click', '#remCF', function(){
$(this).parent().parent().remove();
} );
});
</script>
<script>//auto complete Code
$(function() {
$('.med').autocomplete({
source: "show.php",minLength: 2,
select:function( event, ui ) {
$('#name').val(ui.item.name);
}
});
});
</script>
<table class="form-table" id="customFields">
<div id="name" ></div>
<tr valign="top">
<th scope="row"><label for="customFieldName">Custom Field</label></th>
<td>
<input type="text" class="med" name="customFieldName[]" value="" placeholder="รายชื่อยา" />
<input type="text" class="code" name="customFieldValue[]" value="" placeholder="จำนวน" />
ADD
</td>
</tr>
</table>
http://jsfiddle.net/earc4436/3/
This is happening because you are using an ID in your Javascript, when you add the second field they are duplicated. You either need to use a class or change the ID for each field in your form.
<input type="text" class="code" id="customFieldValue" name="customFieldValue[]"
value="" placeholder="จำนวน" />

Allow the user to add form input fields: Why is append() only working once?

I'm trying to create an order form that has an "add new product" section within a table. Basically the user should be able to click on the "Add Row" link and a new input line will appear to allow the user to add another product to the order list. I'm able to have this work once, but after that the form won't add any new lines. In the console.log I can see that the event handler is only working on the original form element, not the new product input line. I have a shortened fiddle of what I'm working with here:
http://jsfiddle.net/scottm1164/eTBr6/5/
Here is my jQuery:
<script>
$(document).ready(function () {
(function () {
var start = $('table'),
newRow = $('<tr><td><input type="text" class="quantity" /></td><td><input type="text" class="prodNum" /></td><td><textarea cols="15" rows="1"></textarea></td><td><p class="addRow">Add a Row</p></td></tr>');
$('.addRow').on('click', function () {
$(start).append(newRow);
console.log(this);
});
})(); //end SIAF
}); //END document ready
</script>
Here is my Form:
<form enctype="multipart/form-data" method="post" action="#" id="orderForm">
<ul>
<li>Name:
<br>
<input type="text" id="name" />
</li>
<li>Email:
<br>
<input type="email" id="email" />
</li>
<li>Company:
<br>
<input type="text" id="company" />
</li>
<li>Phone:
<br>
<input type="tel" id="phone" />
</li>
<li>Delivery Address:
<br>
<input type="text" id="delAddress" />
</li>
<li>PO Number:
<br>
<input type="text" id="poNum" />
</li>
<li>If you have a document for your order, attach it here:
<br>
<input type="file" id="docs" />
</li>
<li>
<table id="prodTable" width="auto" border="0" cellpadding="4" cellspacing="4">
<tbody>
<tr>
<td>Quantity</td>
<td>Product Number</td>
<td>Product Description</td>
<td> </td>
</tr>
<tr>
<td>
<input type="text" class="quantity" name="quantity_" />
</td>
<td>
<input type="text" class="prodNum" name="prodNum_" />
</td>
<td>
<textarea cols="15" rows="1" name="prodDesc_"></textarea>
</td>
<td>
<p class="addRow">Add a Row</p>
</td>
</tr>
</tbody>
</table>
</li>
<li>Special Delivery Instructions:
<br>
<textarea cols="30" rows="10" id="instructions"></textarea>
</li>
</ul>
<input type="submit" id="submit" />
</form>
Can somebody explain to me what is going wrong with this code, I'm fairly new to jQuery/Javascript so I just don't understand why the code only works once, but not after subsequent clicks to the "add a row" link, and only on the original "add a row" links but not on the newly created link.
Try this
http://jsfiddle.net/eTBr6/8/
$('form').on('click', '.addRow', function () {
var start = $('table'),
newRow = $('<tr><td><input type="text" class="quantity" /></td>' +
'<td><input type="text" class="prodNum" /></td>' +
'<td><textarea cols="15" rows="1"></textarea></td>' +
'<td><p class="addRow">Add a Row</p></td></tr>');
$(start).append(newRow);
});
Put variables inside the click handler and also use event delegation by having the form as your context
Working DEMO
I guess this is what you need. For dynamically loaded elements a delegate $(document).on() is necessary than a normal function(), since normal event work only on page load.
here is the code
$(document).ready(function () {
var start = $('table'),
newRow = '<tr><td><input type="text" class="quantity" /></td><td><input type="text" class="prodNum" /></td><td><textarea cols="15" rows="1"></textarea></td><td><p class="addRow">Add a Row</p></td></tr>';
$(document).on('click', '.addRow', function () {
$(start).append(newRow);
});
}); //end document.ready
Hope this helps, Thank you
I did something similar to johnathan, just not as quickly.
Fiddle here: http://jsfiddle.net/xCNqP/1/
(function () {
var start = $('table'),
newRow = '<tr><td><input type="text" class="quantity" /></td><td><input type="text" class="prodNum" /></td><td><input type="text" maxlength="15"/></td><td><p class="addRow">Add a Row</p></td></tr>';
$(document).on('click', '.addRow', function () {
$(start).append($(newRow));
});
})(); //end SIAF
Primary change I used was set newRow to just a string, since declaring the element will allow you to only append it once. Re-declaring (which jonathan did by moving the declaration inside the handler) is required to re-append.
The correct usage of on so it will attach to new elements was also included.
http://jsfiddle.net/LK5sj/ stick your newrow inside the function and make the function recursive, and don't forget to clear and reassign the event handler or you'll get way more new rows than you want
var start = $('table');
function addRow(){
newRow = $('<tr><td><input type="text" class="quantity" /></td><td><input type="text" class="prodNum" /></td><td><textarea cols="15" rows="1"></textarea></td><td><p class="addRow">Add a Row</p></td></tr>');
$(start).append(newRow);
$('.addRow').off('click');
$('.addRow').on('click', function() {
addRow();
});
}
$('.addRow').on('click', function() {
addRow();
});

How to assign or append a unique ID in javascript with row integer from html

I have rows of forms with unique ID and its own Submit button. I used a for loop to get my rows.
for ( $i = 0 ; $i < count($areaList) ; $i++ )
sample html output below.
In my javascript, I need #loading and #result to reference the unique id="loading(int)" in my html so that the message displays next to that row.
At first, I had the div id="loading" and div id="result" w/o the integer in each row of my table but the message, 'Saved' would only display in my first row (first place it found that ID). I need my ids to be unique but how can I append them to my javascript?
I need some direction in js... I've attempted:
var rows = getElementsByClassName('reply_form');
for (var i=0, ii=rows.length; i<ii; i++)
rows[i]
var loading = $('#loading').attr('value');
$('#loading').prepend(""+loading+"");
-- not sure where to go....
<form id="1" class="reply_form" enctype="multipart/form-data" method="post" action="/reports/addcounts/" accept-charset="utf-8">
<div style="display:none;"><input type="hidden" name="_method" value="PUT" /><input type="hidden" name="data[_Token][key]" value="977ceaa782a964fe9a3f5a1cb3d7d422e8470af9" id="Token108437306" /></div>
<table>
<tbody>
<tr>
<td><input type="hidden" name="data[Report][id]" value="184463" /><b>Room</b><br />207 <input type="hidden" name="data[Report][area]" value="1" /></td>
<td><input name="data[Report][tables1]" type="text" class="inputbox" size="3" value="0" id="ReportTables1" /> </td>
<td><input name="data[Report][chairs1]" type="text" class="inputbox" size="3" value="0" id="ReportChairs1" /> </td>
<td><input name="data[Report][comments1]" type="text" size="20" value="" id="ReportComments1" /> </td>
<td>
<div class="submit"><input type="submit" value="Submit" /></div><br />
<div id="loading1" style="display: none;">Saved</div>
<div id="result1" style="display: none;"></div>
</td>
</tr>
</tbody>
</table>
</form>
<form id="2" class="reply_form" enctype="multipart/form-data" method="post" action="/reports/addcounts/" accept-charset="utf-8">
<div style="display:none;"><input type="hidden" name="_method" value="PUT" /><input type="hidden" name="data[_Token][key]" value="977ceaa782a964fe9a3f5a1cb3d7d422e8470af9" id="Token108437307" /></div>
<table>
<tbody>
<tr>
<td><input type="hidden" name="data[Report][id]" value="184464" /><b>Room</b><br />208 <input type="hidden" name="data[Report][area]" value="2" /></td>
<td><input name="data[Report][tables2]" type="text" class="inputbox" size="3" value="0" id="ReportTables2" /> </td>
<td><input name="data[Report][chairs2" type="text" class="inputbox" size="3" value="0" id="ReportChairs2" /> </td>
<td><input name="data[Report][comments2]" type="text" size="20" value="" id="ReportComments2" /> </td>
<td>
<div class="submit"><input type="submit" value="Submit" /></div><br />
<div id="loading2" style="display: none;">Saved</div>
<div id="result2" style="display: none;"></div>
</td>
</tr>
</tbody>
</table>
</form>
<form id="3" class="reply_form" enctype="multipart/form-data" method="post" action="/reports/addcounts/" accept-charset="utf-8">
<div style="display:none;"><input type="hidden" name="_method" value="PUT" /><input type="hidden" name="data[_Token][key]" value="977ceaa782a964fe9a3f5a1cb3d7d422e8470af9" id="Token108437308" /></div>
<table>
<tbody>
<tr>
<td><input type="hidden" name="data[Report][id]" value="184465" /><b>Room</b><br />209 <input type="hidden" name="data[Report][area]" value="3" /></td>
<td><input name="data[Report][tables3]" type="text" class="inputbox" size="3" value="0" id="ReportTables3" /> </td>
<td><input name="data[Report][chairs3" type="text" class="inputbox" size="3" value="0" id="ReportChairs3" /> </td>
<td><input name="data[Report][comments3]" type="text" size="20" value="" id="ReportComments3" /> </td>
<td>
<div class="submit"><input type="submit" value="Submit" /></div><br />
<div id="loading3" style="display: none;">Saved</div>
<div id="result3" style="display: none;"></div>
</td>
</tr>
</tbody>
</table>
</form>
--
<script type="text/javascript">
$(document).ready(function() {
$('.reply_form').submit(function() {
$.ajax({
type: 'POST',
url: '/reports/addcounts/',
data: $(this).serialize(),
cache: false,
beforeSend: function() {
$('#loading').show();
$('#result').hide();
},
success: function(data) {
if(data==1) {
$('#loading').hide();
$('#result').fadeIn('slow').html("ok");
$('#result').addClass('true');
$(this).slideUp(1000);
}
else {
$('#loading').hide();
$('#result').fadeIn('slow').html(data);
$('#result').addClass('errors');
}
}
});
return false;
});
})
</script>
Im not positive I understand the question, but it seems like you want to reference which of the forms were submitted, and manipulate just those #result and #loading divs? if so...
In the success function you retrieve the DOM element that initiated the event with jQuery, and then append that to each of the #loading and #result divs.
$(document).ready(function() {
$('.reply_form').submit(function(event) {
currentId = event.delegateTarget.id;
$.ajax({
type: 'POST',
url: 'form.php',
data: $(this).serialize(),
cache: false,
beforeSend: function() {
$('#loading'+currentId).show();
$('#result'+currentId).hide();
},
success: function(data) {
if(data==1) {
$('#loading'+currentId).hide();
$('#result'+currentId).fadeIn('slow').html("ok");
$('#result'+currentId).addClass('true');
$(this).slideUp(1000);
}
else {
$('#loading'+currentId).hide();
$('#result'+currentId).fadeIn('slow').html(data);
$('#result'+currentId).addClass('errors');
}
}
});
return false;
});
}):
That should work assuming that you have a relation between the id's of your forms and their result and loading divs.
Sloga, with this kind of thing you don't need separate forms and you should be working, for the most part, with classes not ids.
The trick is to attach a click handler to the Submit buttons, then in the handler work relative to the this (the clicked button) to find all the associated elements. This way, ids are not necessary.
HTML will be something like this :
<table id="reply_table">
<tbody>
<tr>
<td><b>Room</b><br />207</td>
<td>
<input type="hidden" name="_method" value="PUT" />
<input type="hidden" name="data[_Token][key]" value="977ceaa782a964fe9a3f5a1cb3d7d422e8470af9" id="Token108437306" />
<input type="hidden" name="data[Report][id]" value="184463" />
<input type="hidden" name="data[Report][area]" value="1" />
<input name="data[Report][tables1]" type="text" class="inputbox" size="3" value="0" id="ReportTables1" />
</td>
<td><input name="data[Report][chairs1]" type="text" class="inputbox" size="3" value="0" id="ReportChairs1" /></td>
<td><input name="data[Report][comments1]" type="text" size="20" value="" id="ReportComments1" /></td>
<td>
<div><button class="submit">Submit</button></div>
<div class="loading" style="display: none;">Saved</div>
<div class="result" style="display: none;"></div>
</td>
</tr>
</tbody>
</table>
And the javascript will be something like this :
$(function() {
$('#reply_table').on('click', "button.submit", function() {
var $tbody = $(this).closest("tbody");//find relevant tbody relative to the clicked button
var $loading = $tbody.find('.loading').show();//find the relevant "loading" div and show it.
var $result = $tbody.find('.result').hide();//find the relevant "result" div and hide it.
$.ajax({
type: 'POST',
url: '/reports/addcounts/',
data: $tbody.find("input").serialize(),
cache: false,
success: function(data) {
$loading.hide();
if(data==1) {
$result.html('ok').addClass('true').fadeIn('slow', function() {
$tbody.slideUp(1000);
});
}
else {
$result.html(data).addClass('errors').fadeIn('slow');
}
}
});
return false;
});
});
untested
I'm not sure if tbody elements will slideUp in all browsers. You may need to compromise and .hide() instead.

Categories