I have a loop that will declare a new variable each time. I want to write my results to a new window and I would like every string declared to print with breaks.
I did try making combining all vars together with '+' signs (using [i] to get the number of occurrences) but document.write printed it because it was a string.
Does anyone know what I can do? I'm sure there must be a few ways but I've been stuck on this for a while.
window['question'+i] = "some stuff";
var myWindow = window.open("", "Questions", "width=500,height=600");
myWindow.document.write(
question0 + ("<br>") +
question1 + ("<br>") +
question2 + ("<br>") +
question3 + ("<br>")
...
)
I recommend to not use different variables. Array's are made for these kind of things and provide functions to do this a lot easier. See this snippet below how to store the texts from a loop in an array and easy print it splitted by a <br> using the join function.
var values = new Array();
for (var i = 0; i < 10; i++) {
values.push("<span>value " + i + "</span>");
}
document.getElementById('result').innerHTML = values.join("<br>");
//If you really want to use document.write()
//document.write(values.join("<br>"));
<div id="result"></div>
This question already has answers here:
Escape double quote character in XML
(8 answers)
Closed 7 years ago.
I am working on a project where I am saving my data in xml format.I am unable to save double quotes in my data.I have tried replacing double quotes with " but it didn't worked.Please suggest how to achieve this.
Following is the xml data which I am passing
<question HasOptions="0" answer=""I think ki I am vulnerable"...text check // "i am afraid"" QuestionId="2042" OptionId="1260" ></question>
My javascript code for xml creation
function GetXMLForPosting() {
// here is the XML for posting
var xmlqQuestionResponse = '<question HasOptions="{{hasOptions}}" answer="{{score}}" QuestionId="{{questionID}}" OptionId="{{optionID}}" />';
var answers = '';
//lopping through questions
$('.little_text').each(function () {
// question data
hasOptions = $(this).attr('hasoptions');
questionID = $(this).attr('questionid');
// option data
selectedOption = $(this).find('input[name=radio_' + questionID + ']:checked');
score = $(selectedOption).attr('value');
optionID = $(selectedOption).attr('id');
// end
if (questionID > 0) {
if (hasOptions == 0) {
// case of textarea
// overiding default values
selectedOption = $(this).find('textarea[name=radio_' + questionID + ']');
score = $(selectedOption).val();
optionID = '1260';
answers = answers + xmlqQuestionResponse
.replace('{{hasOptions}}', hasOptions)
.replace('{{score}}', score.replace(/\'/g, "\'"))
.replace('{{questionID}}', questionID)
.replace('{{optionID}}', optionID);
}
else {
// normal radio button
answers = answers + xmlqQuestionResponse
.replace('{{hasOptions}}', hasOptions)
.replace('{{score}}', score)
.replace('{{questionID}}', questionID)
.replace('{{optionID}}', optionID);
}
}
});
//console.log('<questions>' + answers + '</questions>');
return '<questions>' + answers + '</questions>';
}
here my answer is coming in score option
My cs code
[HttpPost]
public ActionResult Postback(FormCollection formCollection)
{
// Process the take questionnaire
var model = (WorkflowMessage)Session[Enumerations.SessionItems.ViewModel];
// Check the page guid redirect accoringly
if (!GuidValid())
return ReshowPage();
var rawData = formCollection[Enumerations.FlashVariableFormPostKey.OutputData];
var enc = Encoding.GetEncoding("ISO-8859-1");
var responseXml = HttpUtility.UrlDecode(rawData, enc);
// redundant variable left so that at debug time the result can be inspected.
var result = new QuestionnaireService().SaveTakenQuestionnaire(PatientSessionDataObject.TreatmentId, model.PatientId, PatientSessionDataObject.CustomerId, model.AssetData, rawData);
return RedirectToAction("Next", "Treatment", new { navigationChosen = "Next", area = string.Empty, model.PageCheckGuid });
}
Please suggest how I can save text-"I think ki I am vulnerable"...text check // "i am afraid" in my answer field.Thanks
You need to use ".
For your example...
<question HasOptions="0" answer=""I think ki I am vulnerable"...text check // "i am afraid"" QuestionId="2042" OptionId="1260" ></question>
Is there a way to make a variable using an array value? For ex.
//Define all Notes in Sharps and Flats
var noteSharp = ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"];
var noteFlat = ["A","Bb","B","C","Db","D","Eb","E","F","Gb","G","Ab"];
//Make all Major Scales
for (var x=0; x<12; x++){
var noteSharp[x] + "Sharp" = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
var noteFlat[x] + "Flat" = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
If I do a console.log(CSharp) it says that CSharp is not defined.
In this example I am trying to define a total of 24 variables. Some variable name examples im expecting to get are ASharp , A#Sharp , BbFlat , DFlat. The CSharp and CFlat variable should both be "CDEFGAB"
If this is not possible is it because variables have to be defined before the javascript file is read by the browser at run-time for memory leak security.
If you want to make a global variable, attach it to window
window[variableNameHere] = itsValue;
In your case:
window[noteSharp[x] + "Sharp"] = noteSharp[x] + ...
But it's not good to pollute the global namespace. How about putting it in another namespace:
var sharps = {};
var flats = {};
sharps[noteSharp[x] + "Sharp"] = noteSharp[x]...
flats[noteFlat[x] + "Sharp"] = noteFlat[x]...
//access them
sharps.ASharp;
I quite can't figure out what your code does, but this solution should point you to the right direction.
try the following code
var noteSharp = ["A","B","C"];
for(i in noteSharp) {
window[noteSharp[i]] = 'value of '+noteSharp[i];
}
alert(A)
alert(B)
alert(C)
This is exactly what you want.
and rewriting it for your code
//Define all Notes in Sharps and Flats
var noteSharp = ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"];
var noteFlat = ["A","Bb","B","C","Db","D","Eb","E","F","Gb","G","Ab"];
//Make all Major Scales
for (var x=0; x<12; x++){
window[noteSharp[x] + "Sharp"] = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
window[noteFlat[x] + "Flat"] = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
alert(ASharp);
alert(AFlat);
As per my knowledge, in JavaScript there are 2 ways by which you can create dynamic variables:
eval Function
window object
eval:
var times = 1;
eval("var sum" + times + "=10;");
alert(sum1);
window object:
var times = 1;
window["sum" + times] = 10;
alert(window["sum1"]);
Change the end of your code to look like this:
for (var x=0; x<12; x++){
self[noteSharp[x] + "Sharp"] = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
self[noteFlat[x] + "Flat"] = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
As a result, you will have global variables with variable names like you want, such as CSharp, which would equal "CDEFGAB"--however, complicated variable names like A#Sharp cannot be written outright as variables, but can still be accessed by using subscript notation, like this self["A#Sharp"] (or window["A#Sharp"] in most cases, although it has traditionally been better style to use self rather than window to refer to the most local window object connected with a script instance).
The other answer looks like it has been finished out by the time I finished typing mine, and it looks good, too.
If this is not possible
It isn't for local variables without the use of eval.
is it because variables have to be defined before the javascript file is read by the browser at run-time for memory leak security.
No. It's not possible because ECMA-262 specifies that the only way to declare a variable is by a variable declaration statement, which is of the form:
var *identifier* [optional initialiser]
where identifier is a valid identifier, which can't be an expression like:
var 'foo' + 'bar';
The rest of the question has been covered in other answers.
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Get escaped URL parameter
(19 answers)
Closed 9 years ago.
I have this url index.html#secondPage?name=the%20second%20page
I want to get the value of name ("the second page") using javascript and jquery
thanks
You can use the code from the answers to this question. The only difference is that you want to parse the location.hash instead of location.search so just change that in whichever answer you choose to go with.
You'll also need to use substr to delete the leading # like:
var hash = window.location.hash.substr(1);
Here is the code from my answer to the question I linked to, with the modification:
function get_query(){
var url = location.hash.substr(1);
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
You can use it like:
var secondPage = get_query()['name']; // 'the second page'
Try like below, It will help you
Fiddle : http://jsfiddle.net/RYh7U/144/
Javascript :
function GetURLValue (sKey) {
return unescape("index.html#secondPage?name=the%20second%20page".replace(new RegExp("^(?:.*[&\\?]" + escape(sKey).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
alert(GetURLValue("name"));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Copying array by value in javascript
I am a beginner with javascript, so I would really appreciate any help or advice. I'm trying to get the values that I collect with my inputs array (that are put into a form, by the user, in the document) to set them to the words array. So, I would like inputs[0] = words[0], inputs[1] = words[1] etc. I thought by setting words to an empty array, and then to equal the index value of inputs, that I would achieve this, but it's not working. Words keeps showing up as "undefined".
function goMad() {
var words = [];
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length - 1; i++) {
inputs[i].value = words;
}
var story = words[0] + "! he said " + words[1] + " as he jumped into his convertible " + words[2] + " and drove off with his " + words[3] + " wife.";
document.getElementById("story").innerHTML = story;
console.log(words[0]);
}
Instead of this line:
inputs[i].value = words;
You can use:
words.push(inputs[i].value);
This will add the provided value to the words array. See the MDN docs.
As #pimvdb and #Shmiddty have pointed out you could also use the following. This would behave exactly the same as using push:
words[i] = inputs[i].value;