Make a Button Visible Conditionally Using Javascript - javascript

I am putting a javascript button on a form. The script works, but can I make that button visible only if the DESCRIPTION field starts with a number?
The button gets added to the form and code I could gather is below. That button then calls the function that opens the external url.
<push al="center" btnnm="OnBase" col="45" det="DT0" height="1" id="hidden57" keynbr="function=ShowOnBaseInvoiceDocument()" nbr="_f292r0" nm="" par="DT0" row="1" sz="8" tooltip="" tp="Hidden"/>
function ShowOnBaseInvoiceDocument0()
{
var onBaseServer = "someserver";
var appName = "Dev";
var screenID = "90";
var accField = "InvoiceNum";
var venField = "VendorID";
var company = Form.getDataValue("TO-COMPANY");
var RefNums = Form.getDataValue("REFERENCE", 0);
var RefNum = RefNums.trim();
var sVenNumbers = Form.getDataValue("DESCRIPTION", 0);
var sVenNumber = sVenNumbers.substring(0,9);
if (RefNums == "")
{
portalWnd.cmnDlg.messageBox("Not a valid invoice.","ok","info",window,false)
return true;
}
var s = "http://" + encodeURIComponent(onBaseServer)
+ "/OnBaseLinkScanWeb/AccLogin.aspx?DBID=" + encodeURIComponent(appName)
+ "&ScreenID=" + encodeURIComponent(screenID)
+ "&Company=" + encodeURIComponent(company)
+ "&RefNum=" + encodeURIComponent(RefNum)
+ "&" + encodeURIComponent(venField) + "=" + encodeURIComponent(portalWnd.strTrim(sVenNumber));
//portalWnd.cmnDlg.messageBox(s,"ok","info",window,false)
window.open(s, "My Invoice");
console.log(s);
return true;
}
Rows Data
Button
205121GMAC CASHIERS OF
Button
Di Closed Bank 0000
No Button
Close Bank 0073-0000 Al
No Button

You can simply loop over all the rows and then check if the first column starts with a Number and if it does not you can simply hide the button.
document.querySelectorAll("tr").forEach(row => {
const firstCol = row.children[0];
const secondCol = row.children[1];
if (!"0123456789".includes(firstCol.innerText[0])) {
secondCol.style.visibility = "hidden";
}
});
<table>
<tr>
<td>1234567</td>
<td><button>Click</button></td>
</tr>
<tr>
<td>HelloWorld</td>
<td><button>Click</button></td>
</tr>
<tr>
<td>245Bye</td>
<td><button>Click</button></td>
</tr>
<tr>
<td>Upvote</td>
<td><button>Click</button></td>
</tr>
</table>

Related

How do I dynamically change the ID to do calculations?

I have the same form duplicated and triplicated, and depending on clicks on a button, they appear. What I want to do is to be able to make calculations, for example, of the cell Quantity and Unit_Price a multiplication and that the result is reflected in Total Price.
I need the Quantity and Unit_Price IDs to change dynamically so that the result is displayed per cell in their respective Total Price. I already wrote a piece of code that takes the number of each cell, the problem is that I don't know how to put it with the ID so that it is dynamic (the number should change depending on the cell it is in)
This is where I don't know how the code should be:
function multiplicar() {
let quantity = parseInt(document.getElementById('id__form-1-quantity').value);
let unit_price = document.getElementById('id__form-1-unit_price').value;
let total_price = document.getElementById('id__form-1-total_price');
total_price.value = quantity * unit_price;
}
function updateEmptyFormIDs(element, totalForms) {
var thisInput = element
var currentName = element.attr('name')
var newName = currentName.replace(/__prefix__/g, totalForms)
thisInput.attr('name', newName)
thisInput.attr('id', "id__" + newName)
var newFormRow = element.closest(".part-form");
var newRowId = "row_id_" + newName
newFormRow.attr("id", newRowId)
newFormRow.addClass("new-parent-row")
var parentDiv = element.parent();
parentDiv.attr("id", "parent_id_" + newName)
var inputLabel = parentDiv.find("label")
inputLabel.attr("for", "id_" + newName)
return newFormRow
}
function addForm() {
//$('.add-new-form').click(function(e){
var formId = "id_form-TOTAL_FORMS"
var emptyRow = $("#empty-row").clone();
emptyRow.attr("id", null);
var totalForms = parseInt($('#' + formId).val());
var newFormRow;
emptyRow.find("input,select,textarea").each(function() {
newFormRow = updateEmptyFormIDs($(this), totalForms)
})
$(".part-form:last").after(newFormRow)
$('#' + formId).val(totalForms + 1);
}
<table>
<tr>
<td id="parent_id_form-1-quantity">
<input type="number" name="form-1-quantity" class="form-control" id="id__form-1-quantity">
</td>
<td id="parent_id_form-1-unit_price">
<input type="number" name="form-1-unit_price" class="form-control" onchange="multiplicar()" id="id__form-1-unit_price">
</td>
<td id="parent_id_form-1-total_price">
<input type="number" name="form-1-total_price" class="form-control" id="id__form-1-total_price">
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

JQuery Highlight Row and Column in table

I want to add to my site table with highlighting row and column, but I have troubles with
column highlighting. This is my table. This is online courses and a full the table with
names such as Homework1, HW2 and etc.
%if len(students) > 0:
<div class="grades">
<table class="grade-table">
<%
templateSummary = students[0]['grade_summary']
%>
<thead>
<tr class = "table-header"> <!— Header Row —>
%for section in templateSummary['section_breakdown']:
//......
<th title="${tooltip_str}"><div class="assignment-label">${section['label']}</div></th>
%endfor
<th title="${_('Total')}"><div class="assignment-label">${_('Total')}</div></th>
</tr>
</thead>
<%def name="percent_data(fraction, label)">
//....
<td class="${data_class}" data-percent="${fraction}" title="${label}">${ "{0:.0f}".format( 100 * fraction ) }</td>
</%def>
<tbody>
%for student in students:
<tr class="table-row">
%for section in student['grade_summary']['section_breakdown']:
${percent_data( section['percent'], section['detail'] )}
%endfor
${percent_data( student['grade_summary']['percent'], _('Total'))}
</tr>
%endfor
</tbody>
</table>
This is JQuery. So in highlightRow() is making the magic with row, but I don't understand,
to add highlightColumn() and "$element.find('tr').bind('mouseover', highlightColumn);" or
to add in the function highlightRow() code for column.
var Gradebook = function($element) {
"use strict";
var $body = $('body');
var $grades = $element.find('.grades');
var $studentTable = $element.find('.student-table');
var $gradeTable = $element.find('.grade-table');
var $search = $element.find('.student-search-field');
var $leftShadow = $('<div class="left-shadow"></div>');
var $rightShadow = $('<div class="right-shadow"></div>');
var tableHeight = $gradeTable.height();
var maxScroll = $gradeTable.width() - $grades.width();
var mouseOrigin;
var tableOrigin;
var startDrag = function(e) {
mouseOrigin = e.pageX;
tableOrigin = $gradeTable.position().left;
$body.addClass('no-select');
$body.bind('mousemove', onDragTable);
$body.bind('mouseup', stopDrag);
};
var highlightRow = function() {
$element.find('.highlight').removeClass('highlight');
var index = $(this).index();
$studentTable.find('tr').eq(index + 1).addClass('highlight');
$gradeTable.find('tr').eq(index + 1).addClass('highlight');
};
$leftShadow.css('height', tableHeight + 'px');
$grades.append($leftShadow).append($rightShadow);
setShadows(0);
$grades.css('height', tableHeight);
$gradeTable.bind('mousedown', startDrag);
$element.find('tr').bind('mouseover', highlightRow);
$search.bind('keyup', filter);
$(window).bind('resize', onResizeTable);
};
It should be something like this:
$element.find('td').bind('mouseover', highlightColumn);
var highlightColumn = function() {
//remove all highlights
//not sure if it should be here may be it should happen before both highlightRow and highlightColumn function calls
$element.find('.highlight').removeClass('highlight');
var columnIndex = $(this).index(); //this should be td in this case
$studentTable.find('tr td:eq(' + columnIndex + ')').addClass('highlight');
$gradeTable.find('tr td:eq(' + columnIndex + ')').addClass('highlight');
};

How to get all values from querySelectorAll and pass to URL in javascript

I am trying to send a dynamic TD of table which returned 3 values..I am using the line below to submit the value...I want to be able to pass all three values to a URL LIKE THIS 778, 44, 45
function JSalert() {
// var valueID = document.getElementById('idweek1').innerHTML
var data = document.querySelectorAll('[name=idweek1]');
for (var i = 0; i < data.length; i++) {
theids = data[i].className + " " + data[i].childNodes[0].nodeValue;
window.location = 'http://localhost/bcwater/public/submitinvestment/'+value8+'/'+theids;
}
}
<td id="idweek1" name="idweek1">778</td>
<td id="idweek1" name="idweek1">44</td>
<td id="idweek1" name="idweek1">55</td>
I was able to get it done using the method below
var array_of_name = [];
var elements_arr = document.getElementsByClassName("idweek1");
for (var i in elements_arr) {
array_of_name.push(elements_arr[i].innerHTML);
}
console.log("TRGY",array_of_name);
So when i pass the variable to the URL it works fine
window.location = 'http://localhost/bcwater/public/submitinvestment/'+value8+'/'+array_of_name;
Basically nothing with your code, except it's missing <table> & <tbody> elements.
var data = document.querySelectorAll('[name=idweek1]');
var value8 = 88888888;
for (var i = 0; i < data.length; i++) {
id = data[i].childNodes[0].nodeValue;
console.log(id);
console.log('http://localhost/bcwater/public/submitinvestment/' + value8 + '/' + id);
}
// window.location.href = 'http://localhost/bcwater/public/submitinvestment/' + value8 + '/' + id;
<table>
<tbody>
<tr>
<td id="idweek1" name="idweek1">778</td>
<td id="idweek1" name="idweek1">44</td>
<td id="idweek1" name="idweek1">55</td>
</tr>
</tbody>
</table>

jQuery/Javascript compare two tables against each other

I need to compare two HTML tables' rows assuming that data in first cell can be duplicated but data in second cell is always unique. I need to find whether first cell AND second cell in table1 is the same as data in first cell AND second cell in table2 for instance:
Table1:
<Table>
<tr>
<td>123</td>
<td>321</td>
</tr>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>0</td>
<td>312</td>
</tr>
<tr>
<td>123</td>
<td>323331</td>
</tr>
</Table>
Second table:
<table>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>545</td>
<td>3122</td>
</tr>
<tr>
<td>123</td>
<td>321</td>
</tr>
</table>
The result of this should be:
123 321 - good, do nothing
545 345 - good, do nothing
545 3122 - wrong its not in table1 <-
Here's what I've got so far...
$('#runCheck').click(function(){
var firstTable = $('#firstDiv table tr');
var secondTable = $('#secDiv table tr');
$(secondTable).each(function(index){
var $row = $(this);
var secTableCellZero = $row.find('td')[0].innerHTML;
var secTableCellOne = $row.find('td')[1].innerHTML;
$(firstTable).each(function(indexT){
if ($(this).find('td')[0].innerHTML === secTableCellZero){
if ($(this).find('td')[1].innerHTML !== secTableCellOne){
$('#thirdDiv').append("first: " + secTableCellZero + " second: " + secTableCellOne+"<br>");
}
}
});
});
});
Where am I going it wrong?
Just to clarify once again:
2nd table says :
row1 - john|likesCookies
row2 - peter|likesOranges
1st table says :
row1 - john|likesNothing
row2 - john|likesCookies
row3 - steward|likesToTalk
row4 - peter|likesApples
now it should say :
john - value okay
peter - value fail.
a lot alike =VLOOKUP in excel
Check this working fiddle : here
I've created two arrays which store values in each row of tables 1 and 2 as strings. Then I just compare these two arrays and see if each value in array1 has a match in array 2 using a flag variable.
Snippet :
$(document).ready(function() {
var table_one = [];
var table_two = [];
$("#one tr").each(function() {
var temp_string = "";
count = 1;
$(this).find("td").each(function() {
if (count == 2) {
temp_string += "/";
}
temp_string = temp_string + $(this).text();
count++;
});
table_one.push(temp_string);
});
$("#two tr").each(function() {
var temp_string = "";
count = 1;
$(this).find("td").each(function() {
if (count == 2) {
temp_string += "/";
temp_string = temp_string + $(this).text();
} else {
temp_string = temp_string + $(this).text();
}
count++;
});
table_two.push(temp_string);
});
var message = "";
for (i = 0; i < table_two.length; i++) {
var flag = 0;
var temp = 0;
table_two_entry = table_two[i].split("/");
table_two_cell_one = table_two_entry[0];
table_two_cell_two = table_two_entry[1];
for (j = 0; j < table_one.length; j++) {
table_one_entry = table_one[j].split("/");
table_one_cell_one = table_one_entry[0];
table_one_cell_two = table_one_entry[1];
console.log("1)" + table_one_cell_one + ":" + table_one_cell_two);
if (table_two_cell_one == table_one_cell_one) {
flag++;
if (table_one_cell_two == table_two_cell_two) {
flag++;
break;
} else {
temp = table_one_cell_two;
}
} else {}
}
if (flag == 2) {
message += table_two_cell_one + " " + table_two_cell_two + " found in first table<br>";
} else if (flag == 1) {
message += table_two_cell_one + " bad - first table has " + temp + "<br>";
} else if (flag == 0) {
message += table_two_cell_one + " not found in first table<br>";
}
}
$('#message').html(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="one">
<tr>
<td>123</td>
<td>321</td>
</tr>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>0</td>
<td>312</td>
</tr>
<tr>
<td>123</td>
<td>323331</td>
</tr>
</table>
<hr>
<table id="two">
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>545</td>
<td>3122</td>
</tr>
<tr>
<td>123</td>
<td>321</td>
</tr>
</table>
<hr>
<div id="message">
</div>
</div>
If I understand your requirements, it would be easier to read the first table and store the couples as strings: 123/321, 545/345, etc...
Than you can read the second table and remove from the first list all the rows found in both.
What remains in the list are couples that do not match.
From purely an efficiency standpoint if you loop through the first table just once and create an object using the first cell value as keys and an array of values for second cells, you won't have to loop through that table numerous times
this then makes the lookup simpler also
var firstTable = $('#firstDiv table tr');
var secondTable = $('#secDiv table tr');
var firstTableData = {}
firstTable.each(function() {
var $tds = $(this).find('td'),
firstCellData = $tds.eq(0).html().trim(),
secondCellData == $tds.eq(1).html().trim();
if (!firstTableData[firstCellData]) {
firstTableData[firstCellData] = []
}
firstTableData[firstCellData].push(secondCellData)
})
$(secondTable).each(function(index) {
var $tds = $(this).find('td');
var secTableCellZero = $tds.eq(0).html().trim();
var secTableCellOne = $tds.eq(1).html().trim();
if (!firstTableData.hasOwnProperty(secTableCellZero)) {
console.log('No match for first cell')
} else if (!firstTableData[secTableCellZero].indexOf(secTableCellOne) == -1) {
console.log('No match for second cell')
}
});
I'm not sure what objective is when matches aren't found

Dynamic Div ID and Creating Elements Inside it

I am creating a dynamic Div where i can import values from the showModalDialog when it is closed. So after closing the modal, i get couple of values.
What i am trying to do here is:
I have couple of dynamic div's and against each div, i have a link to open a window.
After selection of the files they are return back to the parent window as comma separated.
I want to insert those values inside the div to which that popup was opened. but in this scenario i am facing the trouble. the Divid's are generated dynamically
Here is the Complete Code for Javascript + Jquery Based, I am getting the following error.
TypeError: theDiv.appendChild is not a function
[Break On This Error]
theDiv.appendChild(newNode);
<script type="text/javascript" src="JS/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function eliminateDuplicates(arr,divID)
{
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++)
{
obj[arr[i]]=0;
}
for (i in obj)
{
out.push(i);
}
return out;
}
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
Test= function(str,divID)
{
var arrID = new Array();
arrID = str.split(',');
arrID = eliminateDuplicates(arrID);
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
alert(theDiv);
var cmp= $("#projectIDS"+divID).val(); //document.getElementById("projectIDS").value;
var cnp = $("#countProj"+divID);//document.getElementById("countProj")
var cproj;
if(cnp.val().length == 0)
cproj=0;
else
cproj=parseInt(cnp.val());
for (var j=0; j<arrID.length; j++)
{
if (parseInt(cproj) + 1 > 50)
{
alert("You cannot add more than 50 Project id's ");
return;
}
if( cmp!="" && cmp.indexOf(arrID[j])!=-1)
continue;
var newNode = document.createElement('div');
newNode.style.cssText = "background:#CCCCCC;border:1px solid #666666;width:100px;word-wrap:break-word;margin:3px;float:left;color:black;text-decoration:none!important;height:auto;vertical-align:middle;padding-top:2px;";
newNode.title = arrID[j]+" ";
newNode.innerHTML = '<input type=hidden name=Proj_' + j + ' ' + 'value=' + arrID[j] + '>' + arrID[j] + ' <b>X</b>';
theDiv.appendChild(newNode);
if(cmp.length == 0)
{
//document.getElementById("projectIDS").value=arrID[j]
$("#projectIDS"+divID).val(arrID[j]);
}
else
{
//document.getElementById("projectIDS").value = document.getElementById("projectIDS").value+","+arrID[j];
$("#projectIDS"+divID).val($("#projectIDS"+divID).val()+","+arrID[j]);
}
cproj = parseInt(cproj)+1;
//document.getElementById("countProj").value =cproj;
cnp.value(cproj);
}
}
removetext = function(par)
{
var strremove=par.text();
var strexist = document.getElementById("projectIDS").value;
strremove = strremove.replace(" X","");
tempRemove(strexist, strremove);
par.remove();
var cproj;
if(document.getElementById("countProj").value.length == 0)
cproj=0;
else
{cproj=parseInt(document.getElementById('countProj').value);
cproj=parseInt(cproj)-1;}
document.getElementById("countProj").value =cproj;
}
function tempRemove(strexist,strremove)
{
var b = strexist.indexOf(strremove);
var after = strexist.indexOf(",",b);
var newstrexist;
var before = strexist.lastIndexOf(",",b);
if(after!=-1)
{newstrexist=strexist.replace(strremove+',',"");}
else if(before!=-1)
{newstrexist=strexist.replace(','+strremove,"");}
else
{newstrexist= strexist.replace(strremove,"");}
document.getElementById("projectIDS").value=newstrexist;
//remove current friend
}
function openWindow(divID)
{
var lookUpAlys=window.showModalDialog("files.cfm?d=" + Math.random() + '&fileID=' + divID,window,"center=yes;dialogWidth:895px:dialogHeight:785px;status:no");
if(lookUpAlys.forename!=undefined)
{
var temp = lookUpAlys.forename;
Test(temp,divID);
}
}
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="2" cellpadding="1">
<tr>
<td>Choose</td>
<td>Files</td>
<td>Action</td>
</tr>
<cfloop from="1" to="5" index="i">
<cfoutput>
<tr>
<td><input type="checkbox" name="getFile" id="getFile" value="#i#" /></td>
<td><div id="projectsList#i#" style="width:500px;height:60px;overflow-y:scroll;border:1px solid gray;"></div><input type="text" name="projectIDS#i#" id="projectIDS#i#" data-id="#i#" value="" /><input type="text" data-id="#i#" name="countProj#i#" id="countProj#i#" value="" /></td>
<td>Files</td>
</tr>
</cfoutput>
</cfloop>
</table>
</body>
</html>
so my apologies if i had entered the code incorrectly. Basically trying do it Classic Javascript Way
This does not do what I think you think it does:
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
You should do
var theDiv = $("#projectsList"+divID)[0];
to get the DOM element.
Or, for this scenario, just do
var theDiv = document.getElementById("projectsList" + divID);
Also, I'm not sure why you are mixing raw DOM operations and jQuery wrapped operations everywhere. Just stick to one of them, and be consistent.
var container = $('.itemsList');
var divSubmit = $(document.createElement('div'));
//assigning id to div
$(divSubmit).attr('id','itemTemplate');
$(divSubmit).css({"font-family":"Gotham, Helvetica Neue, Helvetica, Arial, sans-serif","position":"relative","height": "70px","clear" : "both","background-color":"#FFF","border-bottom": "0.09em solid #EBEBEB"});
//adding class to main container
$(divSubmit).addClass('itemTemplate');
//adding Child's name label and assigning id to it.
var Name = '<label class="lblName" id="lblName" for="Name">'+getName()+'</label>';
$(divSubmit).append(Name);
$(divSubmit).append(container);
Here's a sample code. first of all there is sample container called itemslist
that will contain the generated div.
divSubmit will be gernerate dynamically and append to container.
To find some div for click event. Lets say we want to get child name.
alert($($(this).find("label.lblName")).val());

Categories

Resources