JQuery and Eval - javascript

First of all, lets say I have about 10 divs that are hidden and have the ID's as "modal1", "modal2", "modal3", etc... Using an ajax request, the data returned contains an ID number, lets say it is 7.
In previous tasks, I have used the javascript eval function but this does not work. I wish to append the received data to the correct modal div.
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
$(eval(ResponseDiv)).append(newdataobj.DataToAdd);
This doesn't work and the script stops working at this point. I have also tries using the JQuery version of eval, but that did not work either.

You don't need to use eval() here, use just $(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string and that is what you need for the selector.
Try this to confirm you have the right ID:
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
alert(ResponseDiv); // or console.log(ResponseDiv); - to doublecheck you have the right ID
$(ResponseDiv).append(newdataobj.DataToAdd);

ResponseDiv is already a string containing exactly what you want.
You don't want eval at all.

Related

How to Execute Javascript Code Using Variable in URL

I'm really new to Javascript and I'm having some trouble understanding how to get the following to work. My goal is to have a certain Javascript action execute when a page loads and a variable added to the end of the URL would trigger which Javascript action to execute. The URL of the page that I'm looking to implement this on is http://www.morgantoolandsupply.com/catalog.php. Each of the "+expand" buttons, which are Javascript driven, drop-down a certain area of the page. Ultimately, I would like to be able to create a URL that would automatically drop-down a certain category when the page loads. Could anybody explain to me the process to do this? Thanks in advance for any help!
You have to parse the URL somewhat "manually" since the parameters in the url aren't automatically passed to javascript, like they are in server-side scripting (via $_GET in PHP, for instance)
One way is to the use the URL fragment identifier, i.e. the "#something" bit that can go at the end. This is probably the neatest way of doing it, since the fragment isn't sent to the server, so it won't be confused with any other parameters
// window.location.hash is the fragment i.e. "#foo" in "example.com/page?blah=blah#foo"
if( window.location.hash ) {
// do something with the value of window.location.hash. First, to get rid of the "#"
// at the beginning, do this;
var value = window.location.hash.replace(/^#/,'');
// then, if for example value is "1", you can call
toggle2('toggle' + value , 'displayText' + value);
}
The URL "http://www.morgantoolandsupply.com/catalog.php#1" would thus automatically expand the "toggle1" element.
Alternatively, you can use a normal GET parameter (i.e. "?foo=bar")
var parameter = window.location.search.match(/\bexpand=([^&]+)/i);
if( parameter && parameter[1]) {
// do something with parameter[1], which is the value of the "expand" parameter
// I.e. if parameter[1] is "1", you could call
toggle2('toggle' + parameter[1] , 'displayText' + parameter[1]);
}
window.location.search contains the parameters, i.e. everything from the question mark to the end or to the URL fragment. If given the URL "example.com/page.php?expand=foo", the parameter[1] would equal "foo". So the URL "http://www.morgantoolandsupply.com/catalog.php?expand=1" would expand the "toggle1" element.
I'd perhaps go for something more descriptive than just a number in the URL, like, say use the title of the dropdown instead (so "#abrasives" or "expand=abrasives" instead of "#1" or "expand=1"), but that would require a little tweaking of your existing page, so leave that for later
You've already got the function to call: toggle2(), which takes two parameters that happen to be identical for all categories except for a number at the end. So create a URL that includes that number: http://www.morgantoolandsupply.com/catalog.php#cat=4
Then find that number in location.hash using a regular expression. This one is robust enough to handle multiple url parameters, should you decide to use them in the future: /[\#&]cat=(\d+)/. But, if you expect to never add anything else to the url, you could use a very simple one like /(\d+)/.
Once you've got the number, it's a simple matter of using that number to create your two parameters and calling toggle2().
This should work:
window.onload = function() {
if (/[\#&]cat=(\d+)/.test(location.hash)) {
var cat = parseInt(RegExp.$1);
if (cat > 0 && cat < 13) {
toggle2("toggle"+cat, "displayText"+cat);
}
}
}
Not a complete answer ("Give a man a fish" and all that), but you can start with something along these lines:
// entire URL
var fullURL = window.location.href;
// search string (from "?" onwards in, e.g., "www.test.com?something=123")
var queryString = window.location.search;
if (queryString.indexOf("someParameter") != -1) {
// do something
}
More info on window.location is available from the Mozilla Developer Network.
Having said that, given that you're talking about a PHP page why don't you use some server-side PHP to achieve the same result?

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

JavaScript/JQuery: use $(this) in a variable-name

I'm writing a jquery-plugin, that changes a css-value of certain elements on certain user-actions.
On other actions the css-value should be reseted to their initial value.
As I found no way to get the initial css-values back, I just created an array that stores all initial values in the beginning.
I did this with:
var initialCSSValue = new Array()
quite in the beginning of my plugin and later, in some kind of setup-loop where all my elements get accessed I used
initialCSSValue[$(this)] = parseInt($(this).css('<CSS-attribute>'));
This works very fine in Firefox.
However, I just found out, that IE (even v8) has problems with accessing the certain value again using
initialCSSValue[$(this)]
somewhere else in the code. I think this is due to the fact, that I use an object ($(this)) as a variable-name.
Is there a way arround this problem?
Thank you
Use $(this).data()
At first I was going to suggest using a combination of the ID and the attribute name, but every object might not have an ID. Instead, use the jQuery Data functions to attach the information directly to the element for easy, unique, access.
Do something like this (Where <CSS-attribute> is replaced with the css attribute name):
$(this).data('initial-<CSS-attribute>', parseInt( $(this).css('<CSS-attribute>') ) );
Then you can access it again like this:
$(this).data('initial-<CSS-attribute>');
Alternate way using data:
In your plugin, you could make a little helper function like this, if you wanted to avoid too much data usage:
var saveCSS = function (el, css_attribute ) {
var data = $(el).data('initial-css');
if(!data) data = {};
data[css_attribute] = $(el).css(css_attribute);
$(el).data('initial-css', data);
}
var readCSS = function (el, css_attribute) {
var data = $(el).data('initial-css');
if(data && data[css_attribute])
return data[css_attribute];
else
return "";
}
Indexing an array with a jQuery object seems fishy. I'd use the ID of the object to key the array.
initialCSSValue[$(this).attr("id")] = parseInt...
Oh please, don't do that... :)
Write some CSS and use the addClass and removeClass - it leaves the styles untouched afterwards.
if anybody wants to see the plugin in action, see it here:
http://www.sj-wien.at/leopoldstadt/zeug/marcel/slidlabel/jsproblem.html

Locating text and performing operation based on its existence

I'm trying to learn jQuery, but it's coming slowly as I really don't know any JavaScript.
My site is in VB.NET and I'm putting jQuery code on both my actual .ascx UserControl and in a separate file (something like myscripts.js). This is because I'm using webforms as I still don't know MVC well enough to implement it, so I have to get the clientID's on the page.
What I would like to do is the following:
Grab text from a textbox and make it all lowercase
Get the username from the login info. I've done this like so on my actual page:
var userName = "<%=Split(System.Web.HttpContext.Current.User.Identity.Name.ToLowerInvariant, '|')%>";
Check to see if the username is in the text. If it IS in the text, I want to set a variable to "false", othewise to true.
How do I do this?
I am completely ignorant of the ASP.NET side of it, but as far as jQuery and Javascript....
To get the value of a text field, you use the jQuery function val():
var value = $('#mytextbox').val();
To turn a string to lower case, you use the string method toLowerCase():
var value = $('#mytextbox').val().toLowerCase();
Since val() returns a string we can throw that at the end.
To check if a string is within another string, you use the string method indexOf():
var needle = 'Hello';
var haystack = 'Hello World';
var match = haystack.indexOf(needle); // -1 if no matches, 0 in this case
Another thing to remember is that ASP.NET renames all your control ID's. To access your controls in JavaScript, you should use the following in place of the Control ID <%= txtUserName.ClientID %>.
In jQuery, here is what my selector would look like for a textbox with the ID "txtUserName".
$('#<%= txtUserName.ClientID %>')
Enjoy,
Zach
var userName = "username as it comes out of your web app";
// stuff happens
var $myTextbox = $('#ID_of_textbox');
var userNameIsContained = $myTextbox.val().toLowerCase().indexOf(userName) >= 0;
Short explanation:
$('#ID_of_textbox') // fetches the jQuery object corresponding to your textbox
.val() // the jQuery function that gets the textbox value
.toLowerCase() // self explanatory
.indexOf() // returns the position of a string in a string (or -1)
See the JavaScript String object reference at w3schools.
Alternative (to check if the textbox value equals the username):
var userNameIsEqual = $myTextbox.val().toLowerCase() == userName;
The basics of JQuery are like so: Find a list of dom elements, and perform actions on them.
In your case, you should start off by finding the dom element that is your testbox. For example's sake, we'll choose $('#userName'). The selector # means "id" and together with the name "userName" it finds all elements with the id of "userName". (Ids on a page should be unique if you're following best practices.)
Once you have that list (in this case, a list of one element), you can ask it what the value is.
$('#userName').val()
This gets you the value of the value="" attribute of the input tag.
You can then assign it to a variable and use standard javascript String functions to do the rest!
function checkLogin(userName){
return $('#mytextbox').val().toLowerCase() == userName
}
if ($("#textBoxID").val()) != "") { /*Do stuff*/ }

Categories