JavaScript error (null or not an object) .Only in IE - javascript

var rows = [];
for (var id in topics) {
var topic = g_favoriteTopics[topics[id].id];
var $row = $("table#Favorites tr#topicTemplate").clone();
alert(topic.title);
$row.find("td.txtCol a").html(topic.title);
var href = commonVariables.formAction +
"?PARTITION_ID=" + commonVariables.partitionId +
"&CONFIGURATION=" + commonVariables.configurationId +
"&CMD=DFAQ&DFAQ_TOPIC_ID=" + topic.id +
"&DFAQ_TOPIC_TYPE=" + topic.type;
$row.find("td.txtCol a").attr("href", href);
$row.find("td.imgCol input").attr("topicId", topic.id);
rows.push(topic.title.toLowerCase() + "<<<>>><tr topicId=" + topic.id + ">" + $row.html() + "</tr>");
}
The alert window shows the proper topic title (name of the topic).However Iam presented with a Javascript error (title is null or not an object),after the alert.
It runs fine in FF and chrome

Related

jQuery to emulate iPhone password input changes textbox to disabled in a Visual Studio web application

I am working on a web application in Visual Studio using visual basic and master pages. I have 10 textbox fields on a child page where I would like to emulate the iPhone password entry (ie. show the character entered for a short period of time then change that character to a bullet). This is the definition of one of the text box controls:
<asp:TextBox ID="txtMID01" runat="server" Width="200" MaxLength="9"></asp:TextBox>
At the bottom of the page where the above control is defined, I have the following:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="lib/jQuery.dPassword.js"></script>
<script type="text/javascript">
$(function () {
var textbox01 = $("[id$=txtMID01]");
alert(textbox01.attr("id"));
$("[id$=txtMID01]").dPassword()
});
</script>
When the page loads, the alert displays MainContent_txtMID01 which is the ID of the control preceeded with the name of the content place holder.
The following is the contents of lib/jQuery.dPassword.js (which I found on the internet):
(function ($) {
$.fn.dPassword = function (options) {
var defaults = {
interval: 200,
duration: 3000,
replacement: '%u25CF',
// prefix: 'password_',
prefix: 'MainContent_',
debug: false
}
var opts = $.extend(defaults, options);
var checker = new Array();
var timer = new Array();
$(this).each(function () {
if (opts.debug) console.log('init [' + $(this).attr('id') + ']');
// get original password tag values
var name = $(this).attr('name');
var id = $(this).attr('id');
var cssclass = $(this).attr('class');
var style = $(this).attr('style');
var size = $(this).attr('size');
var maxlength = $(this).attr('maxlength');
var disabled = $(this).attr('disabled');
var tabindex = $(this).attr('tabindex');
var accesskey = $(this).attr('accesskey');
var value = $(this).attr('value');
// set timers
checker.push(id);
timer.push(id);
// hide field
$(this).hide();
// add debug span
if (opts.debug) {
$(this).after('<span id="debug_' + opts.prefix + name + '" style="color: #f00;"></span>');
}
// add new text field
$(this).after(' <input name="' + (opts.prefix + name) + '" ' +
'id="' + (opts.prefix + id) + '" ' +
'type="text" ' +
'value="' + value + '" ' +
(cssclass != '' ? 'class="' + cssclass + '"' : '') +
(style != '' ? 'style="' + style + '"' : '') +
(size != '' ? 'size="' + size + '"' : '') +
(maxlength != -1 ? 'maxlength="' + maxlength + '"' : '') +
// (disabled != '' ? 'disabled="' + disabled + '"' : '') +
(tabindex != '' ? 'tabindex="' + tabindex + '"' : '') +
(accesskey != undefined ? 'accesskey="' + accesskey + '"' : '') +
'autocomplete="off" />');
// change label
$('label[for=' + id + ']').attr('for', opts.prefix + id);
// disable tabindex
$(this).attr('tabindex', '');
// disable accesskey
$(this).attr('accesskey', '');
// bind event
$('#' + opts.prefix + id).bind('focus', function (event) {
if (opts.debug) console.log('event: focus [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
checker[getId($(this).attr('id'))] = setTimeout("check('" + getId($(this).attr('id')) + "', '')", opts.interval);
});
$('#' + opts.prefix + id).bind('blur', function (event) {
if (opts.debug) console.log('event: blur [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
});
setTimeout("check('" + id + "', '', true);", opts.interval);
});
getId = function (id) {
var pattern = opts.prefix + '(.*)';
var regex = new RegExp(pattern);
regex.exec(id);
id = RegExp.$1;
return id;
}
setPassword = function (id, str) {
if (opts.debug) console.log('setPassword: [' + id + ']');
var tmp = '';
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == unescape(opts.replacement)) {
tmp = tmp + $('#' + id).val().charAt(i);
}
else {
tmp = tmp + str.charAt(i);
}
}
$('#' + id).val(tmp);
}
check = function (id, oldValue, initialCall) {
if (opts.debug) console.log('check: [' + id + ']');
var bullets = $('#' + opts.prefix + id).val();
if (oldValue != bullets) {
setPassword(id, bullets);
if (bullets.length > 1) {
var tmp = '';
for (i = 0; i < bullets.length - 1; i++) {
tmp = tmp + unescape(opts.replacement);
}
tmp = tmp + bullets.charAt(bullets.length - 1);
$('#' + opts.prefix + id).val(tmp);
}
else {
}
clearTimeout(timer[id]);
timer[id] = setTimeout("convertLastChar('" + id + "')", opts.duration);
}
if (opts.debug) {
$('#debug_' + opts.prefix + id).text($('#' + id).val());
}
if (!initialCall) {
checker[id] = setTimeout("check('" + id + "', '" + $('#' + opts.prefix + id).val() + "', false)", opts.interval);
}
}
convertLastChar = function (id) {
if ($('#' + opts.prefix + id).val() != '') {
var tmp = '';
for (i = 0; i < $('#' + opts.prefix + id).val().length; i++) {
tmp = tmp + unescape(opts.replacement);
}
$('#' + opts.prefix + id).val(tmp);
}
}
};
})(jQuery);
When I execute my code, the code behind populates the value of the textbox with "123456789" and when the page gets rendered, all the characters have been changed to bullets, which is correct. The problem I am having is that the textbox has been disabled so I can not edit the data in the textbox.
I removed (by commenting out) the references to the disabled attribute but the control still gets rendered as disabled.
As a side note, the code that I found on the internet was originally designed to work with a textbox with a type of password but when I set the TextMode to password, not only does the control get rendered as disabled, but the field gets rendered with no value so I left the TextMode as SingleLine.
Any suggestions or assistance is greatly appreciated.
Thanks!
As far as I know, it is not possible to have it so that while you type a password, the last letter is visible for a second and then turns into a bullet or star.
However what you can do is as the user types in password, with a delay of lets say 500ms store the string the user has typed in so far into some variable and replace the content of the password field or the text field with stars or black bullets. This will give you what you are looking for.

Uncaught ReferenceError: is not defined at HTMLButtonElement.onclick

I have looked at other Questions of this type and none of them solved my problem. I am having this JavaScript code:
var count1;
for (count1 = 1; count1 < 11; count1++) {
var article = res.articles[count1]
var ImageURL = res.articles[count1].urlToImage
$('#showNews').append('<div id="' + count1 + '" class="article"><div class="overlayart"><div class="art"><h3>' + article.title + '</h3 <p>' + article.description + '<br><br><button onclick="divLoad()">Follow Link</button></p></div></div></div>');
$("#" + count1).css('background-image', 'url(' + ImageURL + ')');
x = article.url;
}
function divLoad() {
alert(article.url);
};
Basically there are 10 items with different articles. Scopes of variables are all correct. I can see the links of the items when I console log them in the loop. I want to alert each URL whenever each Item is clicked for a respected button. But when I click that I get the error:
Uncaught ReferenceError: divLoad is not defined
at HTMLButtonElement.onclick
Am I missing something?
EDIT [My Full Code]:
var x;
function divLoad() {
alert(x);
};
$(document).ready(function(){
var url = 'https://newsapi.org/v2/top-headlines?country='+country+'&apiKey=MYAPIKEY';
$.getJSON(url).then(function(res){
//console.log(res)
var count1;
for(count1 = 1; count1 < 11; count1++){
var article = res.articles[count1]
var ImageURL = res.articles[count1].urlToImage
x = article.url;
$('#showNews').append('<div id="'+count1+'" class="article"><div class="overlayart"><div class="art"><h3>'+article.title+'</h3><p>'+article.description+'<br><br><button onclick="divLoad()">Follow Link</button></p></div></div></div>');
$("#"+count1).css('background-image','url(' + ImageURL + ')');
}
});
The problem is that you're always referencing one single, global variable. That variable (x) will only ever hold the last value it was set to in your for loop.
Instead, we can append the articles and give each one a data attribute - that way, we can associate each element with a specific article URL.
function divLoad(url) {
alert(url);
};
$(document).ready(function() {
var url = 'https://newsapi.org/v2/top-headlines?country=' + "test" + '&apiKey=MYAPIKEY';
$.getJSON(url).then(function(res) {
for (let count1 = 1; count1 < 11; count1++) {
let article = res.articles[count1];
$('#showNews').append('<div id="' + count1 + '" class="article"><div class="overlayart"><div class="art"><h3>' + article.title + '</h3><p>' + article.description + '<br><br><button class="article-btn">Follow Link</button></p></div></div></div>');
$("#" + count1)
.css("background-image", "url('" + article.urlToImage + "'")
.attr("data-url", article.url); //Associate the URL to the element
}
});
$("#showNews").on("click", ".article-btn", function() {
var url = $(this).closest(".article").attr("data-url"); //Get the associated URL
divLoad(url);
});
});
If you inspect the <div class="article"> now, you'll see each one has a data-url attribute that holds its URL.

Modifying innerHTML in nested get() jQuery

I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?

Why is Firebug unable to detect some JavaScript?

I have written JavaScript outside the <body> end tag. Firebug is unable to detect the JavaScript and I am unable to detect the JavaScript error.
Here is my code:
</body>
<script type="text/javascript">
function displayIFrameContent()
{
var iFrame = document.getElementById("link");
var if1= "<iframe src='http://leadmarket.hol.es/forms/solar-power.php?adv_id=" + <?php echo($fetch_users_data['id']); ?>;
var if2= "<iframe src='http://leadmarket.hol.es/forms/kitchen-installation.php?adv_id=" + <?php echo($fetch_users_data['id']); ?>;
var if3= "<iframe src='http://leadmarket.hol.es/forms/conservatory.php?adv_id=" + <?php echo($fetch_users_data['id']);; ?>;
var host = document.getElementById("host");
var subId = document.getElementById("subid");
var errorClass = "box form-validation-error border-width-2";
if(host.value == "")
changeClass("host", errorClass);
if(host.value != "")
{
var iFrameEnd = " width='280' height='330' frameborder='0' scrolling='no'></iframe>";
var leadTypeSelect = document.getElementById("leadType");
var leadTypeValue = leadTypeSelect.options[leadTypeSelect.selectedIndex].value;
iFrame.value = "";
if(leadTypeValue == 1)
iFrame.value = if1 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
if(leadTypeValue == 2)
iFrame.value = if2 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
if(leadTypeValue == 3)
iFrame.value = if3 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
}
}
function changeClass(id, classname)
{
document.getElementById(id).setAttribute("class", classname);
}
</script>
</html>
Your help will be appreciated. Thanks in advance!
The code above contains PHP tags, which cause some syntax errors. In this case the Script panel just shows a message "No Javascript on this page". You should make sure they are interpreted by PHP before they are output to the browser.
Also JavaScript syntax errors are listed within the Console Panel. Make sure you have the option Show JavaScript Errors checked to see them.
Furthermore there's a detailed description about script debugging available within the Firebug wiki.
Sebastian

Cross browser compatibility on various javascript elements

I am working on application to make it browser compatible. I have a jsp page which will call the Javascript functions for execution. Basically I am displaying a list of contents in my page for selection using a radio button. Here it goes:
JSP Page :
<script language="JavaScript">
loadcodes(10,'codesTable','#TheCodes',' ' ,'desc','<%=compositeDescTagName%>','<%=compositeDescFormName%>','<%=codeFormName%>','<%=codeIdFormName%>','document.resourceform.<%=Globals.ENFORCE_COMMENTS%>');
</script>.
The above function will reference to the following js page:
function loadcodes(depth,tableId,dataSrc,onclickfunc,descFld,compositeDescTagName,compositeDescFormName,codeFormName,codeIdFormName,enforceCommentsFormName)
{
document.writeln("<TABLE height=100% id=PrimaryTable dataSrc='" + dataSrc + "' cellSpacing=0 cellPadding=0 border=0> <TBODY>");
writeNode(depth,dataSrc,descFld,compositeDescTagName,compositeDescFormName,codeFormName,codeIdFormName,enforceCommentsFormName);
document.writeln("</TBODY></TABLE>");
}
function writeNode(depth,dataSrc,descFld,compositeDescTagName,compositeDescFormName,codeFormName,codeIdFormName,enforceCommentsFormName)
{
if (depth <= 0)
return;
document.writeln("<TR onclick=\"toggle(this,'" + dataSrc + "','" + compositeDescTagName + "','" + compositeDescFormName + "','" + codeFormName + "','" + codeIdFormName + "','" + enforceCommentsFormName + "')\" class=tree_indent>");
document.writeln("<TD><IMG dataFld='image' id=Icon class=tree_node>");
document.writeln("<SPAN dataFld=" + descFld + " class=formtext></SPAN>");
document.writeln("<SPAN dataFld=haschildren id=HasChildren style='DISPLAY:none'></SPAN><SPAN dataFld=isleaf id=isleaf style='DISPLAY: none'></SPAN><SPAN dataFld=composite_desc id=composite_desc style='DISPLAY:none'></SPAN>");
document.writeln("<SPAN dataFld=composite_code id=composite_code style='DISPLAY:none'></SPAN>");
document.writeln("<SPAN dataFld=composite_id id=composite_id style='DISPLAY:none'></SPAN>");
document.writeln("<SPAN dataFld=comments_required id=comments_required style='DISPLAY:none'></SPAN>");
document.writeln("</TD></TR>");
document.writeln("<TR style='DISPLAY: none' class=tree_indent>");
document.writeln("<TD><!-- next level -->");
document.writeln("<TABLE class=tree_node id=node dataFld=node valign=top border=0 cellSpacing=1 cellPadding=1 >");
document.writeln("<TBODY>");
writeNode(--depth,dataSrc,descFld,compositeDescTagName,compositeDescFormName,codeFormName,codeIdFormName,enforceCommentsFormName);
document.writeln("</TBODY>");
document.writeln("</TABLE>");
document.writeln("</TD>");
document.writeln("</TR>");
}
var selectedCode;
function toggle(e,dataSrc,compositeDescTagName,compositeDescFormName,codeFormName,codeIdFormName,enforceCommentsFormName)
{
var nextRow;
var nextRow1;
nextRow = e.nextSibling;
hc = e.all.HasChildren;
var isleaf = e.all.isleaf;
if (nextRow.style.display == "none" && isleaf.innerText == "false")
{
nextRow.style.display = "";
e.all.Icon.src = "/edcs/images/minus.gif";
if (nextRow.all && nextRow.all[2] && !nextRow.all[2].dataSrc)
{
nextRow.all[2].dataSrc = dataSrc;
}
}
else if (isleaf.innerText == "true")
{
// reset the bullet on the one already selected
if (selectedCode && selectedCode.all && selectedCode.all.Icon)
selectedCode.all.Icon.src = "/edcs/images/bullet.gif";
e.all.Icon.src = "/edcs/images/right.gif";
re=/'/g;
var str = e.all.composite_desc.innerText.replace(re,"\\'");
eval(compositeDescTagName + ".innerText = '" + str + "'");
eval(compositeDescFormName + ".value = '" + str + "'");
eval(codeFormName + ".value = '" + e.all.composite_code.innerText + "'");
eval(codeIdFormName + ".value = '" + e.all.composite_id.innerText + "'");
commentsEnforced = eval(enforceCommentsFormName + ".value");
if (commentsEnforced == "false")
eval(enforceCommentsFormName + ".value = '" + e.all.comments_required.innerText + "'");
selectedCode = e;
}
else
{
nextRow.style.display = "none";
e.all.Icon.src = "/edcs/images/plus.gif";
}
}
This flow works well in IE browsers but not supported by other browsers. While searching I found the list of elements supported only by IE:
DataSrc
Datafld and also IMG datafld.
Is there any alternative for the above elements with browsers or how could the modifications made in the code so that it is browser compatible? Kindly help and also it would be turn out be a template for cross browser testing.
Cross-browser compatibility is one of the core benefits of using a library such as jQuery, MooTools, etc.
I would recommend one of these if cross-browser compatibility is your aim - as there are entire teams working on those projects.
Start with replacing usage of "all" and "eval" with document.getElementById.
All browsers support extensive debugging tools (i.e. FireBug for Firefox) - use them to see what fails.

Categories

Resources