Can anyone tell me why this is not working?
var fieldsValid = {
registerUserName: false,
registerEmail: false,
registerPassword: false,
registerConfirmPassword: false
};
function showState () {
var str = "<p>registerUserName: " + fieldsValid[registerEmail] + "</p>" ;
document.getElementById('showstate').innerHTML = str;
}
showState();
There is no output into my div.
Use quotes around the property name because otherwise, registerEmail is treated as a variable containing the property name, not a property name:
var str = "<p>registerUserName: " + fieldsValid['registerEmail'] + "</p>" ;
Or use the . syntax without quotes:
var str = "<p>registerUserName: " + fieldsValid.registerEmail + "</p>" ;
MDN Working With Objects is a good resource, relevant to this.
For future debugging, observe the console (F12) in your browser.
Let's say you have someObject.
someObject[johndoe] Returns the item in someObject that has johndoe's value (since here it is a variable) as index.
Related
I have a function that takes 2 inputs, the variable name as a string and the variable itself - it prints both via console.
var variable1 = ["entry1","entry2"];
function logthis(input1, input2){
console.log(input1+ "\n " + input2)
}
logthis("variable1", variable1) ;
I want to be able to use it as logthis(variable1); and get the same result.
How can I reference the variable name (as a string) and not its contents?
eg, console.log(input2.name) will not work
Something like the C+ equivalent of "nameOf(variable1)"
var variable1 = ["entry1","entry2"];
function logthis(input1, input2){
console.log(input1+ "\n " + input2)
}
logthis('variable1', variable1) ;
You are sending the reference. Pass first argument as string.
Try to get your input from the table first
function logthis(inputTable){
var input1 = inputTable[0];
var input2 = inputTable[1];
console.log(input1+ "\n " + input2) // will display "entry1 \n entry2 "
}
var table1 = ["entry1","entry2"];
logthis(table1);
I have a function that I need to use for filtering table rows:
setFilterString("Filter");
But I have a problem. I can set it to
setFilterString("OrderID = 5");
and it will filter out row where OrderID is equal to 5 but if i try using a variable that has a value taken before like this
setFilterString("OrderID = vOrderID");
I get error "Invalid column name 'vOrderID'." (as vOrderID is variable and not a column, I guess)
I have seen somewhere in filter section inputting something like this ("OrderID = '" & vOrderID & "'") but it doesn't have any result at all for me. Doesn't even throw any error in the console.
JavaScript assumes you are just passing a string to the function. If you want to use the variable, you should try this:
setFilterString("OrderID = '" + vOrderID + "'"); // Results in OrderID = '5'
or
setFilterString("OrderID = " + vOrderID); // Results in OrderID = 5
depending on the body of your function.
Use + instead of &: setFilterString("OrderID = " + vOrderID) should work.
Use "+" for merge strings:
setFilterString("OrderID = " + vOrderID)
You can also try to use ${idvOrderID} inside string:
setFilterString("OrderID = ${vOrderID}")
Or:
setFilterString(sprintf("OrderID = %s", vOrderID))
Remember about difference between ' and "
I need to get field source from JSON but my solution not working !!
this is json:
"trailers":{
"quicktime":[],
"youtube":[{
"name":"BandeAnnonce",
"size":"HD",
"source":"RqEuaM9Fsrg",
"type":"Trailer"
}]
}
i try to get the source :var link_trailer = data.trailers[0].youtube[0].source;
but is not working for me !!
trailers is object, you don't need to use index.
var link_trailer = JSON.parse(data).trailers.youtube[0].source;
Try the following code
var text = '{' +
'"trailers": {' +
'"quicktime": [],' +
'"youtube": [{' +
'"name": "BandeAnnonce",' +
'"size": "HD",' +
'"source": "RqEuaM9Fsrg",' +
'"type": "Trailer"' +
'}]' +
'}' +
'}';
obj = JSON.parse(text);
var source = obj.trailers.youtube[0].source;
document.getElementById("demo").innerHTML ="Source field value is :"+source;
Here is the working jsfiddle:http://jsfiddle.net/NJMyD/5387/
Parse json into object first
var link_trailer = JSON.parse(data).trailers[0].youtube[0].source
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.
I am very new to learning both Javascript and Jquery.
In the website I am creating I am trying to insert a Javascript if statement and a for loop in a line of JQuery. The last confirm does not run. I suspect it is the if statement that is causing the issue. How can I fix this? Here is how my code looks like.
$(document).ready(function() {
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
confirm("You're last name is" + " " + lastname);
if (userResponse = "girl") {
for (var i = 0; i <= girlnames.length; i++) {
confirm("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
})
});
There's a lot that doesn't make much sense with your code.
First, what is userResponse? Where does this get defined and where is it set? Have you verified under a debugger that it is indeed equal to "girl"?
Second, you probably meant to use a comparison equals not an assignment equals here:
if (userResponse = "girl") { // This should be ==
However, this should not prevent the block from running. In fact, it will force the block to always run since "girl" is true-ish.
Third, what is girlnames? Is it an array? Where is this defined? Have you verified it indeed contains valid items?
Lastly, I believe your for loop is incorrect:
for (var i = 0; i <= girlnames.length; i++) {
Should be:
for (var i = 0; i < girlnames.length; i++) {
Arrays start at 0, thus girlnames[girlnames.length] is not a valid item.
However, considering you don't use the i variable in your loop anywhere, again this should not actually cause any errors.
I would step through your code line by line using a script debugger (usually F12 in modern browsers) and set a break point at:
var lastname = $('#lastnameresponse').val();
Then verified each line is behaving correctly. If that still doesn't work, you'll need to post more of your code so we can get a better idea of what's going on.
UPDATE:
Based on your comment:
Here is where the userResponse variable is defined:
$(document).ready(function(){ $("#girlimg").click(function() { var
userResponse = prompt("Confirm the gender you selected").toLowerCase;
$('html, body').animate({ scrollTop: $(".LastName").offset().top },
2000);
It seems that userResponse gets declared within the click handler for the #girlimg tag:
$("#girlimg").click(function() {
// Everything declared here is local to this function
var userResponse = confirm(); // local variable
});
Thus, it would not be accessible in the click handler for .button3. You'll need to declare userResponse in a scope that is accessible to both functions. Perhaps global (this is frowned upon in JavaScript) or within your $(document).ready() code, provided both click event handlers are defined within that block.
First: it's Your not You're :)
Secondly, userResponse is undefined. Maybe it's defined somewhere else.
For comparison, use == operator.
Are you sure is that what you want to do? I see you also have confirm there.
Use confirm like this:
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
// confirm() returns true or false, depending on the clicked button
is_confirmed = confirm("You're last name is" + " " +lastname);
if (true == is_confirmed) {
for (var i = 0; i <= girlnames.length; i++) {
confirm ("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
}
}
});
girlnames is also not defined here (maybe it's somewhere else). Same for random and randomagain
As for writing JavaScript "in" jQuery: there is no such question. jQuery is a library written in Javascript that provides useful functions to ease development.
Following statement does not contain a proper JavaScript Comparison Operator
equals is written ==
if (userResponse = "girl") {
for reference look here
you forgot to close some arrows, any way when you put :
if (userResponse ="girl"){...}
you set userResponse variable to "girl", and that passes the value to the variable only
to check in the userResponse is equal to "girl" you should put
if (userResponse =="girl")
your final code will look like this
$(document).ready(function(){
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
confirm("You're last name is" + " " +lastname);
if (userResponse ="girl") {
for (var i = 0; i <= girlnames.length; i++) {
confirm ("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
}}}
)
});
p.s:you forgot to close too many arrows