How to check when input value is changed? - javascript

How can i check when a value on input is changed.
I have a calendar and when i click on calendar it changes the value on input , but when im trying to see if it has changed its not working. i have tried AddEventListener, also jquery on change, also i sent a function on change to call it but none of them is working.
<input type="text" id="date" class="date" onchange="changed()" name="" >
function changed(){
alert("hello world");
}
Main js file for creating the calendar :
This function creates the calendar on my php file .
And then when on click it gets the value on the input with id #date
But When im trying to see if value has changed it is not working .
// Initialize the calendar by appending the HTML dates
function init_calendar(date) {
$(".tbody").empty();
$(".events-container").empty();
var calendar_days = $(".tbody");
var month = date.getMonth();
var year = date.getFullYear();
var day_count = days_in_month(month, year);
var row = $("<tr class='table-row'></tr>");
var today = date.getDate();
// Set date to 1 to find the first day of the month
date.setDate(1);
var first_day = date.getDay();
// 35+firstDay is the number of date elements to be added to the dates table
// 35 is from (7 days in a week) * (up to 5 rows of dates in a month)
for(var i=0; i<35+first_day; i++) {
// Since some of the elements will be blank,
// need to calculate actual date from index
var day = i-first_day+1;
// If it is a sunday, make a new row
if(i%7===0) {
calendar_days.append(row);
row = $("<tr class='table-row'></tr>");
}
// if current index isn't a day in this month, make it blank
if(i < first_day || day > day_count) {
var curr_date = $("<td class='table-date nil'>"+"</td>");
row.append(curr_date);
}
else {
var monthplusone = months[month];
var curr_date = $("<td class='table-date' id='"+day+"-"+monthplusone+"-"+year+"'>"+day+"</td>");
var events = check_events(day, month+1, year);
if(today===day && $(".active-date").length===0) {
curr_date.addClass("active-date");
let x = document.getElementById('date').value=day+"-"+monthplusone+"-"+year;
$('.table-date').ready(function () {
x.value;
});
show_events(events, months[month], day);
}
// If this date has any events, style it with .event-date
if(events.length!==0) {
curr_date.addClass("event-date");
}
// Set onClick handler for clicking a date
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
curr_date.click({events: events, month: months[month], day:day}, date_click);
row.append(curr_date);
}
}
// Append the last row and set the current year
calendar_days.append(row);
$(".year").text(year);
}

Notice that change is actually triggered when the input is not focused anymore.
document.getElementById("date").addEventListener("change", function () {
alert("hello world");
});
<input type="text" id="date" class="date" name="">

This works. Not sure where you're running into an issue.
function changed(){
console.log("hello world");
}
<input type="text" id="date" class="date" onchange="changed()" name="" >
EDIT: Shortened version of init_calender() for others interested in answering:
function setDate() {
document.getElementById("date").value = '19-Dec-2021'
}

I basically agree with #Spankied in that you should try and shorten your code to the point where you are having the issue. However, after looking at your code it seems to me that you want the following function
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
to not only change the value in your #date input but also trigger its change event-handler function. You can do that by changing it to something like
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
$("#date" ).change();
});
jQuery.change() without any arguments will trigger a predefined "change"-event on the DOM-object that is selected by the jQuery-object.

You can use js to do that:
let x = $(...) //select the input box
let val = x.value;
function repeat() {
if (val !== x.value) {
change()
}
}
setInterval(repeat, 100)
This checks if the result is the same.

This might make your site a bit slow and it might look odd but this will work in just every case
<script>
let Oldvalue = $('.date')[0].val();
setInterval(() => {
let currentValue = $('.data')[0].val()
if (Oldvalue != currentValue){
//do whatever but in end write this
Oldvalue = currentValue;
}
}, 10);
</script>

Related

Stuck on incrementing date in JavaScript

I am trying to create a page that grabs a set of PDFs sorted by date. I can't seem to increment the date correctly. I'm not sure what's going wrong here. I rewrote the code twice now. No luck.
The current issue is that the set variables for the date do not keep the value of the date as a whole. IE incrementing from 12, 31, 2018, or in the case of the URL format 20181231, should result urlIncremented=20190101. January 1st, 2019, but the result of my code is urlIncremented=20181232.
The end result of one loop if set to June 8th 2018, should be: url20180608
I've searched for advice on here, and found a JS file called Date.JS; I've imported it and it was looking promising but just consoles out a part of its code, namely:
function () {
if (this._isSecond) {
this._isSecond=false;
return this;
}
if (this._same) {
this._same=this._is=false;
var o1=this.toObject(),
o2=(arguments[0] || new Date()).toObject(),
v="",
k=j.toLowerCase();
for (var m=(px.length-1); m>-1; m--) {
v=px[m].toLowerCase();
if (o1[v]!=o2[v]) {
return false;
}
if (k==v) {
break;
}
}
return true;
}
if (j.substring(j.length-1)!="s") {
j+="s";
}
return this["add"+j](this._orient);
}
Just a heads up I do not yet know jQuery, I was just playing with it to see if it would help..
Here is my actual code.
let url = "blank",
firstRun = true;
/*
function setDateByIncrement(currentSetDate){
let newDate,
currentDate = new Date(),
day = currentDate.getDate()+1,
month = currentDate.getMonth() + 1,
year = currentDate.getFullYear();
console.log(newDate);
newDate = (year+month+day);
console.log(newDate);
return newDate;
}
*/
// use on First run to set the url and date.
//3
function setURL(){
let urlIncremented = url + dateIncrementMethod();
return urlIncremented;
}
// will open x number of new windows containing URL
//2
function grabOpenPDF(maxNumberDays){
let urlSet = setURL();
//Set the variable for max days.
for(let x = 0; x < maxNumberDays; x++){
//window.open(urlSet);
console.log("It works: " + x);
urlSet = setURL();
}
}
/* TODO Add automatic download for MASS print.
function downloadPDF(){
}
*/
//Starts the task.
//1
function start(load){
console.log("Current Address: " + url);
if(load === 1){
console.log("Event load active. ");
let maxDay = document.querySelector('#maxNumberDays').value;;
grabOpenPDF(maxDay);
}else{
console.log("Event load skip. ")
let maxDay = document.getElementById('maxNumberDays').value;
}
}
//4
function dateIncrementMethod(current){
let dateIncrement;
if(firstRun=== true){
var today = new Date($('#date-input').val());
console.log("FirstRun check in 4. ")
}
firstRun = false;
var tomorrow = today.add(1).day;
console.log(tomorrow);
return tomorrow;
}
/* Possibly Deprecated
//let dateIncrement;
let date = new Date($('#date-input').val());
console.log(date);
day = date.getDate() + 1;
if(firstRun === true){
month = date.getMonth() + 1;
year = date.getFullYear();
//dateIncrement = (parseToAPI(year, month, day));
firstRun = false;
parseToAPI(year, month, day);
}else{
day = date.getDate()+1;
parseToAPI(year, month, day);
}
}
*/
function parseToAPI(year, month, day){
let apiDate;
console.log("Entered parse");
this.day = day;
this.month = month;
let d = this.day.toString(),
m = this.month.toString();
if(d.length === 1){
console.log("Entered First IF");
this.day = ('0') + day;
//console.log(day);
}
if(m.length === 1){
console.log("Entered Second IF")
this.month = ('0') + month;
}
apiDate = (year + "" + "" + month + "" + day);
console.log(apiDate);
return apiDate;
}
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="date" id="date-input" required />
<input type="maxNumberDays" id="maxNumberDays" max="31" required />
<button id="startPDFApp" onClick="start()">Print PDFs</button>
<button id="startPDFApp" onClick="start(1)">Load PDFs</button>
<div id="info"></div>
</body>
</html>
While I haven't invested enough time trying to understand what you're really trying to do, it seems like there's a lot of unnecessary code. I'll leave it to you to decipher what you need.
I can only express that the below code is in an in-between state. It includes a number of changes, most of which I'll point out, but I didn't want to change it too drastically that it all looked foreign. So even the code below has much to be improved on.
Significant changes include:
Because your URL is increasing by one, you may benefit by using a function generator. Inside it increases the date by calling setDate on itself using it's own date + 1. It also uses a string function, padStart, to ensure months and days are always two-digit.
Getting rid of firstRun variable as it is no longer needed
Inside your grabOpenPDF, all you need to do is get the next value returned by the URL generator function
let URL_GEN = UrlGenerator('blank'),
URL = URL_GEN.next().value;
//Starts the task.
//1
function start(load) {
let startDate = new Date(document.querySelector('#date-input').value)
// overwrite global with values
URL_GEN = UrlGenerator('blank', startDate)
URL = URL_GEN.next().value
console.log("Current Address: " + URL);
if (load === 1) {
console.log("Event load active.");
let maxDay = document.querySelector('#maxNumberDays').value;
grabOpenPDF(maxDay);
} else {
console.log("Event load skip.")
let maxDay = document.getElementById('maxNumberDays').value;
}
}
/* URL generator */
function* UrlGenerator(url, dt=new Date()) {
while (true){
yield url + dt.getFullYear() + (''+(dt.getMonth()+1)).padStart(2,'0') + (''+dt.getDate()).padStart(2,'0');
// increase day for next iteration
dt.setDate(dt.getDate()+1);
}
}
// will open x number of new windows containing URL
function grabOpenPDF(maxNumberDays) {
//Set the variable for max days.
for (let i=0; i < maxNumberDays; i++) {
console.log("It works: " + i, URL);
URL = URL_GEN.next().value;
}
}
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<input type="date" id="date-input" value="12/29/2018" required />
<input type="maxNumberDays" id="maxNumberDays" value="5" max="31" required />
<button id="startPDFApp" onClick="start()">Print PDFs</button>
<button id="startPDFApp" onClick="start(1)">Load PDFs</button>
<div id="info"></div>
This can be further improved by better management of your globals, more straightforward code (more simply laid out), and perhaps better naming conventions. Also, it's generally a no-no to be putting event handlers directly in the HTML these days, you could bind those event dynamically via JavaScript.
I can't seem to increment the date correctly.
If you have a dates like "20181231" with a format YYYYMMDD, you must parse it to the date parts, increment the day, then format it back to an appropriate string. A date manipulation library can help, or you can write a custom function.
You can do it without generating a Date, but it's a bit more code and logic.
E.g.
// Accept date string in format YYYYMMDD
// and return next date in same format
function getNextDate(s) {
let z = n => ('0'+n).slice(-2);
let [y, m, d] = s.match(/^\d{4}|\d{2}/g);
let date = new Date(y, m-1, d);
date.setDate(date.getDate() + 1);
return date.getFullYear() + z(date.getMonth()+1) + z(date.getDate());
}
['20181230','20181231','20190101'].forEach(
s => console.log(`${s} => ${getNextDate(s)}`)
);
You can also use a library like moment.js:
function getNextDate(s) {
return moment(s, 'YYYYMMDD')
.add(1, 'day')
.format('YYYYMMDD');
}
['20181230','20181231','20190101'].forEach(
s => console.log(`${s} => ${getNextDate(s)}`)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
If you are using moment.js for other things, include it. But if this is the only date stuff you need it for, it's a bit of overhead you don't need.
A lot of your code is a little unclear and the logic is not obvious, in regards to what should happen. Here is what I could gleam:
User should enter a Date, that is required
When user click Load PDF, a list of dates should be calculated
Assuming today until selected date, with a max of 31 days in the future
The script checks if a PDF exists for each of the days in the list
I suspect you were just looking for a way to generate a pattern for the days. I may have more here than you need.
$(function() {
function grabOpenPDF(end) {
var current = new Date();
end.setDate(end.getDate() + 1);
var urls = [];
while (current < end) {
urls.push({
name: $.datepicker.formatDate("yymmdd", current),
url: "https://example.com/getpdf.php?date=" + $.datepicker.formatDate("yymmdd", current),
hit: null
});
current.setDate(current.getDate() + 1);
};
console.log(urls);
$.each(urls, function(k, v) {
$.ajax({
url: v.url,
success: function(data) {
v.hit = true;
$("#info").append("<div>" + (k + 1) + ". " + v.url + ", hit: " + v.hit.toString() + "</div>");
},
error: function(data) {
v.hit = false;
$("#info").append("<div>" + (k + 1) + ". " + v.url + ", hit: " + v.hit.toString() + "</div>");
}
});
});
}
var dtInp = $("#date-input").datepicker({
dateFormat: "mm/dd/yy",
maxDate: "+31d",
minDate: new Date()
});
$(".today").html($.datepicker.formatDate("mm/dd/yy", new Date()));
$("#printPDF").click();
$("#startPDF").click(function(e) {
e.preventDefault();
$("#info").html("");
if ($("#date-input").val() === "") {
$("#date-input").focus();
return false;
}
console.log("Event load active.");
grabOpenPDF(dtInp.datepicker("getDate"));
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<div class="ui-widget ui-widget-content" style="padding: 7px;">
<p>From <span class="today">Today</span> until <input type="text" id="date-input" placeholder="mm/dd/yy" required style="border: 0; width: 8em; border-radius: 0; border-bottom: 1px solid #eee;" /></p>
<button id="printPDF">Print PDFs</button>
<button id="startPDF">Load PDFs</button>
<div id="info"></div>
</div>
As I mentioned, you can use jQuery and jQuery UI to help you out. Take a look: http://api.jqueryui.com/datepicker/
When the user clicks on the field, they can select a date between today and 31 days into the future. they can then click the "Load PDF" button and it will grab the PDFs by iterating each day and performing some action.
Good reference for incrementing the date: Incrementing a date in JavaScript
Personally, I would push this off to the server instead of doing this in the browser. Assuming there is a DB of PDFs, it would be faster to send a start and end date to the server and have it perform a SELECT query and return the results. You're sending two bits of data to the server and getting a list of results versus hammering around for PDFs hoping to find your nail. using the above example, you could set the option, minDate: "-6m" and just limit the range the user might select a start and end date.
Hope this helps. Feel free to comment and ask for more clarity if needed.

Can i call another function inside the GetElement in Javascript

I am trying to call another function inside the getElement but it is not working everything when i change my selection. When i select Car, in the textbox my varxumb should populate. Any idea...
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option><option>Force</option><option>Angle</option><option>Area</option></select></td>';
function fillgap() {
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
if (forcxlist == "Force") {
document.getElementById("result1").value = xnumb;
}
}
I don't know how this "Force" value is coming to check.
you can try these solutions.
if (forcxlist == "Force")
instead use
var forcxlistText = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistText == "Force")
or use value technique
<div id ="mycall1">
</div>
<div id ="result1">
</div>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx" onchange="fillgap(this.value)"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
function fillgap(value){
var xnumb = 20;
if (value == "2"){
document.getElementById("result1").innerHTML = xnumb;
}
}
</script>
or use
<div id ="mycall1">
</div>
<input type="text" id="result1" value=""/>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
document.getElementById("forcx").onchange = function (){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].value;
if (forcxlistValue == "2"){
document.getElementById("result1").value = xnumb;
}
}
</script>
The forcxlist variable is an element object, returned by the document.getElementById method. Afterwards, you are checking if this element object is equal to "Force", which is a string (meaning the contents of your if block will never be executed). Did you mean to check if the contents of that object are equal to Force?
Instead of
if (forcxlist == "Force"){
use
if (forcxlist.innerHTML == "Force"){
I hope this helps!
Can't use innerHTML so i changed it to .value
document.getElementById("result1").value = xnumb;
There are a couple issues here.
First, you are expecting forcxlist to be a string, not an element, so you need to use .value to get the selected value of the dropdown.
Second, you should do your comparison with === not ==, as this ensures type equality as well, and is best practice.
I would also recommend building your select using HTML elements. It keeps things cleaner, is more readable, and is easier to maintain.
Since you are using the same id for the select, you would have to change the selector in your fillgap handler to var forcxlist = e.target.value;, this way the event will fire based on only the select that you are interacting with, regardless of how many rows you have in the table.
Updated code is below, and an updated working fiddle here. As per your comment about adding additional rows, the fiddle has this working as well.
<input type="button" value="Add Row" onclick="addDropDown()">
<table id="mycall1"></table>
<script>
function addDropDown() {
var tbl = document.getElementById("mycall1");
var newRow = tbl.insertRow(-1);
var newCell = newRow.insertCell(0);
newCell.appendChild(createDropDown("forcx", fillgap));
}
function createDropDown(id, onchange) {
var dd = document.createElement('select');
dd.id = id;
dd.onchange = onchange;
createOption("Select", dd);
createOption("Force", dd);
createOption("Angle", dd);
createOption("Area", dd);
return dd;
}
function createOption(text, dropdown) {
var opt = document.createElement("option");
opt.text = text;
dropdown.add(opt);
}
function fillgap() {
var xnumb = 20;
var forcxlist = e.target.value;
if (forcxlist === "Force") {
document.getElementById("result1").value = xnumb;
}
}
</script>
<input type="text" id="result1">

JQuery Values are not changing

#Html.ActionLink("Search", "GetDateWiseGuestReport", "Reports", new { StartDate = "sss",EndDate="eee" }, new { #id = "btnDateWiseGuestSearch", #class = "btn btn-red" })
$("#btnDateWiseGuestSearch").bind('click', function () {
//Get the id of the selected item in dropdown
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
this.href = this.href.replace("sss", StartDate);
this.href = this.href.replace("eee", EndDate);
});
Okay i am using above code to change the Action-link URL at run time.Everything is running smoothly. but i have a strange issue i.e. when i click the button 1st time its gets the values from text boxes and change accordingly, but when i press button again its doesn't get new values from text boxes rather its somehow using OLD VALUES that i inputted 1st time!
Because after the firs click you are replacing the sss and eee from the href so there after is no sss or eee in the href. So nothing is replaced after the first click
So a possible solution is to store the original href value somewhere else then use that for replacing the content. In the below solution the data api is used to store the original value
var $btn = $("#btnDateWiseGuestSearch");
$btn.data('href', $btn.attr('href'))
$btn.bind('click', function () {
//Get the id of the selected item in dropdown
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
var href = $(this).data('href');
this.href = href.replace("sss", StartDate).replace("eee", EndDate);
});
Basically in your jQuery code you are create a new link by replacing sss and eee however once you have replaced them that is it, you won't find them again
this.href = this.href.replace("sss", StartDate); // sss no longer exists after this
this.href = this.href.replace("eee", EndDate); // sss no longer exists after this
What you will need to do is store the original href value before you modify it and then reference that when you want to update the link
$("#btnDateWiseGuestSearch").bind('click', function () {
var $this = $(this);
var originalhref = $this.data("href");
if(!originalhref){
this.data("href", this.href);
}
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
this.href = originalhref.replace("sss", StartDate).replace("eee", EndDate);
});

Open overlay if today is current day

I'm in the process of making a Christmas calendar, and I have an overlay which should open if the date is ex 1.12.13, otherwise it should alert the amount of days until it's available. I've tried a lot of different things but can't get it to work.
Here is what should be displayed if date is something:
<!-- overlayed element, which is styled with external stylesheet -->
<div class="apple_overlay black" id="photo1">
<img src="images/onecom.png" alt="onecom" width="496" height="496" />
<div class="details">
<h2>December 1st</h2>
<p>
Some script that does something
</p>
</div>
</div>
What I have tried
function dooropen(door) {
today=new Date();
daynow=today.getDate();
monthnow=today.getMonth();
if (monthnow!=11 && monthnow!=0) {
alert("This feature opens in December. Please come back then.");
return false;
}
if (daynow==door-1) {
alert("Come back tomorrow to see what's behind that door!");
return false;
}
if (door>daynow) {
alert("You\'ll have to wait "+(door-daynow)+" days before that door's available!");
return false;
}
}
This may work, as i can see you may have some different div for each day of the month since you are using numeric id id="photo1">, so you can try to get the dates :
var today = new Date();
var dd = today.getDate() + 1;
var mm = today.getMonth() + 1;
after that get the main parent of all divs and put it in a jquery object:
var $number_of_objects = $("#parent_div img");
once you have all those you need to put them inside a for loop to count them and match to later exit the function:
for (var i = 1; i < $number_of_objects.length; i++) {
console.log("value of i " + i);
if(i == dd){
console.log(' break');
break;
}
$("#apple img[rel='#photo"+i+"']").overlay({
effect: 'apple'
});
}
it should give you a good start point to improve it and add more feature to the script :)
happy coding
<script>
var date = new Date(),
year = date.getYear(),
month = date.getMonth()+1,
day = date.getDate();
if(day == 13){ // today is 13
code
}else{
code
}
</script>
Just show the element you want at the end of your method..
$('#photo1').show();

OnClick event, show pop-up or focus on textbox to add comment

What I'm trying to achieve is the following. I'm (still) working on a timesheet, and the user has to be able to add a comment.
Comment [ .................. ] for D2
TaskID - Taskname - D1 - D2 - D3 ...
1 Hello 5 3 2
2 Bai 4 2 1
3 I'm back 3 4 3
When a user clicks on a specific textbox, where he has to fill in the hours, an additional textbox should get the comment value of that specific box. When he clicks on another textbox, it should get that value etc, etc.
I don't really know where to look for, or how I could do it best. Any ideas? Javascript? JQuery? I'm currently working with Spring MVC, so it should get the value and add it to a specific modelattribute so it can be submitted.
Another possibility is some kind of pop-up, which appears when you click on an icon next to the textbox...
I used Javascript to realize this.
Once you enter a certain field, I call a function to fill the commentary with a new classname:
<input type="text" onfocus='addComment(id, index, taskid)' />
Function:
function addComment(classname, commValue, taskid){
var comm = document.getElementById('comment');
var comment = document.getElementById(taskid + classname);
comm.className = taskid + classname;
comm.value = comment.value;
}
This will fill the textbox with the value from the latest focused textbox. It will also set the classname using the provided one.
To save the commentary value, I use jQuery Ajax:
function saveComment(){
var comment = document.getElementById('comment');
var classn = comment.className;
var firstday = document.getElementById('firstweek').value;
var commentval = comment.value;
var windex = comment.className.indexOf("w");
var day = comment.className.substring(windex+1, windex+2);
var taskid = comment.className.substring(0, windex);
var pid = document.getElementById('projectid').value;
if (classn != ""){
var commentSaved = document.getElementById(taskid+comment.className.substring(windex, windex+2));
commentSaved.value = commentval;
$.post("savecomm.html", { day: day, comment: commentval, taskid: taskid, firstday: firstday, pid: pid }, function(data) {
alert("callback");
});
} else {
alert("No entries selected");
}
}

Categories

Resources