Why "Microsoft JScript runtime error: Object expected"? - javascript

I'm about 1 day old in using jquery, and is currently having a nightmare with it. I alreadt spent half of my day trying to get rid of this error.
I did some reading after “googling” the error (sorry, Bing!) and discovered that most of these errors result from the jquery file not being properly loaded. Okay…that started to point me in the right direction but I still couldn’t figure out why it wasn’t pathing properly. I mean, I was doing as people said – I would drag the .js file into my designer and it would print out the proper path, but still the error shows.
Here's my exact code in my editor template (with the error):
#model bool
#{
string status = "Active";
string buttonValue = "Deactivate";
string hiddenValue = "true";
if (!ViewData.Model)
{
status = "Inactive";
buttonValue = "Activate";
hiddenValue = "false";
}
}
<div style="width:100px; float:left;">
<img id = "AD_Img" src = "/Content/themes/base/images/icon_#(status).png" alt = #(status) />
<label for = "AD_Img" id = "AD_Label" >#(status)</label>
</div>
<div style="width:100px; float:left;">
<input type="button" id = "AD_Button" value = #(buttonValue) style = "width:100px" onclick = "ChangeStatus()" />
<input id = "AcntStatus" type = "hidden" name = "AcntStatus" value = #(hiddenValue) />
</div>
and in the same cshtml file, the script goes this way:
<script type="text/javascript" src="/Scripts/jquery-1.5.1.min.js">
function ChangeStatus()
{
var ButtonVal = $("#AD_Button").val();
alert(ButtonVal);
if (ButtonVal == "Deactivate")
{
var stat = "Inactive";
var buttonVal = "Activate";
var HiddenValue = "false";
}
else if (ButtonVal == "Activate")
{
stat = "Active";
buttonVal = "Deactivate";
HiddenValue = "true";
}
$("#AD_Img").attr({src: "/Content/themes/base/images/icon_"+stat+".png", alt: stat});
$("#AD_Label").html(stat);
$("#AD_Button").val(buttonVal);
$("#AcntStatus").val(HiddenValue);
}
</script>
The debugger stops on the ChangeStatus function of the input element on the following line:
<input type="button" id = "AD_Button" value = #(buttonValue) style = "width:100px" onclick = "ChangeStatus()" />
i tried to debug it by using this in my function code:
function ChangeStatus()
{
var ButtonVal = document.getElementById("AD_Button").value;
alert(ButtonVal);
}
And it works properly, it returns the exact string that I'm looking for without that error, but why? What's wrong with my codes?
Please help me figure this out.

This:
$("#AD_Img").attr(src: "../../../Content/themes/base/images/icon_"+stat+".png", alt: stat);
forces an Syntax-error. It has to be:
$("#AD_Img").attr({src: "../../../Content/themes/base/images/icon_"+stat+".png", alt: stat});
Edit:
Also take a look at your <script>, you can't mix external JS and internal JS.
This:
<script type="text/javascript" src="../../../Scripts/jquery-1.5.1.min.js">
//your code
</script>
Has to be splitted into
<script type="text/javascript" src="../../../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
//your code
</script>

Related

Add Dynamic Variable in URL Content in JQuery

I am trying to add attach my variable on my script section, since my filename is in GUID format. The filename is in hidden field:
string strDirectory = Server.MapPath(Url.Content("~/Content/AnnouncementImages/"));
string[] strFiles = Directory.GetFiles(strDirectory);
string strFileName = string.Empty;
foreach (var strFile in strFiles)
{
strFileName = Path.GetFileName(strFile);
}
<img id="myImg" src="#Url.Content("~/Content/AnnouncementImages/" + strFileName)" width="300" height="200" />
<input type="hidden" id="hiddenStringFileName" value="#strFileName"/>
In script section, I am trying to get this hidden field value:
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName');
//This is not working so far since it says cannot resolve symbol filename on below code:
modalImg.src = '#Url.Content("~/Content/AnnouncementImages/" + filename);
}
I am not sure what you are trying to do but if you want razor code plus javascript, you can put it in your view. Obviously this will no longer be unobtrusive javascript. But to do what you want, this will work. I added a button when you click it, it calls the function to show the concatenated URL.
#{
ViewBag.Title = "Test";
var strFileName = Guid.NewGuid();
}
<input type="hidden" id="hiddenStringFileName" value="#strFileName" />
<button onclick="fncAnnouncementLoad()">Show</button>
<script>
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName').value;
//This is not working so far since it says cannot resolve symbol filename on below code:
var src = '#Url.Content("~/Content/AnnouncementImages/")' + filename;
alert(src);
}
</script>

Undefined function in javascript

I'm encountering an error that doesn't seem to make sense.
Chrome's console is saying Uncaught ReferenceError: clicked_server is not defined
I tried almost everything to fix it but the error itself doesn't make much sense
<script>
var selected_char = 'X';
function draw_list () {
// lets draw an x in all server in the array
var server_id = 0;
var draw_servers = new Array();
draw_servers = document.getElementById("server_arr").value.split(";");
foreach(draw_servers as server_id) {
document.getElementById("server("+server_id+")").innerHTML = selected_char;
}
// Update the counter and servers array
server_count_field.innerHTML = "Buy Server("+servers_array.length+")";
}
function clicked_server(server_id) {
var clicked = document.getElementById("server("+server_id+")").innerHTML;
if (clicked == selected_char) remove_server(server_id);
else add_server(server_id);
}
window.onload = draw_list();
function add_server(server_id) {
// select a server for purchase
var servers_array = document.getElementById("server_arr").value;
if(servers_array.length > 0) servers_array = servers_array + ";" + server;
else servers_array = server;
document.getElementById("server_arr").value = servers_array;
}
</script>
My HTML is working perfectly. Here it is
<form action="dobuyserver.php" method="POST">
<input type="hidden" name="server" id="server_arr"/>
<input type="submit" value="Buy Server(0)" id="server_count"/>
</form>
<td style="background-color:##000000;" onclick="clicked_server(9)"><font color="#FFFFFF">
<strong>
<span id="server(9)">
</span>
</strong>
</font></td>
As per my understanding you need to use
window.onload = draw_list;
instead of
window.onload = draw_list();
The reason for the stated error is that your javascript fails before getting to your function.
foreach(draw_servers as server_id) {
This line is invalid, so the js blows up and never goes beyond that line.
Replace window.onload = draw_list(); with window.onload = draw_list;
window.onload
Use window.onload = draw_list; instead of window.onload = draw_list();

New to HTML5 and JavaScript, and I can't connect JavaScript file to HTML file?

So I am having a problem with HTML5 and javascript.
I made a few .js files for the javascript part and I made the link to connect it with the HMTL code but it will not show the javascript part.
This is my HTML
<!doctype html>
<html lang="en">
<head>
<title>Gateway Tunes</title>
<meta charset="utf-8" />
<script src="playlist_store.js"></script>
<script src="playlist.js"></script>
</head>
<body>
<form>
<input type="text" id="songTextInput" size="40" placeholder="Song name">
<input type="button" id="addButton" value="Add Song">
</form>
<ul id="playlist">
</ul>
</body>
</html>
and here are my javascript files; the names of the files are at the top
playlist_store.js
function save(item) {
var playlistArray = getStoreArray("playlist");
playlistArray.push(item);
localStorage.setItem("playlist", JSON.stringify (playlistArray));
}
function loadPlaylist() {
var playlistArray = getSavedSongs();
var ul = document.getElementById('playlist");
if (playlistArray !Null) {
for (var i = 0; i < playlistArray.length; i++) {
li.innerHTML = playlistArrray[i];
ul.appenChild(li);
}
}
}
function getSavedSongs() {
return getStoreArray("playlist")
}
function getStoreArray (key);
var playlistArray = localStorage.getItem(key);
if(playlistArray == null || playlistArray == "") {
playlistArray = new Array();
}
else {
playlistArray = JSON.parse (playlistArray);
}
return playlistArray;
}
playlist.js
window.onload = init;
function init() {
var button = document.getElementById ("addButton");
button.onclick = handleButtonClick;
loadPlaylist();
}
function handleButtonClick () {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
if (songName == "") {
alert("Button was clicked!");
}
else {
alert("Your track has been added!");
}
var li = document.createElement("li");
li.innerHTML = songName;
var ul = document.getElementById("playlist");
ul.appendChild(li);
save (songName);
}
You've got some syntax errors so your javascript isn't running.
In playlist_store.js
var ul = document.getElementById('playlist");
Opens a string with ' but tries to close it with ". It doesn't matter which you use as long as you're consistent, so you can either change it to 'playlist' or "playlist".
if (playlistArray !Null) {
If you're trying to make sure playlistArray isn't null you can do
if (playlistArray != null) {
notice != as the comparison and null needs to be lowercase. If you want to make sure it isn't just undefined or null you can simply do if (!playlistArray).
ul.appenChild(li); needs to be ul.appendChild(li);.
I'm sure there's more, check over your code.
The first line of your script (and the only one that isn't just a function definition) is window.onload = init;. This means that after the page has loaded, your init function is called.
This function looks up the element with id addbutton, and then calls a method on the returned result. Since you don't have an element with this ID, there won't be any object returned, and so an exception will be thrown (something like "button is null or not an object", depending on your browser). This exception stops the method from executing further - and in particular, loadPlaylist() will not be called.
The moral of the story here though is pay attention to the JavaScript error console, especially while you're doing development! You browser will almost certainly have displayed a red exclamation mark icon or similar, which you could double-click to give you the name, message and location of the exception.
You really don't need to post your code listing on Stack Overflow to ask us what's wrong with it, when your browser is already capable of telling you exactly where the problem is.

Javascript text file reader doesnt work the first time

I got a webpage with some homemade search engine which is supposed to look for some data in a server-side text file. I use JS to parse this file, it works well except for the very 1st time I use it... The culprit seems to be my fetchText() function which doesnt return anything the first time. Note that if I add a alert() inside the fetchText() it works correctly (see note in JS source code). I guess the IFRAME is not fully loaded or something. What can I do ?
Webpage code
<form style="margin-top:15px; margin-left:15px;width:200px;">
<input type="text" value="NGR_" id="srcTxtInput" style="margin-top:0px;margin-left:0px;width:100px;"/>
<input type="button" value="Go" onclick="SearchString('./Coordinates.txt')" />
</form>
<div id="searchResults" style="vertical-align:right;margin-top:25px;">
<select size="4" id="select_list" onchange="Selec_change();" ondblclick="Selec_change();" style="visibility: hidden; width:250px;margin-left:8px;" ></select>
<img id="closeImg" src="./close.png" height="15px" width="15px" style="opacity:0.5;visibility:hidden; margin-left:235px;margin-bottom:5px;margin-top:5px;vertical-align:top;" alt="Close results" title="Close results" onclick="HideSearch();" onmouseover="this.style.cursor='pointer';"/>
</div>
JS code
function SearchString(txtFile){
var slist = document.getElementById('select_list');
var str = trim(document.getElementById('srcTxtInput').value.toUpperCase());
if(str == "" ){
slist.options.length = 0; //empty list
HideSearch();
exit;
}
var txt = fetchText(txtFile);
//DO SOMETHING
}
function fetchText(txtFile) {
var d = document;
var txtFrame = d.getElementById('textReader');
txtFrame.src = txtFile;
**//Note that if I add *alert(txtFrame.src)* here the function works the 1st time**
var text = '';
if (txtFrame.contentDocument) {
var d = txtFrame.contentDocument;
text = d.getElementsByTagName( 'BODY')[ 0].innerHTML;
}
else if (txtFrame.contentWindow) {
var w = txtFrame.contentWindow;
text = w.document.body.innerHTML;
}
return text;
}
Since loading page content like that is an asynchronous operation, you can't expect the contents to be there immediately after setting the "src" attribute of your <iframe>. You'll have to put the code that searches through the text in a "load" event handler on the frame document.
That means you'll write something like:
fetchText(textFile, function(theText) {
// DO SOMETHING
});
and modify "fetchText()" to be more like this:
function fetchText(txtFile, whenLoaded) {
var d = document;
var txtFrame = d.getElementById('textReader');
txtFrame.onload = function() {
var text = '';
if (txtFrame.contentDocument) {
var d = txtFrame.contentDocument;
text = d.getElementsByTagName( 'BODY')[ 0].innerHTML;
}
else if (txtFrame.contentWindow) {
var w = txtFrame.contentWindow;
text = w.document.body.innerHTML;
}
whenLoaded(text);
};
txtFrame.src = txtFile;
}

Replacing DIV content based on variable sent from another HTML file

I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>

Categories