Javascript script return errors [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Following code is returning error. Since I am beginner so i need to help so that i can fix the error
<script>
function myFunction() { var message, x; message = document.getElementById("message"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "empty"; if(isNaN(x)) throw "not a number"; x = Number(x); if(x < 5) throw "too low"; if(x > 10) throw "too high"; } catch(err) { message.innerHTML = "Input is " + err; } }
</script>

In the first example you're assigning the HTML element defined by the id "message" to the message variable, and then setting the innerHTML of that element to an empty string. It's a useful caching method if you need to, for example, change more than the innerHTML, like the style, or attribute values too.
In the second example you're doing more or less the same thing but, in this case, there is no reason for you to assign it to a variable. You can simply set the innerHTML of the HTML itself:
document.getElementById("message").innerHTML = "";

var message = document.getElementById("message");
message.innerHTML = "";
In message you have an element, you can use message to manipulate it how many time you want.
var message = document.getElementById("message").innerHTML();
In that you are putting in message the string inside the inner Html

In this case
var message = document.getElementById("message");
message.innerHTML = "";
message is of typeElement (here the MDN documentation: getElementById) and then you set its property innerHTML as ""
but here
var message = document.getElementById("message").innerHTML = "";
you create a variable named message and set it as the returning value of the operation document.getElementById("message").innerHTML = "" that, in this case, is ""
Conclusion:
The first code will result in having the variable message as an Element object;
The last code will result in having the variable message as, in this case, an empty string

Related

Compare two variable string in JavaScript

i am trying to compare two strings in javascript. below is my code
var statuss = document.getElementById("status").innerHTML;
//alert(statuss);
var s =statuss.toString();
var ss= "Active";
if (s === "Active"){
alert ('match');
}
else {
alert ('do not match');
}
why am i getting the output " do not match" when it should have been 'match' since when i did
alert ('document.getElementById("status").innerHTML');
i got the output: Active.
So basically both variable should have matched.. why am getting the opposite?
You might want to try the following
var s = statuss.toString().trim();
The most likely explanation is that your HTML also contains whitespace at the beginning and/or end.

jquery hide/show or condiiton failing

Is there anything wrong with the jQuery/JS below? I have an input field aAmt which on change calls below. ${dAmt} = "10000" from DB. It basically converts the number to $ format(eg.. 23 to $23.00) and focuses the value to the input field. Issue is the if loop (if(aAmt >= a_amount)...) fails.
Even if the condition fails it goes to if loops and shows the div which should not happen. I don't see any error in developers console.
$('#aAmt').change(function() {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
curFormat(aAmt);
if(aAmt >= a_amount)
{
$("#dsDiv").show();
}else{
$("#dsDiv").hide();
}
});
function curFormat(aAmt)
{
var nAmt = Number(aAmt.replace(/[^0-9\.]+/g,""));
var fAmt = '$' + nAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
document.getElementById("aAmt").value = fAmt;
}
Have you tried to convert a_amount to an int, to be sure to compare two integers together:
var a_amount = parseInt("${dAmt}");

Replacing an Element in jQuery [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to modify an element in jQuery programmatically, i.e. a number in docID increments up to a maximum number. I'm replacing text on a series of images on a page from Download to View. If I use #ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload instead of docID in the $(docID).text(...) part of the code, the text gets replaced correctly. When I use the docID variable in its place, it doesn't work.
What am I doing wrong here?
Thanks.
var max = 10;
var count = 100;
var s1 = "#ctl00_cphMainContent_dlProductList_ct";
var s2 = "_ctl00_lnkProofDownload";
var docID = "";
for (i = 1; i <= max; i++)
{
docID = s1.concat (count++, s2);
$(document).ready(function() {
$(docID).text(function(i, oldText) {
return oldText === 'Download' ? 'View' : oldText;
});
});
}
This is the HTML code that is being modified. The word Download is replaced by View.
<a id="ctl00_cphMainContent_dlProductList_ctl00_ctl00_lnkProofDownload"
href="../../../Controls/StaticDocProof.ashx?qs=op/5WlcUxeg849UT973Mwf0ZnNcMLfe3JYAe7EnJORsdyETYV1vcKaj0ROc2VrN5fXfYjO2MM6BUYXzX2UKmog=="
>Download</a>
It looks like you have done a couple things incorrectly in your code, including using a 1 instead of an l. If it was supposed to be a 100 instead of a l00, something more like this would work:
jQuery(function () {
var max = 10,
count = 100,
s1 = 'ctl00_cphMainContent_dlProductList_ct',
s2 = '_ctl00_lnkProofDownload',
docID;
for (var i = count; i <= count + max; i++) {
docID = s1 + i + s2;
jQuery('#' + docID).text(function (idx, oldText) {
return oldText === 'Download' ? 'View' : oldText;
});
}
});
Fiddle here: http://jsfiddle.net/ochguL2d/
Otherwise, let us know if it is supposed to be l00 for a different answer.
Your a element has this in the middle (note two "els"):
ctl00_ctl00
… but your docID has this in the middle (note a "one and an el"):
ct100_ctl00
Fix your HTML, and your code works as-is: http://jsfiddle.net/5c7hwyts/
However, that's an odd way to write jQuery.
Here's a different approach:
$('a').text(function(i, oldText) {
var num= parseInt(this.id.split('ctl00_cphMainContent_dlProductList_ct')[1]);
if(num>=100 && num<110) {
return oldText === 'Download' ? 'View' : oldText;
}
});
Fiddle
The element IDs your are trying to match in your code are not the ones in the DOM.
// This is what you want to match
var domID = "#ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload"
^ that is an L
// this what your code is trying to match in its first iteration
var docID = "#ctl00_cphMainContent_dlProductList_ct10_ctl00_lnkProofDownload";"
^ that is a 1 (one)
Also, your code's max variable needs to be a two char numeric string with leading zeros starting at zero, not an integer starting at 10.
Personally, I would just:
// On DomReady...
$(document).ready(function() {
// loop through all anchors that have "lnkProofDownload" in their ID attribute
$('a[id*="lnkProofDownload"]').each(function() {
// and if the text is set to "Download", change it to "View"
if ($(this).text() == "Download") {
$(this).text("View");
}
});
});

Variable reset to default option, WHY? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I do not understand how I keep ending up with "null" after variable is assigned a number.
function evalKayScript(syn){
coms = extract(syn,"{...}");
document.write(JSON.stringify(coms));//debug
for(x in coms){
ops = extract(coms[x],"(...)");
com = null; //<-- ***com preset null***
for(y in funNames){
if(ops[1] == funNames[y]){
com = y; //<-- ***com changed to "y"***
}
}
alert(com); <-- alerts given below (first two alerts)
if(com == null){
alert("Command ((("+ops[1]+"))) Not Registered!");
return null;
}
exe = funValues[y];
inputs = execVars(ops[2]);
inputs = extract(inputs,"[...]");
for(y in inputs){
exe.replace(new RegExp("/\(\%"+y+"\%\)/gim"),inputs[y]);
}
exe.replace(new RegExp("/\(\%name\%\)/gim"),ops[0]).replace(new RegExp("/\(\%function\%\)/gim"),ops[1]);
exea = exe;
if(exe.replace(new RegExp("/\:\:\:javascript/gim"),"")! = exes){ //<-- new invalid ":" error
eval(exe);
}else{
evalKayScript(exe);
}
}
}
I do not understand why, variable "com" goes to a number, then back to null...
I have setup some error catching in my own form, and i end up with these alerts:
0 //<-- var com
null //<-- ***var com? this makes no sense, how does it go back to null?***
Command ((("(%name%) already exists!"))) Not Registered! //<--caused by if(com == null) This is normal.
Live script at http://jstone88.bugs3.com/kayscript/file1.html, and JS file at http://jstone88.bugs3.com/kayscript/kayscript.js
You aren't using RegExp constructor as it should have been used.
It is like this:
new RegExp("pattern without / at the beginning an end","flags");
/pattern/flags is literal form of writing a regex in js, but it is different in RegExp constructor.

variable string appearing as undefined, new string not appearing in array, javascript

I'm attempting to write some code that puts a single string of emails into an array of emails. Splitting the string wherever there's a comma(,). The initial problem i'm having is the string that is being passed as a variable is not being recognized. I'm getting the error message "Cannot read property 'length' of undefined" of the conditional part of the for loop. Odd, as I'm definitely passing a string or trying to ?
When I pass in a string directly to the function parameter(to avoid the above problem for testing the rest of the function) only the first 2 email addresses appear the final email address is lost ?
I'm learning programming and this is an exercise as such I'm trying to avoid using the split() method or regEx. Daft i know.
Any help in overcoming these 2 issues greatly appreciated.
function separateCommaValues(text)
{
var input = [];
var val = '';
for(var i = 0; i < text.length; i++) {
if(text[i] == ',') {
if(val.length == 0){
continue;
}
input.push(val);
val = '';
} else {
val += text[i];
}
}
document.write( input );
}
separateCommaValues(str);
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
separateCommaValues(str);
This is the correct order. Your variable can be declared before it is used via hoisting, but you can't define it before it is used (undefined error).
And the last email address isn't pushed into the array because it doesn't have a comma after it. So after the loop, before document.write( input );, add something like this:
if(val.length > 0){
input.push(val);
val = '';
}

Categories