Javascript: Can't get element using $('id') - javascript

I want to access a object by using $('id'), but cannot success.
here's my code :
function jumptopage(myOffset, mySilder, table) { // javascript
...
var oPageSlice = $(recordsPageName); // -> stop
var myURL = $("jumptourl").value; // -> -> stop
...
}
The program always stops at that two lines.
recordsPageName is 'records_page', and both "jumptourl" & 'records_page'
are really exist.
I can use
"var oPageSlice = document.getElementById(recordsPageName);"
to replace
"var oPageSlice = $(recordsPageName);"
And it will work.
But I still want to find the reason.
p.s. The problem also can be reproduced in the following .
It seems the same issue in my php code.
html[] = '<input type="button"
onClick="setPerPageRecs($(\''.$this->aName['records_page'].'\')...'
In this situation, setPerPageRecs doesn't be called when i click the button
it seems that $(\''.$this->aName['records_page'].'\' doesn't correspond
to the object.

You need to add # to get a element by id. like this:
$("#id");

Look at Selector #ID. It lacks the # to select an ID
$("#jumptourl").val();

you missed # character to get element by id and use val() instead of value:
$("#jumptourl").val()
---^
to access by class use $('.elementClass')

I presume $("jumptourl") is meant to be referencing an id or a class?
You need to use a . for a class, or a # for an id.
E.g.
$(".jumptourl") or $("#jumptourl")

Related

.addClass() not working

This is my first time working with .addClass().
In my project, I need to display notifications on a dummy phone screen (an image of iPhone). A notification has a title and some description. This title and description is coming from a form on the same webpage. To compose this notification, I am doing:
var notificationText = $('#title').val().addClass('title') + plainText.addClass("description");
However, I am getting an error:
TypeError: $(...).val(...).addClass is not a function
What am I doing wrong here?
UPDATE:
So, as per the overwhelming requests, I did:
var notificationText = $('#title').addClass('title').val() + plainText.addClass("description");
However, I am getting an error:
Uncaught TypeError: Object sss has no method 'addClass'
jsFiddle
UPDATE 2: I do not need to style the description, so I removed the class related to it. Please see my updated fiddle. Now the problem is that the text in title is getting bold instead of the one copied in #notifications. It is not getting styled as per the CSS.
So many answers in so little time... sigh
I gathered what I think you wanted. Try this one:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/7b3j2/13/
$(document).ready(function(){
CKEDITOR.replace( 'description' );
$('#title').focus();
$('form').submit(function(event){
event.preventDefault();
var html=CKEDITOR.instances.description.getSnapshot();
var divEle=document.createElement("DIV");
divEle.innerHTML=html;
var plainText=(divEle.textContent || divEle.innerText);
var $title = $('<span></span');
$title.addClass('title');
$title.text($('#title').val());
var $desc = $('<span></span');
$desc.addClass('description');
$desc.text(plainText);
$('form').append($title);
$('form').append($desc);
});
});
You can obviously chain some of the span operations, but I left them readable for now. Shorter version would look like:
var $title = $('<span></span').addClass('title').text($('#title').val());
var $desc = $('<span></span').addClass('description').text(plainText);
$('form').append($title).append($desc);
As you probably know by now, but for completeness, the initial errors were the result of trying to apply jQuery methods to string objects. This solution creates new jQuery span objects that can then be styled and appended to the form.
You are trying add class to a value, which is definitely is not a jQuery object
Try this instead:
$('#title').addClass('title').val()
addClass can only be performed on jQuery objects and returns a jQuery object - that's what makes it chainable. You can't add a class to a string.
So, in this code, there are actually two mistakes:
1) plainText.addClass - plainText is a string, and not a jQuery object. You must add the class to the element you created (in your case, the divEle element), but, since addClass only works with jQuery objects, you must convert your div to a jQuery element first. You can accomplish this by doing the following:
$(divEle).addClass('description');
2) addClass returns a jQuery object, so you can't concatenate it with a string.
EDIT: Just realized that you're appending notificationText (which is a string) to the DOM. You must convert it to a div and add the div to the DOM.
jsFiddle: http://jsfiddle.net/7b3j2/17/
Mistake done by you:
<div id="title"><div>
$('#title').val().addClass('title')
->Now here $('#title').val() will give that particular element value.
->$('#title').val().addClass() you are adding class to that value.
Use this:
$('#title').addClass();
As you cannot add class to element's value.
You should addClass to particular element as addClass internally will add attribute class to that element.
So finally solution becomes:
$('#title').addClass('title').val()
For adding a class, you have to use
$('#title').addClass('title');
If you want to get the value, you can use
$('#title').addClass('title').val()
While addClass and val() are both methods on the jQuery object, val() is not chainable like addClass is. When you do $('#title').val() you aren't returning the object, you're only returning the string value of the element.
Use this instead:
$('#title').addClass('title');
And if you still need to get the value:
$('#title').addClass('title').val();
The reason why plaintext is producing an error is because you're trying to use the jQuery addClass method on a DOM node that has been natively created with document.createElement("DIV");. This will not work. To get it to work you either need to to define your new element with jQuery:
var divEle = $('<div></div>');
and then add the class:
divEle.addClass('description');
Or use the native classname method to add the class to the DOM node:
divEle.className = divEle.className + " description";
Try putting addClass first
$('#title').addClass('title');
Update
To get the code fully working you should split up the line like so.
var notificationText = $('#title').val() + ' ' + plainText;
$('#title').addClass('title');
$(plainText).addClass("description");
Fiddle
Final Update
So what we actually want to do here is:
get the values of the content
append them on submit and style the appended text
Example
// Get the text.
var notificationText = $('#title').val() + ' ' + plainText;
// Append to form.
$('form').append('<span class="summary">' + notificationText + '</span>');
// CSS styling
.summary {
display:block;
font-weight: bold;
}
See Fiddle
Considering #title is the id of the element.
You can directly need to add classname to it.
$('#title').addClass('className');
where className is the name of the class.
because you are trying to add class over value instead of element.
$('#title').val().addClass('title') //it is wrong
replace it with:
$('#title').addClass('title')
if plainText is not an element object you initialize by
var plainText = $('#anotherId');
will also cause this error.

JQuery and Eval

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.

How to change split sign from html element with jQuery

I have some h3 element:
<h3>Data Performance</h3>
I need to change it to class name: data_performance.
So i do this but something is wrong, can anybody tell me what?
var $product_name = $('.subpage_promo.top').find('h3').text().toLowerCase(),
$product_name_mod = $product_name.split(' ').replace('_');
Thx for help.
You can do this using below code.
var $product_name = $('h3').html().toLowerCase(),
$product_name_mod = $product_name.replace(' ','_');
Demo
You're not implementing replace correctly. Its syntax is:
str.replace(regexp|substr, newSubStr|function)
It should be executed on a string (you're passing an array of strings), and it should specify both what to search for and what to replace it with (you're currently passing only what should be the second argument):
$product_name_mod = $product_name.replace(/ /g,'_');
The code above uses a regex, only to be able to specify the global flag, which is required in order to replace every space with an underscore. If you know you'll always have just one, .replace(' ','_') should do.
$('h3').addClass(product_name.replace(/ /g,'_'));
DEMO

'div_element' is null or not an object in IE7

Here I have get one error in JavaScript div_element is null or not an object.
I have given my code below:
function showLoading(id) {
div_element = $("div#" + id)[0];
div_element.innerHTML = loading_anim; // Error in this line
}
When I am debugging my script but it's working fine in other browsers including IE 8, but it's not working in IE 7. I don't understand what exact issue occur in this script.
First of all, you dont need to put a tag name infront of the jQuery, unless you have other elements with exact same id on other elements, in other pages.
Next, your statement div_element.innerHTML = loading_anim; is correct. So, the only explanation is that, there is no element with that ID, in the DOM.
Finally, since you are usign jQuery already, no need to mix up native JS and jQuery to create a dirty looking code.
function showLoading(id) {
div_element = $("#" + id);
console.log(div_element); //check the console to see if it return any element or not
div_element.html(loading_anim);
}
I think you don't select anything with your jquery selector (line 2)
try to display
id
"div#" + id
$("div#" + id)
$("div#" + id)[0]
You can use firebug javascript console or a simple alert like this:
alert($("div#" + id)[0]);
And see if you must id or class on your div ( use # or . selector)
I suppose, that nic wants to display some loader GIF animation, I confirm, that nic must use jQuery .html() method for DOM objects, and tusar solution works fine on IE6+ browsers. Also (it is obvious but anyway) nic must assign a value to loading_anim variable in script, lets say: var loading_anim = $('#loader').html(); before assigning its value to div_element.
Use .html() for jQuery objects. innerHTML work for dom objects, they wont work for jQuery objects.
function showLoading(id) {
div_element = $("div#" + id);
$(div_element).html(loading_anim); // Provided `loading_anim` is valid html element
}

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!

Categories