I am using jQuery selector to get the values of all CMS components on the page using $('div.cmscomponent') but how can I test this to see if am actually getting the list of compoents on the page.
I use:
var temp = $('div.cmscomponent');
alert(temp);
and result that I get is [object OBJECT] and so how can I test this ? and how can I get values of the object and its properties.
$() returns a jQuery wrapper object, whose contents is usually a list of DOM elements, along with properties and methods that apply to those elements.
If you want to get an element, you can access them using array-style indexes or the get() method:
alert(temp[0].tagName); // Fetch the first element, alert the `tagName`
alert(temp.get(1).tagName); // Fetch second element, alert the tagName
To check to see how many elements the result contains, you can use .length, just like you would on an array or collection/nodelist:
alert(temp.length); // Alerts number of elements found.
Here is a javascrip include that will enable you to view object structure and information.
EX: dump(temp, true);
http://www.netgrow.com.au/files/javascript_dump.cfm
Well it depends on what you want to know about the matched objects. Some examples:
var temp = $('div.cmscomponent');
alert(temp.length); // number of matched elements
// Alert each id attribute of every matched element
$(temp).each(function(index) {
alert(index + ': ' + $(this).attr("id"));
});
var temp = $('div.cmscomponent').length;
alert(temp);
If by "how can I test this", you meant "how can I write a unit test for this?", the answer is that you shouldn't. You didn't write jQuery, so you should assume it's already been unit-tested. (If there were a problem with jQuery, though, you can write integration tests would catch this.)
On the other hand, if you meant "how can I sanity-check what jQuery is telling me to make sure I didn't goof on the inputs?", there are a few ways:
Check that .length matches the expected number of items.
Check that an XPath query for the same nodes ("//div[#class='cmscomponent']") returns the same number of values.
Check that the content of the Nth node matches what you expect.
Otherwise, it's probably best to use a third-party tool like Firebug.
If all you want to do is test if your code is doing what you expect, Firebug is your friend here. It will give you a console to type a command like $('div.cmscomponent') and then interactively explore the results that are returned by it.
You can then mouseover each item that your command returned and it will be highlighted on the page, so you can see which item the command returned, and if those items are the ones you expected/wanted.
Related
I am using CKEditor. Within my page, the user can dynamically add/remove the element containing the WYSIWYG ckeditor text editor.
CKEDITOR.instances returns an object which contains within it all the ck_editor objects on my page.
When the user clicks the add button, then the following code successfully grabs that element:
CKEDITOR.instances[“my_textarea_0_body"]
The issue is when the user clicks delete to remove that element, and then reclicks add. I now want to grab that new ckeditor element on the page. However, now I need to grab it with this:
CKEDITOR.instances[“my_textarea_1_body"]
Notice that the number changed. So, the user is able to toggle the add/remove of this element any number of times. Example: if they did it 100 times I would need to have a way to grab that object like so:
CKEDITOR.instances[“my_textarea_100_body"]
The problem is that I never know what that number will be. That number is vital for me to create the string in order to grab the appropriate object.
Question: How can I grab this dynamically labeled object that is contained within the CKEDITOR.instances object? I know that my desired object will always be the LAST object appended within that CKEDITOR.instances object.
I assume that CKEDITOR.instancess a kind of a map (dictionary), so you can get all key names by Object.keys(). And then select the last/first/ or n-th instance name.
var mapping_length = Object.keys(CKEDITOR.instances).length;
var object_label = Object.keys(CKEDITOR.instances)[mapping_length - 1];
CKEDITOR.instances[object_label];
This will return the desired object from within that dictionary object.
Regex indeed is your friend here. /^CKEDITOR\.instances\["my_textarea_\d+_body"\]$/.test(str) should get the job done. (if you copy and paste any of your initial examples to test, it will fail however since you've got an angled quote illegal character in there)
console.log(/^CKEDITOR\.instances\["my_textarea_\d+_body"\]$/.test('CKEDITOR.instances["my_textarea_0_body"]'))
I think I understand what you're getting at though - you know the vague structure of the key, but not exactly what it will be when you're trying to retrieve it. In that case, you'd want to search through the keys of the CKEDITOR.instances object for any that match that pattern. So, let matchingKeys = Object.keys(CKEDITOR.instances).filter(key => /^my_textarea_\d+_body$/.test(key)). That will return a set of all keys that match that pattern.
You can create a helper function which checks for a regex match. The regex for that field should be:
my_textarea_\d+_body
Then you can modify/add the new object key to instances
Suppose I have a div tag like this:
<div id="group-dialog" class="modal-dialog">
Now I want to grab it as a jQuery object (in this case so I can run .dialog()).
When I try this:
var gDialog = $('#group-dialog');
I get an array back (!!).
Why am I getting an array? Isn't the point of having an ID attribute that there's only one? I can see getting multiple p's or .my-css-thing back ...
Next question:
I have this array with 1 object in it that I now want to access as a jQuery object.
When I do this:
$(gDialog[0])
And pull it up in F12, I still have an array!! I thought I de-referenced the array already by picking the first element.
This doesn't seem to help either:
var gDialog = $('#group-dialog:first');
This is basic, but I run into this problem a lot. It seems like it used to be a lot simpler!
What is the best way to access this DOM element as a jQuery object?
Answer 1
jQuery selectors always return arrays.
Selection with id attribute is a particular use case and ideally the result should be unique. However, there is nothing preventing you from having duplicated ids in a HTML document (although this is bad practice).
Answer 2
The following code will get you the first element as a DOM object:
var gDialog = $('#group-dialog')[0];
Note: you may want to check the size of the return array first.
As far as I know, there is no way to transform this DOM element back to a jQuery object. The standard use case would be to directly used $('#group-dialog') and asume that it is found and unique.
Try using .get(). Though I'm not sure it will work with dialog()
Retrieve the DOM elements matched by the jQuery object.
var gDialog = $('#group-dialog').get();
If you're trying to grab it to use it on a dialog, you can just put
$(document).ready(function(){
$('#group-dialog').dialog({put options here})
});
I'm displaying elements from an arraylist in table on the webpage. I want to make sure that once the user press "delete the data", the element in the table is immediately removed so the user does not have to refresh and wait to see the new table. So I'm currently doing it by removing the element from the arraylist, below is the code:
$scope.list= function(Id) {
var position = $scope.list.indexOf(fooCollection.findElementById({Id:Id}));
fooCollection.delete({Id:Id});
if (position>-1) {
$scope.list.splice(position,1);
}
$location.path('/list');
};
But I the position is always -1, so the last item is always removed from the list no matter which element I delete.
I found it strange you we're operating on two different lists to begin with so I assumed you were taking a copy of the initial list. This enabled me to reproduce your bug. On the following line you're trying to find an object that isn't present in your list.
var position = $scope.list.indexOf(fooCollection.findElementById({Id:Id}));
Eventhough we're talking about the same content, these two objects are not the same because:
indexOf compares searchElement to elements of the Array using strict
equality (the same method used by the ===, or triple-equals,
operator).
So there lies your problem. You can see this reproduced on this plunker.
Fixing it the quick way would mean looping over your $scope.list and finding out which element actually has the id that is being passed.
you can use the splice method of javascript which takes two paramete
arrayObject.splice(param1, param2);
param1 -> from this index elements will start removing
param2 -> no of elements will be remove
like if you want to remove only first element and your array object is arrayObject then we can write code as following
arrayObject.splice(0, 1);
I'm trying to get the values of all selected checkboxes with the following code to insert them in a textarea.
$('input[name="user"]:checked').each(function(){
parent.setSelectedGroup($(this).val()+ "\n");
});
but i always get only one value.
How to write the code in a correct way to get the value of ALL selected checkboxes?
Thanks ahead!
EDIT
1) "parent" because the checkboxes are in a fancybox.iframe.
2) setSelectedGroup in the parent window is
function setSelectedGroup(groupText){
$('#users').val(groupText);
You are getting all the values, simply on each loop through the collection you're passing a new value to setSelectedGroup. I assume that method replaces content rather than appending so you are simply not seeing it happen because its too fast.
parent.setSelectedGroup(
//select elements as a jquery matching set
$('[name="user"]:checked')
//get the value of each one and return as an array wrapped in jquery
//the signature of `.map` is callback( (index in the matching set), item)
.map(function(idx, el){ return $(el).val() })
//We're done with jquery, we just want a simple array so remove the jquery wrapper
.toArray()
//so that we can join all the elements in the array around a new line
.join('\n')
);
should do it.
A few other notes:
There's no reason to specify an input selector and a name attribute, usually name attributes are only used with the input/select/textarea series of elements.
I would also avoid writing to the DOM inside of a loop. Besides it being better technique to modify state fewer times, it tends to be worse for performance as the browser will have to do layout calculations on each pass through the loop.
I strongly recommend almost always selecting the parent element for the parts of the page that you're concerned with. And passing it through as the context parameter for jquery selectors. This will help you scope your html changes and not accidentally modify things in other parts of the page.
I am trying to make a page work for my website using the mootools framework. I have looked everywhere I can think of for answers as to why this isn't working, but have come up empty.
I want to populate several arrays with different data types from the html, and then, by calling elements from each array by index number, dynamically link and control those elements within functions. I was testing the simple snippet of code below in mootools jsfiddle utility. Trying to call an element from array "region" directly returns "undefined" and trying to return the index number of an element returns the null value of "-1".
I cannot get useful data out of this array. I can think of three possible reasons why, but cannot figure out how to identify what is really happening here:
1. Perhaps this array is not being populated with any data at all.
2. Perhaps it is being populated, but I am misunderstanding what sort of data is gotten by "document.getElementBytag()" and therefore, the data cannot be displayed with the "document.writeln()" statement. (Or am I forced to slavishly create all my arrays?)
3. Perhaps the problem is that an array created in this way is not indexed. (Or is there something I could do to index this array?)
html:
<div>Florida Virginia</div>
<div>California Nevada</div>
<div>Ohio Indiana</div>
<div>New York Massachussetts</div>
<div>Oregon Washington</div>
js:
var region = $$('div');
document.writeln(region[2]);
document.writeln(region.indexOf('Ohio Indiana'));
Thanks for helping a js newbie figure out what is going on in the guts of this array.
$$ will return a list of DOM elements. If you are only interested in the text of those DOM nodes, then extract that bit out first. As #Dimitar pointed out in the comments, calling get on an object of Elements will return an array possibly by iterating over each element in the collection and getting the property in question.
var region = $$('div').get('text');
console.log(region[2]); // Ohio Indiana
console.log(region.indexOf('Ohio Indiana')); // 2
Also use, console.log instead of document.writeln or document.write, reason being that calling this function will clear the entire document and replace it with whatever string was passed in.
See an example.