If i input my code here:
http://writecodeonline.com/javascript/
It works as intended, but if i input it in my adressbar with "javascript:" infront the alert box just shows the original string.
What is going wrong?
var string = "Sunshine & Whiskey";
var stringFeedback;
var i = 0;
string = string.replace("&","%26");
do {
stringFeedback = string.search(/[ ]/);
string = string.replace(/[ ]/,"%20");
i += 1;
} while (i < 5);
alert(string);
Edit:
If i input in my Chromium console it works fine, but if i make a bookmark with the same code it doesn't.
Any suggestions on how to fix that?
Try initialising i before the loop:
var i = 0;
do {
stringFeedback = string.search(/[ ]/);
string = string.replace(/[ ]/,"%20");
i += 1;
} while (i < 5);
Whatever, I recommend you use your browser console to test these code snippets.
You can use
encodeURIComponent("Sunshine & Whiskey");
That returns
Sunshine%20%26%20Whiskey
without any loop, it's a native method of javascript that is supported by all Browser.
MDN documentation
Related
I am working on a PDF with some scripting, and I am applying code to fields using the console and some simple loops to save on repeated efforts. In some cases, I am applying a custom calculation script to a field where one integer needs to change from one field to the next. If all the scripts were the same, I would run this in the debugger console:
var s = "if(this.getField(\"Span A\").value >= 60){\n\
event.value = Math.round(((this.getField(\"Span A\").value*41500 - 1674500)/233));\n\
}else{\n\
event.value = Math.round((this.getField(\"Span A\").value*3500/60));\n\
}";
for (var i = 0; i < this.numFields; i++){
var f = this.getField(getNthFieldName(i));
if(f.name.match(/quant a/i) != null){
var n = f.name.match(/\d/g);
f.setAction("Calculate", s);
}
}
I have many 'Quant' fields, and each group (A, B, etc) will have a similar calculation. The fields are name "Quant A1", "Quant A2" etc. Quant A1 needs to calculate with the input from Span A1.
In the above script, it would be really cool if I could have a variable within the script string that I can pass a value (n) to be plugged in to the string, essentially the same way a function call works.
Is this possible?
Here is my fantasy version of what I imagine it could look like (this is just to further explain my intent; I don't think this would actually work this way):
var s(x) = "if(this.getField(\"Span A\""x").value >= 60){\n\
event.value = Math.round(((this.getField(\"Span A\""x").value*41500 - 1674500)/233));\n\
}else{\n\
event.value = Math.round((this.getField(\"Span A\""x").value*3500/60));\n\
}";
for (var i = 0; i < this.numFields; i++){
var f = this.getField(getNthFieldName(i));
if(f.name.match(/quant a/i) != null){
var n = f.name.match(/\d/g);
f.setAction("Calculate", s(n));
}
}
You could use string litterals if you're useing ES6 and higher.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals?retiredLocale=nl
const greetings = "I'm a variable!";
let string = `Hi! this is a variable: ${greetings}`;
console.log(string);
Otherwise concatenate it with the + operator.
If I understand correctly your question. I think you want to use template literals.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Use backticks instead of " or ' to insert your variables inside a string.
const a ='Cheese'
const b= 'is Delicious'
${a} ${b} will output 'Cheese is Delicious'
I have one hidden box which contains value like (,1420,1254,1258,124,1235). These values are IDs which are populated based on the description selected by user through Select Box. If user selects any description and removes it from Select Box then corresponding ID should be removed from the Hidden box. I can only use Javascript to do this. I tried using replace method but it is not supported and also my application works only in IE browser.
Could anyone let me know how to get this done?
TIA
Without seeing your code, this is the most we can help you with
function removeId(hiddenBox,id){
var idList = hiddenBox.innerHTML;
idList = idList.customReplace(','+id,'');
hiddenBox.innerHTML = idList;
}
And since you said the replace method is not working for some reason (which is weird), here is a custom replace method
I'm hoping the indexOf(), length and substring() methods are still working
String.prototype.customReplace = function(from,to){
var string = String(this);
var newString = "";
var startIndex = string.indexOf(from);
if(startIndex == -1) return string;
var endIndex = startIndex + from.length;
newString = string.substring(0,startIndex);
newString += to;
newString += string.substring(endIndex,string.length);
return newString;
}
I am having a problem with a simple script that is supposed to update a page with some values(user input) that are turned from monthly to yearly (the numbers go into numeric fields created by confirmIT)
<script>
function update() {
for (var i = 0; i < 9; i++) {
var ans = parseInt(document.getElementById("bq10a_" + i).value, 10);
if (!isNaN(ans)) {
var new = ans * 12;
document.getElementById("bq10a_" + i + "calc").value = new;
}
}
}
return;
}
setInterval("update()", 1000);
</script>
this yields an Expected identifier error on line
var new = ans*12;
and i would appreciate any help on how to solve it
The word new is a reserved word in JavaScript and cannot be used as the name of a variable.
The error means that the parser expected an "identifier", which is to say that it expected to see a valid identifier.
Change the name of the variable and things should improve. In the code you've posted I think there's a { } nesting problem; there appears to be one too many before the return of the function.
edit — also as jbabey notes in a comment, your setInterval() call should be
setInterval(update, 1000);
It's not a good idea, generally, to pass strings to setInterval(), despite the advice of thousands of mouldy old instructional websites.
Word "new" -- is special in javascript language:
line is incorrect:
var new = ans*12;
try this:
var newvalue = ans*12;
More information on:
http://javascript.about.com/library/blreserved.htm
http://www.ecma-international.org/publications/standards/Ecma-262.htm
I have the following function in javascript. It works in every browser except firefox. There seems to be some problems with the substring keyword in this browser.
function EvalMonthYear() {
var RawMonth = $.trim( $('#MonthList').val() );
var SpacePosition = RawMonth.lastIndexOf(' ') + 1;
var TheYear = $.trim(RawMonth.substring(SpacePosition, RawMonth.lenght));
var TheMonth = IndexOfMonth($.trim(RawMonth.substring(0, SpacePosition)));
};
MonthList contains a month/year string such as January 2011 or May 2009. The goal is to fill the variables TheYear and TheMonth so that it works in every browser.
If you've run into this problem and can think of a good solution this would be helpful.
Thanks.
Maybe you want to rewrite
RawMonth.lenght
as
RawMonth.length
Your original code works in Firefox 4b11 for me, so it might be an issue with 3.6. I'm guessing that your typo works in most browsers because RawMonth.lenght is undefined, which is similar to not passing in the argument. (It's a little different, if you inspect the arguments array.)
Try this:
function EvalMonthYear() {
var RawMonth = $.trim( $('#MonthList').val() );
var MonthYear = RawMonth.split(" ");
var TheYear = MonthYear[1];
var TheMonth = MonthYear[0];
};
I have the following code:
for (i=1; i<=len; i++) {
var optcheck = col+'|'+document.getElementById('color').options[i].value;
text = document.getElementById('color').options[i].text.split(' - ');
}
This is part of the original code from javascript. I have successfully converted much of the other stuff into jquery but I can't seem to figure out how to convert this into jquery.
Please note that col is just value I am passing when calling the function which is usually "16"
Here is what I got so far:
for (i=1; i<=len; i++) {
var optcheck = col+'|'+$('#color').val(i);
text = $('#color').val(i).text.split(' - ');
}
Also, the original code works fine in Chrome, Firefox, Opera and Safari but in IE (all version from 6 to 9) I get an error saying 'options[...].value' is not null or not an object
Thanks for the help!
You're mis-calling val.
Change it to $('#color option').eq(i).text() and $('#color option').eq(i).val()
$('#color option').each(function() {
var a = col + '|' + this.value,
b = this.text.split(' - ');
// do stuff with a and b
});