How do I load bootstrap in a new browser tab - javascript

I am running a code that scrapes a form and then opens a new browser tab with the data using the format: fieldID, fieldLabel, filedValue
jQuery(document).ready(function(){jQuery('#helpdesk_ticket_submit').on('click', function(e){
submitText = "<table class='table'>"
submitText += ` <thead>
<tr>
<th scope="col">fieldID</th>
<th scope="col">fieldLabel</th>
<th scope="col">fieldValue</th>
</tr>
</thead>
<tbody>`
jQuery('#new_helpdesk_ticket input, #new_helpdesk_ticket select, #new_helpdesk_ticket textarea').each(
function(index){
var input = jQuery(this);
if (input.prev().is('textarea'))
if (input.attr('class').indexOf('hide') >= 0)
return;
let label = extractLabelText(input.attr('id')) //extrenal function to get the label of the field
submitText += "<tr><td>" + input.attr('id') + "</td><td>" + label + "</td><td> " + input.val() + "</td></tr>"
}
);
window.open().document.write(submitText);
there is nothing wrong with the code. My question is when I do window.open().document.write(submitText); how can I format the table with bootstrap?

Related

Highlight Searched Text in Table bug

So I'm working on a feature that require a user to type in a search item that will search a table for the term and highlight every occurrence. I found some code and got it to work, but I have a bug that I'm not sure how to resolve. In the search input if I hit back space to erase the search term, the unhighlight works until the last character letter. For example, I type in Demo and use back space to delete Demo, only the D is still highlighted.
Below are my code snippets.
NOTE: I have a search and render function that call the highlightActivity and renderReports functions
My CSS
.highlight {
background-color :gold
}
.highlight {
padding:1px 4px;
margin: 0 -4px;
}
My HTML
<input type="text" id="uniStringSearch" onkeyup="SearchAndRender()"></input>
<table id="currentReports" class="table table-striped table-condensed table-bordered">
<thead>
<tr>
<th><input name="select_all" id="selectedReports" value="1" type="checkbox" onclick="checkAll(this)" /> </th>
<th>DATE</th>
<th>SUMMARY TITLE</th>
<th>NAME</th>
<th>ACTIVITY TYPE</th>
<th>SUB ACTIVITY TYPE</th>
<th>ACTIVITY DETAILS</th>
</tr>
</thead>
<tbody id="reports"></tbody>
</table>
HighlightActivity Function
function highlightActivity() {
var searchTerm = $('#uniStringSearch').val();
var tableID = ''
switch (webPage) {
case 'reports':
tableID = '#currentReports';
break;
case 'analysis':
tableID = '#currentAnalysis';
break;
case 'statuses':
tableID = '#currentStatuses';
break;
default:
}
$(tableID).find('.highlight').removeClass('highlight');
$(tableID).find('tr td').each(function () {
if ((this).attr('data-search') !== 'false') {
var text = $(this).text();
var textLowerCase = text.toLowerCase();
var pos = textLowerCase.indexOf(searchTerm.toLowerCase());
var regex = new RegExp(searchTerm, 'ig');
text = text.replace(regex, (match, $1) => {
return '<span class="highlight">' + match + '</span>';
});
$(this).html(text);
if (pos !== -1) {
setTimeout(function () {
if ($(this).parent().find('.highlight').is(':empty')) {
$('.highlight').remove();
}
}.bind(this), 0);
}
else {
$(this).text(text);
}
}
if ($(this).parent().find('.highlight').length > 0) {
$(this).parent().show();
}
else {
$(this).parent().hide();
}
});
}
Render Reports Function
function renderReports(items) {
var html = '';
for (var i = 0; i < items.length; i++)
{
html = '<tr><td><input type="checkbox" id="selectedReports" onchange="chkInputChanged(event)"/></td>'
html += '<td>' + items[i].DateActivity + '</td>'
html += '<td>' + items[i].Name + '</td>'
html += '<td>' + items[i].ActivityType + '</td>'
html += '<td>' + items[i].SubActivityType + '</td>'
html += '<td id="searchActivityDetails">' + items[i].ActivityDetails + '</td></tr>'
}
$('#reports').empty();
$('#reports').append(html);
}
ALSO....one more thing, is there a way to have my highlight function to target a specific column? For example Summary Title and Activity Details

build unique table with JQuery AJAX

I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>

Javascript: calculate appended value

I have this table which adds service. Im trying to input evry quantity and display total on keyup on the right.
I can only get the first row working not the next rows.
Here are my codes
$(document).on('keyup',function(){
var pri = $('#price_display').val();
var q = $('#qty_display').val();
var tots = pri*q;
$('#sub_display').val(tots);
});
every row is added through append
price_display holds the price value
qty_display holds the inputted value
sub_dispplay holds the output value
I'm willing to bet each row has the same ID for each column (e.g. id=price_display). IDs by definition need to be unique on each page, so jQuery always finds the first instance of each (i.e. the first row).
Probably the easiest way around this is to append a row number to each field, e.g. price_display_1, qty_display_1, sub_quantity_1 etc. - that way jQuery can look for the right instance of each field.
See below for an example - although having said all this, it looks as though you're using something like Angular Material to style your page, so it might be worth your time investigating databinding in AngularJS to save you the hassle.
// source data for table (array holds a JavaScript object per row)
var tableData = [{
serviceCode: 'xbed',
serviceName: 'xbed',
price: 500,
quantity: 1
},
{
serviceCode: 'xpil',
serviceName: 'xpil',
price: 200,
quantity: 2
}
];
// find the table body
var $tableBody = $("#myTable").children("tbody");
// for each row of data, generate a table row
tableData.forEach(function(row, index) {
var rowIndex = index + 1;
$tableBody.append("<tr>" +
"<td><input type='text' id='service_code_" + rowIndex + "' value='" + row.serviceCode + "' /></td>" +
"<td><input type='text' id='service_name_" + rowIndex + "' value='" + row.serviceName + "' /></td>" +
"<td><input type='text' class='price' id='price_display_" + rowIndex + "' value='" + row.price + "' /></td>" +
"<td><input type='text' class='qty' id='qty_display_" + rowIndex + "' value='" + row.quantity + "' /></td>" +
"<td><input type='text' class='total' id='sub_display_" + rowIndex + "' value='" + row.price * row.quantity + "' /></td>" +
"</tr>");
});
// wire up keyboard handlers
$(".price, .qty").on("keyup", function(evt) {
var $row = $(evt.target).closest("tr"),
price = $row.find(".price").first().val(),
qty = $row.find(".qty").first().val(),
$total = $row.find(".total").first();
$total.val(price * qty);
});
table {
font-family: 'Arial', sans-serif;
}
input {
width: 8em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>Service code</th>
<th>Service name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Change ids to classes and try that code:
$(document).on('keyup', '.qty_display, .price_display', function(){
var row = $(this).parent('tr');
var pri = row.find('.qty_display').val();
var q = row.find('.price_display').val();
var tots = pri*q;
row.find('.sub_display').val(tots);
});
In that way you will change only need rows with correct values.
try to log "tots" variable value, is it coming?
if YES
**THEN**
make sure must have unique "#sub_display" id to display the value else it only appears on the first raw
if NO
**THEN**
try to log the second raw object eg:-console.log(this)

How to show total of dynamically added column using jquery

I have made a shopping cart where I added row based on autocomplete search. and based on quantity price changed. But I want to find the total of subtotal..I have written the update part. But it's showing 0 instead of actual value. Can anyone help me to find it out what's the wrong in my jQuery code..Thank You!
$('#searchName').autocomplete({
source: '{!! asset('nameAutocomplete') !!}',
select:function(suggestion,ui){
event.preventDefault();
var $tbody = $('#example tbody');
$tbody.append('<tr><td class="id">' + ui.item.id +
'</td><td class="name">' + ui.item.value +
'</td><td class="price">' + ui.item.price +
'</td><td><input type="text" class="quantity" value="1"/></td><td><input type="text" class="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');
$('.quantity').on('keyup',function(){
var tot = $(this).parent().prev().html() * this.value;
$(this).parent().next().find('.total').val(tot);
console.log(calculateSum());
});
function calculateSum(){
var sum = 0;
$(".total").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
return sum;
}
}
});
Here is table part :
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
$(".total") is an input, so you should use var value = $(this).val();, not var value = $(this).text();

How to Add data in tbody using Javascript only

This is my Javascript function:
function SaveCustomdata() {
var customName = document.getElementById("lblNAME").value;
var customEmail = document.getElementById("lblEmail").value;
var customContectNo = document.getElementById("lblContectNO").value;
var row = "";
row += '<tr><td>' + customName + '</td><td>' + customEmail + '</td><td>' + customContectNo + '</td></tr>';
document.getElementById("Customdata").appendChild(row);
}
HTML code where I want to append the data:
<table>
<thead>
<tr>
<th style=" color:#01A0DF; padding-right:60px;">Name</th>
<th style=" color:#01A0DF; padding-right:70px;">Email</th>
<th style=" color:#01A0DF; padding-right:90px;">Contect/Mobile No</th>
<td>
<input type="button" id="btnclick" value="Add" onclick="AddRecord()" />
</td>
</tr>
</thead>
<tbody id="Customdata"></tbody>
</table>
Getting an error:
0x800a139e - JavaScript run time error: Hierarchy Request Error
With the use of innerHTML:
function SaveCustomdata() {
var customName = document.getElementById("lblNAME").value;
var customEmail = document.getElementById("lblEmail").value;
var customContectNo = document.getElementById("lblContectNO").value;
var row = "";
row += '<tr><td>' + customName + '</td><td>' + customEmail + '</td><td>' + customContectNo + '</td></tr>';
// get the current table body html as a string, and append the new row
var html = document.getElementById("Customdata").innerHTML + row;
// set the table body to the new html code
document.getElementById("Customdata").innerHTML = html;
}
Here you have a fiddle. Let us know if it helped you a bit.Basically you could use .innerHTML for appending strings as elements, because this gets "evaluated by browser".Otherwise you would have to do it programmatically as mentioned in the comments

Categories

Resources