In my code behind, I have –
tbWhatIfBeginDate.Attributes.Add("onchange", "checkDates(" + tbWhatIfBeginDate.ClientID + ", " + tbWhatIfEndDate.ClientID + ")");
tbWhatIfEndDate.Attributes.Add("onchange", "checkDates(" + tbWhatIfBeginDate.ClientID + ", " + tbWhatIfEndDate.ClientID + ")");
and here is my javascript function –
function checkDates(BeginDateId, EndDateId) {
if (BeginDateId.value > EndDateId.value) {
var beginDt = new Date(BeginDateId.value);
var endDt = new Date(EndDateId.value);
var newDt = new Date(endDt.getTime() - (24 * 60 * 60 * 1000));
var y = newDt.getFullYear(),
m = newDt.getMonth() + 1, // january is month 0 in javascript
d = newDt.getDate();
BeginDateId.value = [pad(m), pad(d), y].join("/");
}
}
when I run through Visual Studio 2010, it works.
When I deploy to my test server, I get an error message. “Object expected – Line:176,Char:1”
line 176 is –
input name=”ctl00$cpMain$tbWhatIfBeginDate” type=”text” value=”8/1/2012″ id=”ctl00_cpMain_tbWhatIfBeginDate” onchange=”checkDates (ctl00_cpMain_tbWhatIfBeginDate, ctl00_cpMain_tbWhatIfEndDate)” style=”width:70px;”
I don’t see an error.
Ideas?
You are passing the id of HTML elements to the function, which are strings, but you pass it without quotes, as if it were a defined variable. In the
onClickscope, there is no such variablectl00_cpMain_tbWhatIfBeginDatealready defined, so you’re getting a javascript error. That’s expected — you’ve not declared such a variable.In your function, you then immediately try to treat these arguments as objects, but again, you passed in
undefinedsince the variables with the specified names didn’t exist. Nor should they! When you’re attempting to reference a DOM node by id, you have to usegetElementByIdfrom thedocumentobject to “fetch” the related object. The ids, then, are just string.As such, you should pass those strings wrapped in quotes. To do this, you need to modify the two lines where you add the events:
That way, the string ids get passed to your function. Then, your function needs to be modified to get the DOM objects based on the passed ids:
Documentation
document.getElementById– https://developer.mozilla.org/en/DOM/document.getElementById