how to get row index of selected row - javascript

this is my view
im trying to access row index using this method
$("input.deliverQty").focusout(function (e) {
var table = document.getElementById('invoiceDetailTbl');
var DeliverQty = $(this).val();
var rowId = $(this).closest('tr').attr('rowIndex');
//var OrderQty = $(this).closest('tr').find('input.payingAmt').val();
var OrderQty = table.rows[parseInt(rowId) + 1].cells[2].childNodes[0].data;
but result was undefined
i'm append my table like this
for (var i = 0; i < data[0].itemDetails.length; i++) {
itmCode = data[0].itemDetails[i].item_Code;
itmName = data[0].itemDetails[i].item_Name;
OQty = parseInt(data[0].itemDetails[i].item_Qty);
//netAmt = parseFloat(data[i].Net_Amt).toFixed(2);
//paidAmt = parseFloat(data[i].Paid_Amt).toFixed(2);
//balance = (parseFloat(netAmt) - parseFloat(paidAmt)).toFixed(2); //id = "damt['+i+']"
$("#invoiceDetailTbl tbody").append("<tr id=" + i + ">" + "<td>" + itmCode + "</td>" + "<td>" + itmName + "</td>" + "<td>" + OQty + "</td>" + "<td>" + '<input type="text" class="deliverQty form-control input-sm" style="width: 100px;" placeholder="Deliver Qty" id="dqty">' + "</td>" + "<td>" + '<span class="glyphicon glyphicon-trash"></span>' + "</td>" + "</tr>");
//noOfItems = parseInt(noOfItems) + parseInt(OQty);
//noOfProducts = parseInt(noOfProducts) + 1;
}

rowIndex is not an attribute, so try .prop()
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).appendTo($log)
}
})();
jQuery(function() {
$('tr input').each(function() {
var rowId = $(this).closest('tr').attr('rowIndex');
log('attr: ' + rowId);
rowId = $(this).closest('tr').prop('rowIndex');
log('prop: ' + rowId);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input />
</td>
</tr>
<tr>
<td>
<input />
</td>
</tr>
</table>
<div id="log"></div>

Related

unable to load html table through onclick

I have a function which loads a html table with sql data query and a html page to display the table when i click the button but it is not showing the table, it just shows the url changing to match my search but does not display the table
Function code:
function Search()
{
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function()
{
search_array = JSON.parse(request.responseText);
result();
}
searchrestaurant.send(JSON.stringify(search));
}
function result()
{
var table = document.getElementById("result");
table.innerHTML = "";
result = search_array.length
for (var count = 0; count < result; count++)
{
// data from sql
var restaurant_name = search_array[count].restaurant_name;
var Description = search_array[count].Description;
var location = search_array[count].location;
var thumbnail = search_array[count].thumbnail;
var price = search_array[count].price;
var rating = search_array[count].avg_rating;
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>"+
"<td>" +"<a href = 'detailed_restaurant.html' target ='_blank'>"+"<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>"+"</td>" +
"<td>"+"<a href = 'detailed_restaurant.html' target ='_blank'>"+ restaurant_name + "</td>" +
"<td>"+ location + "</td>" +
"<td>"+ Description + "</td>" +
"<td>"+ price + "</td>" +
"<td>"+ rating + "</td>"
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
Html:
<body>
<form id = "SearchForm">
<label>Search </label>
<input type="text" id="searchinput" name="restaurantName">
<input type="button" onclick="Search()" value="Submit">
</form>
<div class="container"></div>
<div id="result" class="row"></div>
</div>
I have already loaded the script into the html site but it is just take my input and does not display the table i created
Concatenation operator is missing after "<td>" + rating + "</td>".
Add the + operator. like "<td>" + rating + "</td>" +.
function result() {
var table = document.getElementById("result");
table.innerHTML = "";
result = 5
for (var count = 0; count < result; count++) {
// data from sql
var restaurant_name = 1;
var Description = 'ddf';
var location = 'location';
var thumbnail = 1;
var price = 'Price';
var rating = 'rating';
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + "<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>" + "</td>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + restaurant_name + "</td>" +
"<td>" + location + "</td>" +
"<td>" + Description + "</td>" +
"<td>" + price + "</td>" +
"<td>" + rating + "</td>" +
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
result();
<div id="result" class="row"></div>
</div>
You have to pass the search array in your result function.
function Search() {
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function () {
search_array = JSON.parse(request.responseText);
result(search_array);
}
searchrestaurant.send(JSON.stringify(search));
}
Hope this will work.

how to check equality between and array and html table value

I check the equality between an array value and html table cell value both are same but how can i check this. I try this but it wont work properly. it always return true if there are same value. check this out.......
function addOrder() {
var bookid = document.getElementById("book_id").value;
var qty = document.getElementById("qty").value;
var price = document.getElementById("unit_price").value;
var total = document.getElementById("dts_total_price").value;
var table = document.getElementById("results");
var tableData = new Array();
$('#results tr').each(function() {
var row = $(this);
tableData.push(row.find("TD").eq(0).html());
});
tableData.shift();
var check;
for (var i = 0; i <= tableData.length; i++) {
var booksId = tableData[i];
alert(bookid);
if (bookid === booksId) {
check = false;
} else {
check = true;
}
}
alert(check);
var table_len = (table.rows.length);
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'>" +
"<td id='book_row" + table_len + "'>" + bookid + "</td>" +
"<td id='qty_row" + table_len + "'>" + qty + "</td>" +
"<td id='price_row" + table_len + "'>" + price + "</td>" +
"<td id='total_row" + table_len + "'>" + total + "</td>" +
"<td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'>" +
" <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> " +
"<input type='button' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("qty").value = "";
document.getElementById("unit_price").value = "";
document.getElementById("dts_total_price").value = "";
};

I want to fix the code concisely

var template is used as redundant I want to know how to fix it so you can use this section only once
function pluscal(data) {
var idx = index++
var form = parseInt($("#plusstr1").val()) + $("#plus_op").text() + parseInt($("#plusstr2").val())
var cal = parseInt($("#plusstr1").val()) + parseInt($("#plusstr2").val())
var template = "<tr>" +
"<td>" + idx + "</td>" +
"<td>" + form + "</td>" +
"<td>" + data.result + "</td>" +
"<td><button class='ul icon button' id='remove_btn'><i class='trash alternate icon'></i></button></td>" +
"</tr>"
$("tbody").append(template)
}
and
function minuscal(data) {
var idx = index++
var form = parseInt($("#minusstr1").val()) + $("#minus_op").text() + parseInt($("#minusstr2").val())
var cal = parseInt($("#minusstr1").val()) - parseInt($("#minusstr2").val())
var template = "<tr>" +
"<td>" + idx + "</td>" +
"<td>" + form + "</td>" +
"<td>" + data.result + "</td>" +
"<td><button class='ul icon button' id='remove_btn'><i class='trash alternate icon'></i></button></td>" +
"</tr>"
$("tbody").append(template)
}
Simply separate the logic related to template. Here I have organized it in one function. And I have merged pluscal and minuscal function.
function cal(data, calType) {
// calType need to be either plus or minus
var idx = index++
var form = parseInt($(`#${calType}str1`).val()) + $(`#${calType}_op`).text() + parseInt($(`#${calType}str2`).val())
var cal = parseInt($(`#${calType}str1`).val()) + parseInt($(`#${calType}str2`).val())
generateTemplate(idx, form, cal, data);
}
function generateTemplate(idx, form, cal, data) {
var template = `<tr>
<td> ${idx} </td>
<td> ${form} </td>
<td> ${data.result} </td>
<td><button class='ul icon button' id='remove_btn'><i class='trash alternate icon'></i></button></td>
</tr>`
$("tbody").append(template)
}
Create another function what returns the template
function getTemplate(idx, form, result) {
return "<tr>" +
"<td>" + idx + "</td>" +
"<td>" + form + "</td>" +
"<td>" + result + "</td>" +
"<td><button class='ul icon button' id='remove_btn'><i class='trash alternate icon'></i></button></td>" +
"</tr>";
}
So then you can use like this
function pluscal(data) {
var idx = index++
var form = parseInt($("#plusstr1").val()) + $("#plus_op").text() + parseInt($("#plusstr2").val())
var cal = parseInt($("#plusstr1").val()) + parseInt($("#plusstr2").val())
var template = getTemplate(idx, form, data.result);
$("tbody").append(template)
}
try this
function multiCase(caseType, data) {
if (caseType === 'Maj') {
str1 = "#plusstr1",
str2 = "#plusstr2",
op = "#plus_op"
} else {
str1 = "#minusstr1",
str2 = "#minusstr2",
op = "#minus_op"
}
var idx = index++
var form = parseInt($(str1).val()) + $(op).text() + parseInt($(str2).val())
var cal = parseInt($(str1).val()) + parseInt($(str2).val())
/* And other part of your function
...
...
*/
Hope it helps

why to use '$' in javascript variables?

I've seen others do these things to create a dynamic table element or other HTML on a page:
var $myRow = $('#myRowContainer' + IDRow);
var $column = $('<div />', { 'class': 'col', 'css': { 'width': '30%' } }).appendTo($myRow);
$('<div />', { css: { 'text-align': 'left' } }).append($('<span />', { 'html': objDetails[0].message })).appendTo($column);`
I often create html stuff in javascript like:
jQuery.each(mytable, function (i, obj) {
var newrow = ' <tr> ';
newrow += ' <td> ';
newrow += ' <span> ' + obj.ID + '</span>';
newrow += ' </td> ';
newrow += ' <td> ';
newrow += ' <span> ' + obj.PartNumber + ' </span>';
newrow += '</td>';
newrow += ' <td> ';
var name1 = 'txEI_';
var consecutive = obj.IDc;
var idLabelText = name1 + consecutive;
newrow += ' <input id="' + idLabelText + '" class="' + myCssClassToDetect + '" type="text" value="0" /> ';
newrow += ' </td> ';
newrow += ' </tr> ';
$("#tbDesglose").append(newrow);
//make spinner for new field
makeSpinner(idLabelText);
});
What's the difference? Why choose one over another?
When I see var prefixed with $ in javascript, it just usually means the variable is storing some element that is already wrapped in jQuery.
It's just a coding convention some people do.

How can I add javascript touch spin to html when call javascript function

I have button to add new row(s) to table.
In the table row have a column with touch spin.
I want to loop through Array(Items). to make a rows. But below code make a Error Uncaught TypeError: undefined is not a function at function tp0
function showtable() {
$('#showtable').html("");
for(var i in Items) {
var no = parseInt($('#tb tr').length) - 1;
var data = "<tr role='row' class='filter' >"
+ "<td>" + no
+ "</td>"
+ "<td>"
+ "<div class='form-group'>"
+ "<input id='touch" + i + "' type='text' value='1' name='touch" + i + "' /> "
+ "<script>"
+ "function tp" + i + " () {$(\"input[name=\'touch" + i + "\']\").TouchSpin(); alert('ttt');}"
+ "</scr" + "ipt>"
+ "</div>"
+ "</td>"
+ "</tr>";
$('#showtable').append(data);
var method_name = "tp";
window[method_name + i]();
}
}
Have any ideas thanks
Instead of adding functions like that with each row, you should just pass the row number as a variable to a predefined function:
function tp(index) {
$("input[name='touch" + index + "']").TouchSpin();
alert('ttt');
}
function showtable() {
$('#showtable').html("");
for (var i in Items) {
var no = parseInt($('#tb tr').length) - 1;
var data = "<tr role='row' class='filter' >"
+ "<td>" + no
+ "</td>"
+ "<td>"
+ "<div class='form-group'>"
+ "<input id='touch"+i+"' type='text' value='1' name='touch"+i+"' /> "
+ "</div>"
+ "</td>"
+ "</tr>";
$('#showtable').append(data);
tp(i);
}
}

Categories

Resources