Run a javascript from a html table cell - javascript

I am using asp.net core 5 and I have the following cell in a table -
<td id="actionId" class="text-left">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
</td>
I am trying to call a javascript function and add html at designationplaceholder for each record in the table.
I have tried -
$('tr').each(function (i, item) {
var html = DesignationStatus($('#dedesignatedDateId').val(), $('#renewalDueId').val(), $('#nextRenewalDueAtId').val(), #(ViewBag.NumberOfDays));
$('#designationPlaceHolderHere').html(html);
});
Doesn't work properly.
I want to call the function, for each record, passing the appropriate values for each record.
Any ideas?
Thanks
[UPDATE]
This is the function I call -
function DesignationStatus(dedesignatedDate, renewalDue, nextRenewalDue, numberOfDays) {
var isRenewalDue = (renewalDue === 'true')
//Get today's date
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
//Create next renewal due date display value.
var reDate = new Date(nextRenewalDue);
var reDay = reDate.getDate();
var reMonth = reDate.getMonth() + 1;
var displayRenewalDate = (reDay < 10 ? '0' : '') + reDay + '/' + (reMonth < 10 ? '0' : '') + reMonth + '/' + reDate.getFullYear()
//Create de-designation date display value.
var deDate = new Date(dedesignatedDate);
var deDay = deDate.getDate();
var deMonth = deDate.getMonth() + 1;
var displayDedesignationDate = (deDay < 10 ? '0' : '') + deDay + '/' + (deMonth < 10 ? '0' : '') + deMonth + '/' + deDate.getFullYear()
//Calculate what one day is
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
//Parse the number off days passed in
var numOfDays = parseInt(numberOfDays);
//If no number has been passed in set to default of 90.
if (isNaN(numberOfDays)) {
numOfDays = 90;
}
//Start html string
var html = '<div>'
html += ' <label>Designation status:</label>'
html += ' </div>'
html += ' <div>'
//Get rest of html dependant on due date etc.
if (dedesignatedDate != null && dedesignatedDate != "") {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>De-designated on</label>' + ' ' + displayDedesignationDate
}
else {
if (nextRenewalDue != null && nextRenewalDue != "") {
var today = new Date();
var renewal = new Date();
today = Date.parse(todaysDate);
renewal = Date.parse(nextRenewalDue);
if (renewal > today) {
if (!isRenewalDue) {
html += ' <div class="alert alert-success" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Active</label>'
}
else {
html += ' <div class="alert alert-warning" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Due to renew - renew before </label>' + ' ' + displayRenewalDate
}
}
else if (renewal < today) {
//Work out the number of days between renewal and today's date
var diffDays = Math.round(Math.abs(((new Date(today).getTime()) - (new Date(renewal).getTime())) / (oneDay)));
if (diffDays < numOfDays) {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive - lapsed on </label>' + ' ' + displayRenewalDate;
}
else {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive</label>'
}
}
}
}
//Finish off the html string
html += ' </div>'
html += ' </div>'
html += '</div>'
//return html strin
return html
}

<td id="actionId" class="text-left" onclick="DesignationStatus('#clinic.VaccClinic.DedesignationDate','#clinic.RenewalDue','#clinic.VaccClinic.NextRenewalDueAt','#ViewBag.NumberOfDays')">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
This should call your javascript function. Also never use the same id="dedesignatedDateID".

Related

Trying to get the HTML displayed to change every time a new button is clicked with jquery

let table = 6;
let i = 1;
$(function() {
let $newOperatorButton = $('button');
$newOperatorButton.on('click', function math(){
let msgOperator = '';
let expression;
let operator = $(this).attr("value");
if(operator === '+'){
msgOperator = ' + ';
expression = (table + i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table + i) + '<br />';
i++;
}
} else if (operator === '-') {
msgOperator = ' - ';
expression = (table - i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table - i) + '<br />';
i++;
}
some code missing but it adds multiplication and division
let el = document.getElementById('blackboard');
el.innerHTML = msg;
}
);
});
This code is inside the body tag in my index.html
<section id="page">
<section id="blackboard"></section>
</section>
<form id="operator">
<button name="add" type="button" value="+">+</button>
<button name="subtract" type="button" value="-">-</button>
<button name="multiply" type="button" value="x">x</button>
<button name="division" type="button" value="/">/</button>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/index.js"></script>
I have it so it prints out a table with 10 numbers depending on the button clicked. For ex. table = 6 and i = 1 is 6+1=7.... 6+10=16
You need an if statement at the end that reset your equations and variables.
after you've run your equation "i" is still equal to 11 so it never passes into the while loops again, you also need to empty your message so it doesn't keep adding addition text to your existing text.
$("#blackboard").html(msg)
if (i == 11) {
i = 1
msg = ""
}

I cannot add the class "unread" to the append content of a certain data-id

I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!

Calculate Percentage in HTML Table - jQuery

I am just trying to get the percentage in html table in second row
Database Consensus.
So just tried that jQuery
var TableData = new Array();
jQuery('#myTable tr').each(function(row, tr){
TableData[row]={
"1st" : jQuery.trim(jQuery(tr).find('td:eq(2)').text())
, "2nd" :jQuery.trim(jQuery(tr).find('td:eq(3)').text())
, "3rd" : jQuery.trim(jQuery(tr).find('td:eq(4)').text())
, "4th" : jQuery.trim(jQuery(tr).find('td:eq(5)').text())
}
});
TableData.shift();
TableData.sort();
var First = [];
var Second = [];
var Third = [];
var Fourth = [];
for (var i = 0; i < TableData.length - 1; i++) {
if (TableData[i + 1]['1st'] == TableData[i]['1st']) {
First.push(TableData[i]['1st']);
}
if (TableData[i + 1]['2nd'] == TableData[i]['2nd']) {
Second.push(TableData[i]['2nd']);
}
if (TableData[i + 1]['3rd'] == TableData[i]['3rd']) {
Third.push(TableData[i]['3rd']);
}
if (TableData[i + 1]['4th'] == TableData[i]['4th']) {
Fourth.push(TableData[i]['4th']);
}
}
var first = First.length;
var total = TableData.length;
var percent = first/total * 100;
jQuery('.1st').text(First[0] + "\n" + "(" + percent + "%"+")");
var second = Second.length;
var percent = second/total * 100;
jQuery('.2nd').text(Second[0] + "\n" + "(" + percent + "%"+")");
var third = Third.length;
var percent = third/total * 100;
jQuery('.3rd').text(Third[0] + "\n" + "(" + percent + "%"+")");
var fourth = Fourth.length;
var percent = fourth/total * 100;
jQuery('.4th').text(Fourth[0] + "\n" + "(" + percent + "%"+")");
But i am not getting right percentage :(
I am not have very good experience in jQuery but tried Here is demo
http://jsfiddle.net/bcHsy/33/
I am not much of a Fiddler, so I'm not sure that the link will even work, but I think that this might work:
Fiddle Link
I mostly changed the HTML in one section:
<tr>
<td align="center" valign="middle" bgcolor="#ffffff">
<p align="left">
<span style="color: #d89b5a;"><strong>Database Consensus</strong></span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;">-------</span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;" class="1st">L.Tunsil</span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;" class="2nd">C.Wentz</span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;" class="3rd">J.Ramsey</span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;" class="4th">M.Jack</span>
</p>
</td>
</tr>
and some of the JS:
var TableData = new Array();
var Picks = new Array();
jQuery('#myTable tr').each(function(row, tr){
if (row == 1) {
Picks[0] = jQuery.trim(jQuery(tr).find('td:eq(2)').text());
Picks[1] = jQuery.trim(jQuery(tr).find('td:eq(3)').text());
Picks[2] = jQuery.trim(jQuery(tr).find('td:eq(4)').text());
Picks[3] = jQuery.trim(jQuery(tr).find('td:eq(5)').text());
}
TableData[row]={
"1st" : jQuery.trim(jQuery(tr).find('td:eq(2)').text())
, "2nd" :jQuery.trim(jQuery(tr).find('td:eq(3)').text())
, "3rd" : jQuery.trim(jQuery(tr).find('td:eq(4)').text())
, "4th" : jQuery.trim(jQuery(tr).find('td:eq(5)').text())
}
});
TableData.shift();
TableData.shift();
TableData.sort();
var First = [];
var Second = [];
var Third = [];
var Fourth = [];
for (var i = 0; i < TableData.length; i++) {
if (TableData[i]['1st'] == Picks[0]) {
First.push(TableData[i]['1st']);
}
if (TableData[i]['2nd'] == Picks[1]) {
Second.push(TableData[i]['2nd']);
}
if (TableData[i]['3rd'] == Picks[2]) {
Third.push(TableData[i]['3rd']);
}
if (TableData[i]['4th'] == Picks[3]) {
Fourth.push(TableData[i]['4th']);
}
}
var first = First.length;
var total = TableData.length;
var percent = first/total * 100;
jQuery('.1st').text(First[0] + "\n" + "(" + percent + "%"+")");
var second = Second.length;
var percent = second/total * 100;
jQuery('.2nd').text(Second[0] + "\n" + "(" + percent + "%"+")");
var third = Third.length;
var percent = third/total * 100;
jQuery('.3rd').text(Third[0] + "\n" + "(" + percent + "%"+")");
var fourth = Fourth.length;
var percent = fourth/total * 100;
jQuery('.4th').text(Fourth[0] + "\n" + "(" + percent + "%"+")");

Add Javascript and HTML form entries to database

How can I add this javascript/html form to the database? I know only how to connect html/php with SQL...
here is the code that will allow the user to pick up the dates but its connected with javascript .. I need a way to save it into the database ..
HTML
<div id="hourForm">
<div id="Sunday" class="day"></div>
<div id="Monday" class="day"></div>
<div id="Tuesday" class="day"></div>
<div id="Wednesday" class="day"></div>
<div id="Thursday" class="day"></div>
<div id="Friday" class="day"></div>
<div id="Saturday" class="day"></div>
</div>
javascript
$('.day').each(function() {
var day = $(this).attr('id');
$(this).append('<div id="label">' + day + ': </div>');
$(this).append('<select name="' + day + 'FromH" class="hour from"></select>');
$(this).append('<select name="' + day + 'FromM" class="min from"></select>');
$(this).append('<select name="' + day + 'FromAP" class="ampm from"></select>');
$(this).append(' to <select name="' + day + 'ToH" class="hour to"></select>');
$(this).append('<select name="' + day + 'ToM" class="min to"></select>');
$(this).append('<select name="' + day + 'ToAP" class="ampm to"></select>');
$(this).append(' <input type="checkbox" name="closed" value="closed" class="closed"><span>Closed</span>');
});
$('.hour').each(function() {
for (var h = 1; h < 13; h++) {
$(this).append('<option value="' + h + '">' + h + '</option>');
}
$(this).filter('.from').val('9');
$(this).filter('.to').val('5');
});
$('.min').each(function() {
var min = [':00', ':15', ':30', ':45'];
for (var m = 0; m < min.length; m++) {
$(this).append('<option value="' + min[m] + '">' + min[m] + '</option>');
}
$(this).val(':00');
});
$('.ampm').each(function() {
$(this).append('<option value="AM">AM</option>');
$(this).append('<option value="PM">PM</option>');
$(this).filter('.from').val('AM');
$(this).filter('.to').val('PM');
});
$('input').change( function() {
if($(this).filter(':checked').val() == "closed") {
$(this).siblings('select').attr('disabled', true);
} else {
$(this).siblings('select').attr('disabled', false);
}
});
$('#Saturday .closed, #Sunday .closed').val(["closed"]).siblings('select').attr('disabled', true);
please give me a hint or a tutorial if you can't help..
You'll need to learn how to use AJAX, this will allow you to send and receive data from the database, usually you'll have some PHP which will display JSON and your AJAX will request this from the PHP page.
http://www.formget.com/submit-form-using-ajax-php-and-jquery/
Your AJAX will look something like this:
$.ajax({
method: "GET",
url: "test.php",
data: { param1 : "Bob", param2 : "Larry" },
dataType: "script"
});
This will call your PHP file "test" and pass in parameters param1 and param2

Beginner JavaScript help(functions)

I'm having some trouble copying the scripts and HTML from the calender on refdesk.com. I need put the JavaScript on a different style sheet and use those functions to recreate the calender on a HTML page. Here is what I have so far, any tips will help. This is a homework assignment so I'm not looking for the answers.
JavaScript -
function initialize()
{
buildCal();
updateCalender();
}
var themonths = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
var todaydate = new Date();
var curmonth = todaydate.getMonth() + 1; //get current month (1-12)
var curyear = todaydate.getFullYear(); //get current year
function buildCal(month, year, cM, cH, cDW, cD, border)
{
var mn = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var dim = [31,0,31,30,31,30,31,31,30,31,30,31];
var firstDaySelectedMonth = new Date(year, month - 1, 1); //DD replaced line to fix date bug when current day is 31st
firstDaySelectedMonth.od=firstDaySelectedMonth.getDay() + 1; //DD replaced line to fix date bug when current day is 31st
var todaydate = new Date(); //DD added
var scanfortoday = (year == todaydate.getFullYear() && month == todaydate.getMonth() + 1) ? todaydate.getDate() : 0; //DD added
dim[1] = (((firstDaySelectedMonth.getFullYear() % 100 != 0) && (firstDaySelectedMonth.getFullYear() %4 == 0)) || (firstDaySelectedMonth.getFullYear() % 400 == 0)) ? 29 : 28;
var t = '<div class="' + cM + '"><table class="' + cM + '" cols="7" cellpadding="0" border="' + brdr + '" cellspacing="0"><tr align="center">';
t += '<td colspan="7" align="center" class="' + cH + '">' + mn[month - 1] + ' - ' + year + '</td></tr><tr align="center">';
for (s = 0; s < 7; s++)
{
t += '<td class="' + cDW + '">' + "SMTWTFS".substr(s,1) + '</td>';
t += '</tr><tr align="center">';
}
for(i = 1;i <= 42; i++)
{
var x = ((i-firstDaySelectedMonth.od >= 0) && (i-firstDaySelectedMonth.od < dim[month -1 ])) ? i-firstDaySelectedMonth.od + 1 : ' ';
if (x == scanfortoday) //DD added
{
x = '<span id="today">' + x + '</span>'; //DD added
t += '<td class="' + cD + '">' + x +'</td>';
}
if(((i) % 7 == 0) && (i < 36))
{
t += '</tr><tr align="center">';
}
}
return t += '</tr></table></div>';
}
// update calender function
function updateCalendar(theSelection)
{
var themonth = parseInt(theSelection[theSelection.selectedIndex].value) + 1;
var calendarstr = buildCal(themonth, curyear, "main", "month", "daysofweek", "days", 0);
if (document.getElementById)
{
document.getElementById("calendarspace").innerHTML = calendarstr;
}
document.write('<option value="'+(curmonth - 1) + '" selected="yes">Current Month</option>');
for (i = 0; i < 12; i++) //display option for 12 months of the year
{
document.write('<option value="' + i + '">' + themonths[i] + ' ' + curyear + '</option>');
}
}
HTML -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="refdesk.css">
<script src="refdesk.js"></script>
</head>
<body onload="initialize()">
<!-- CALENDAR START -->
<form>
<div id="choicespace">
<p>(This will be replaced with JavaScript-generated HTML)</p>
<select onchange="updatecalendar(this.options)">
<script>
updatecalendar(theselection);
</script>
<option value="1" selected="yes">Current Month</option><option value="0">January 2013</option><option value="1">February 2013</option><option value="2">March 2013</option><option value="3">April 2013</option><option value="4">May 2013</option><option value="5">June 2013</option><option value="6">July 2013</option><option value="7">August 2013</option><option value="8">September 2013</option><option value="9">October 2013</option><option value="10">November 2013</option><option value="11">December 2013</option>
</select>
</div>
<div id="calendarspace">
<p>(This will be replaced with JavaScript-generated HTML)</p>
</div>
</form>
</body>
</html>
First, try to figure how your javascript code really work. Take a look on calendar in javascript as a simple example.
Personally I would indent more to keep things organized. Another thing I would do is just make shorter variables because sometimes i find myself coding wrong because of my huge variable names.

Categories

Resources