Cross browser compatibility on various javascript elements - javascript

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.

Related

Uncaught syntaxerror: Unexpected Identifier (Javascript, asp.net mvc, cshtml)

So the error I am receiving is when I click the remove button on the dynamically created html, which is meant to call the remove method at the bottom and pass the arguments. The passing of the object as an argument is where I am running into the problems..
function addMarkerToList(args) {
var object = args;
var camera = args.id;
var test = selectedCameras.indexOf(args.id);
var noOfCamerasAllowed = #Model.usersName.CamerasSelectable;
if (selectedCameras.length < noOfCamerasAllowed) {
if (test > -1) {
alert("Camera already in list");
} else
{
selectedCameras.push(args.id);
var outputString = "";
for (i = 0; i<selectedCameras.length; i++) {
outputString += selectedCameras[i] + ",";
}
//$("#cameraSelectedList").append("<p id=" + args.id + ">" + args.id + "</p>");
$("#cameraSelectedList").append(
"<div id = " + camera + " class=\"col-md-12\">" +
"<div class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 user-item\">" +
"<div class=\"user-container\">" +
"<a class=\"user-avatar\"><i class=\"glyphicon glyphicon-facetime-video\" style=\"color: #ed1c24; font-size: 36px;\"></i></a>" +
"<p class=\"user-name\">" +
"<span>Camera</span>" +
This is where I think the issue is being caused:
"<input type=\"button\" value=\"Remove\" onclick=\"removeMarkerFromList(" + object + ")\"/>" +
"</p>" +
"</div>" +
"</div>");
The directly above section is where the error is being caused, I think by how I am passing the args called (object) in the input button back the the remove method below..
if (check === 0) {
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 1;
lastAddedId = (camera + ".2");
} else {
//alert("This is the last added id: " + lastAddedId);
document.getElementById(lastAddedId).remove();
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 0;
lastAddedId = (camera + ".2");
}
}
} else {
alert("You have added the maximum number of cameras");
}
}
//Removing objects by right clicking the marker
function removeMarkerFromList(args) {
var camera = args.id;
alert(camera);
var test = selectedCameras.indexOf(camera);
if (test > -1) {
document.getElementById(camera).remove();
selectedCameras.splice(test, 1);
alert("Camera removed from list");
} else {
alert("Camera not in list");
}
var outputString = "";
for (i = 0; i<selectedCameras.length; i++) {
outputString += selectedCameras[i] + ",";
}
document.getElementById(lastAddedId).remove();
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 1;
lastAddedId = (camera + ".2");
}
You're concatenating your object into a string, which probably gives you something like
onclick="removeMarkerFromList([Object object])"
You can use an id (string or number) instead and retrieve your object afterwards:
"onclick=\"removeMarkerFromList(" + object.id + ")\"/>"
You can also stringify your object:
"onclick=\"removeMarkerFromList(" + JSON.stringify(object) + ")\"/>"
I managed to solve the issue by using object manipulation before passing the object to my method.
Thank you everyone for your assistance!
In ASP.NET/MVC/.NET Core project if you are facing this issue, sometimes this might be due to cache storage refresh not happening. In my instance, I had a Redis server running and it needed a manual restart. Go to Task Manager-> Services tab and see the server you are running and restart it manually( Redis server: Memurai in case if you are using windows).

Issue trying to escape a string in javascript plugin

I'm trying to use a Bootstrap Tab plugin for CKEditor, and it works well. But, when i use a single quote on content (doesn't matter if the string is "'", or " or '), it broke up.
I guess is just a escape issue. I tried with escape() and encodeURI(), but fails.
Error: SyntaxError: missing ) after argument list;
Source:
x)PRE3015 Pino 1/2'' 15mm Ponta Balistica Aço 3,1 15
The piece of plugin code for tabs is:
data: function() {
var bootstrapTab_d = new Date();
var bootstrapTab_id = bootstrapTab_d.getTime();
var bootstrapTab_item = bootstrapTab_contents = '';
for (var bootstrapTab_i = 0; bootstrapTab_i <= this.data.bootstrapTab_total; bootstrapTab_i++) {
eval("bootstrapTab_title = this.data.bootstrapTab_item" + bootstrapTab_i);
bootstrapTab_title = bootstrapTab_title != undefined ? bootstrapTab_title : '';
eval("bootstrapTab_content = this.data.bootstrapTab_content" + bootstrapTab_i);
bootstrapTab_content = bootstrapTab_content != undefined ? bootstrapTab_content : '';
eval("bootstrapTab_itemClass = this.data.bootstrapTab_itemClass" + bootstrapTab_i);
bootstrapTab_itemClass = bootstrapTab_itemClass != undefined ? bootstrapTab_itemClass : '';
eval("bootstrapTab_contentClass = this.data.bootstrapTab_contentClass" + bootstrapTab_i);
bootstrapTab_contentClass = bootstrapTab_contentClass != undefined ? bootstrapTab_contentClass : '';
if (bootstrapTab_title) {
bootstrapTab_item += '<li role="presentation" class="' + bootstrapTab_itemClass + '">' + bootstrapTab_title + '</li>';
bootstrapTab_contents += '<div role="tabpanel" class="' + bootstrapTab_contentClass + '" id="tab' + bootstrapTab_id + '_' + (bootstrapTab_i + 1) + '">' + bootstrapTab_content + '</div>'
}
}
this.element.setAttribute('id', 'collapse' + bootstrapTab_id);
this.element.$.innerHTML = '<div role="tabpanel"><ul class="nav nav-tabs" role="tablist">' + bootstrapTab_item + '</ul><div class="tab-content">' + bootstrapTab_contents + '</div></div>'
}
I'd refactor the code, and not use eval!
eval is evil http://blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx
instead of
eval("bootstrapTab_title = this.data.bootstrapTab_item" + bootstrapTab_i);
use bootstrapTab_item as an array and do this
bootstrapTab_title = this.data.bootstrapTab_item[bootstrapTab_i]
really don't know if the error is there, but I think the path to find the error is refactor to eliminate those eval, that could be the source of your problem.

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

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

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

Converting firefox javascript to IE javascript

I've been trying to get some AJAX code that runs fine in FireFox to run in IE.
I'm running into some trouble with updating some tables in the script though. I've seen numerous other people have similar issues, but none of the solutions they've found have worked for me. The problem occurs first on the line
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
Where I'm getting the error "'null' is null or not an object"
I'm pretty sure that all of my other errors are of the same type as this one, my AJAX script and some accompanying javascript is below.
<script type="text/javascript">
<!--
//obtains the box address for a QE3 on the system for the given index
function getQE3BoxAddressHash(index)
{
var retVal = 0x00000100; //initial value for QE3 boxes
retVal |= (index & 0x000000FF);
return retVal;
}
//obtains the box address for a QED on the system for the given index
function getQEDBoxAddressHash(index)
{
var retVal = 0x00001300; //initial value for QED boxes
retVal |= ((index & 0x0000000F) << 4);
retVal |= ((index & 0x000000F0) >> 4);
return retVal;
}
-->
</script>
<script type="text/javascript">
<!--
var textSocket;
function fillTables()
{
if(textSocket.readyState != 4)
return;
var qe3Table = document.getElementById("QE3_TABLE");
var qedTable = document.getElementById("QED_TABLE");
var rawData = textSocket.responseText.split("::::");
var qe3Data = new Array();
var qedData = new Array();
var qe3Index = 0;
var qedIndex = 0;
for(var item in rawData)
{
if(rawData[item].indexOf("QA") != -1)
{
qe3Data[qe3Index++] = rawData[item];
}
else if(rawData[item].indexOf("QED") != -1)
{
qedData[qedIndex++] = rawData[item];
}
}
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
qedTable.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
for(var value in qe3Data)
{
var components = qe3Data[value].split("-");
if(components.length != 3)
continue;
qe3Table.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQE3BoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
for(var value in qedData)
{
var components = qedData[value].split("-");
if(components.length != 3)
continue;
qedTable.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQEDBoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
}
function initAjax()
{
try
{
// Opera 8.0+, Firefox, Safari
textSocket = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
textSocket = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
textSocket = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("A browser error occurred.");
return false;
}
}
}
textSocket.onreadystatechange=fillTables
}
function reloadTables()
{
textSocket.open("GET","ajax_scripts/get_connected_boxes.php",true);
textSocket.send(null);
}
function init()
{
initAjax();
reloadTables();
}
window.onload=init();
-->
</script>
The problem is probably with:
var qe3Table = document.getElementById("QE3_TABLE");
If you're running this script before the body is loaded, that won't exist. Check to see if that variable has anything in it.
I Tried both of your guys' fixes but they didn't seem to help. In the end, I converted all calls of the form:
qe3TableNew.innerHTML = ("<tr>\n" +" <th>Name</th>\n" +" <th>Status</th>\n" +" <th>View Status</th>\n" +"</tr>\n");
to
var row;
var cell;
var text;
var font;
row = document.createElement("tr");
qe3TableNew.appendChild(row);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Name");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Status");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("View Status");
cell.appendChild(text);
This seemed to solve it, so I believe it has to do with IE's inability to handle changes to innerHTML.
Thanks for the help guys.
At least one issue (which could produce the above symptoms) is the line:
window.onload=init();
Hint: the () operator executes the function immediately and evaluates to the return value. This in turn may allow the XHR handler (in certain situations) to fire at a time when the DOM may not be ready.
Happy coding.

Categories

Resources