When I want to redirect, the variable where is always udefined. But, for example, I want put that variable in alert(); it shows correct number.
code
var where = msg.txt;
window.location = "/page.php?id=".where; //this redirects to /page.php?id=undefined
alert(where); //it show correct number
It should be:
window.location = "/page.php?id=" + where;
You have:
"/page.php?id=".where;
Which tries to retrieve a where property of a string, and such has not been defined.
In JavaScript, . is used for property access, not for string concatenation like in PHP.
Use + instead:
window.location = "/page.php?id=" + where;
Related
I was wondering if it is possible to create variable names from parameters passed to a function in javascript. Something like this:
function createVar(number) {
var "number" + number;
}
createVar(1)
I'm new to Stack Overflow and programming, so any help would be appreciated.
You could attach this to the window object, but note it will be global. For example:
function createVar(varName, value) {
window[varName] = value;
}
createVar("test", "Hello World");
alert(test); // Outputs "Hello World".
It is possible to interpret Object as associative array where you specify index and get value by name of index ( hash ):
var x = Array();
x[number] = value;
Single variable name is for programmer, and the code would be hard to maintain and understand when you set variable dynamically in code.
Honestly, I don't see why this would ever be useful, because every time you want to use the variable you'd have to search for it with your number argument.
However, you can do it, albeit not the exact way you had described:
function createVar(number){
eval("var number" + number.toString() + ";");
}
however, this variable will only be accessible within the function, to make it global assign to the window object:
function createVar(number){
window["number" + number] = 15; // creates "global" variable
}
As I've stated before, however, I don't see this being useful, [i]ever[/i], if you want to stratify values by numbers you'd be much better off with an array.
I am making a div and in its onclick function I am calling function Remove() to which I am passing its id and name. But when I use name in my remove function, an undefined error is thrown. For example, I call Remove(1,xyz) and then in the Remove function I am unable to access xyz; it's showing me xyz is not defined.
Here is my jQuery code which calls the Remove function:
$("#h2-"+id).append("<div id = 'c2-"+id+"' onclick = 'Remove("+id+","+name+")' class='clear_btn1'> </div>");
and here is my Remove function:
function Remove(i, name){
alert("I am deleting " +name);
var sender = "<?php echo $user_check?>";
var receiver = name;
console.log("Name is " +sender);
console.log("receiver is " +receiver);
}
The value of i is coming perfectly fine but I cannot access name in my function.
Change your code as below
$("#h2-"+id).append("<div id = 'c2-"+id+"' onclick = \"Remove("+id+",'"+name+"')\" class='clear_btn1'>sdfsdf sdfsdf</div>");
What is saved in onclick is actually Remove(id,name). This looks okay at first look, but...
Say id=10 and name="Mark".
You would be calling Remove(10,Mark), which is not what you want. Mark would be treated as a variable. You therefore need to put additional quotes enclosing name to treat it as a string.
You should, of course, escape the additional quotes you would add.
You need to call Remove(10,"Mark"). Notice the quotes.
I have the following function (which I didn't write) to extract a URL parameter value:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
I have virtually no experience with regular expressions. This code currently does a case sensitive search for the parameter name. I'd like to have RegExp do a case insensitive search for the name of the parameter. Could someone show me how I might change this to accomplish that?
Add i flag for regexp(more info):
new RegExp('your regexp', 'i')
Here's something that I've been using that may help, as I need to do something very similar to pull down a substring of the current page's URL to then pass into a variable to be used in several of my functions.
Here's the generic format of my URLs:
file:///Users/myname/folder/teamname.html
And here's what how I'm parsing them:
function parseURL() {
var match = window.location.href.match(/(\w+).html$/);
if (match) {
return match[1];
}
return null;
}
This will do this:
1) Check the URL for the current page
2) Parse the URL into two different fragments of an array: "teamname" and "html"
3) I then return match[1] which is "teamname"
How I'm using it:
From there, I declare a variable for the parseURL function like this:
var teamSched = parseURL();
So now, I can make dynamic calls for any page with the same URL syntax I've outlined above to have specific code executed with the page-specific variable from parseURL(). Then, I use that variable to generate unique datasets from objects in my code who's key match the "team name" variable created by parseURL().
Someone definitely correct me if I'm wrong, but case sensitivity shouldn't be a factor here, as long as the value you're pulling from your URL via parseURL matched the variable, object key, etc. you're trying to access.
I hope that helps!
I'm trying to create a page that allows for the multiple upload of images, this requires different name attributes. To achieve this, I'm using JS to add one the variable i giving a number.
The below code returns NaN, I'm not too sure why?
$('document').ready(function() {
var i = 1;
$('#new-dialogue').click(function() {
var i = i + 1;
$('.create-upload').append('<div class="upload"><input type="file" name="image' + i + '"/></div>');
});
});
Remove the second var.
What your current code is saying, is what when new-dialogue is clicked, it should create a variable called i and set it to i+1... but because i hasn't been defined yet in this scope you are doing undefined + 1, which is NaN.
Removing the second var will cause the click function to get the i variable from the containing scope, which is what you want it to do. You can then just have i++ to increment it as needed.
That said, you could just make your life easier by using:
<input type="file" name="image[]" />
Because on the server side, you will then have an array of uploaded files ;)
Instead of
var i = i + 1;
Just do
i++;
You need to increment already declared variable, not re-declare it again.
When you redeclared i local to the callback, your function got its own local copy of i that had yet to receive a value. So var i = i + 1; is basically var i = undefined + 1;, which evaluates to NaN.
Get rid of the var to fix this.
How to shift between variable names in jQuery and change them?
//predefined variables
var s1='';
var d2='';
//trying to change variables by .attr() parameter but no luck
$('body').on('click','span', function() {
var $(this).parent().attr('data-scan')=$(this).attr('id');
});
HTML
<div data-scan="s1"><span id="banana">Banana</span><span id="apple">Apple</span></div>
<div data-scan="d2"><span id="orange">Orange</span><span id="apple">Apple</span></div>
How can I change specific variables? I do't care about changing attr papameter, all I need is changing predefined global var parameters!
You are using wrong syntax of attr()
Syntax: attr( attributeName , value)
Change
var $(this).parent().attr('data-scan')=$(this).attr('id');
To
$(this).closest('div').attr('data-scan',$(this).attr('id'));
You code would be
Live Demo
$('body').on('click','span', function() {
debugger
$(this).closest('div').attr('data-scan',$(this).attr('id'));
s1=$(this).closest('div').attr('data-scan');
alert(s1);
});
Firstly, your html for the data-scan attributes is wrong, you have no closing quotes.
Secondly, you can the data() jquery function to access data attributes.
Thirdly, you cannot set values by using the = operator.
You want something like this:
$(this).parent().data('scan', $(this).attr('id'));
or, without the data() function:
$(this).parent().attr('data-scan', $(this).attr('id'));
Here is a working example
To get the value you can do one of the following:
var dataScan = $(this).parent().data('scan');
or
var dataScan = $(this).parent().attr('data-scan');
Your exact requirements for setting a variable based on the data-scan value
Based on your comments and code, I think it has not been clear what you were trying to do. I think I have worked it out though and you want to use the data-scan value to determine which global variable should be set...
//predefined variables
var s1='';
var d2='';
$('body').on('click','span', function() {
var variableType = $(this).parent().data('scan');
var valueToSet = $(this).attr('id');
if(variableType == "s1"){
s1 = valueToSet;
}
else if(variableType == "d2"){
d2 = valueToSet;
}
});
Here is an example of what I think you are trying to do.
However, if you have lots of variables then it is not ideal to use so many if/else statements. So you could use the javascript eval() function.
var variableType = $(this).parent().data('scan');
var valueToSet = $(this).attr('id');
eval("" + variableType + " = '" + valueToSet + "';");
See here for an example
But be careful the your eval code is subjected to user injected values (not that javascript is safe from users anyway)
You're pretty close!
// set
$('#item').attr('data-scan', 'set new value');
// get
var dataScan = $('#item').attr('data-scan');
console.log(dataScan); //=> set new value
Probably best if you use .prop() rather than .attr()
$(this).parent().prop('data-scan', $(this).attr('id') );
As the jQuery api documentation states
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.