I'm not getting the same result when I use JQuery vs javascript functions.
This is the HTML
<form id="testform">
<div id="FormContainerID"></div>
<input type="button" id="y" value="Button" />
<div id="ListContainerID"></div>
</form>
Here is the Javascript
01 var Form = document.getElementById('y').form;
02 //var Form = $('#y').closest('form');
03 alert(Form);
When Activating row 1, I get a legal form object. The Alert says "object HTMLFormElement" and everything works fine.
But if I use row 02 instead, Alert says "object Object" and then I ofcourse get errors becaus it isn't a real Form object.
Why is JQuery not returning the correct Object?
I get the same result with Chrome and IE8.
[EDIT]
I'm using JQuery version: jquery-1.5.1.min
[SOLUTION]
Thank you for clearing this up. I Changed the code to:
var Form = $('#'+fChildID).closest('form')[0];
...and now it works as a charm.
Vivek Goel was the first to answer, so creds to him. I voted up you other guys that explained the JQuery instance model.
Thank you.
jQuery returns a jQuery instance when you use it to look things up, not the raw DOM element. The jQuery instance is a wrapper around the set of matched elements, and allows you to apply set-based operations to the elements. This is one of the absolute fundamentals of using jQuery.
You can also access the raw elements if you like using array-like notation — [0], [1], etc., up to .length - 1. So in your case, since you're getting just one element, it would be Form[0]. If your code matched multiple form elements, it would be Form[1] for the second one, Form[2] for the third one, etc. (Using the [] notation is surprisingly hard to find in the documentation, though, one of the gaps in my view; in the old days you used the get method, but you only need that now if you're using its special handling for negative indexes.)
You frequently don't need to access the raw elements at all. You haven't said what you're going to do with the form once you have it, but if you were to (say) submit it, just call the submit function on the jQuery instance, and it will submit the form. If you wanted to get an attribute from it, there's the attr jQuery function (so for instance, val = Form.attr("action")).
jQuery is very set-based, but it's assymetrical, which feels weird at first but works fairly well in practice. When getting a value, functions usually get the value from the first matched element only. When setting a value, functions usually set it on all the matched elements.
This is because the jquery statement is returning a jquery object and not a form object.
You need something like Form[0] to access the form element.
with jquery use
alert(Form[0]);
http://jsfiddle.net/dvCtr/
Try
var form = $("#y").parent
this should return the parent of yin the DOM tree
Related
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})
});
This has driven me "doo-lally" this afternoon!
A vendor (Zaxaa) uses a multi-dimentional form thus:
<form method="post" name="zaxaa" action="xxxx">
<input type="text" name="products[0][prod_name]" value="ABC">
<input type="text" name="products[0][prod_type]" id="pt" value="FRONTEND">
</form>
** This is my understanfing of how a multdimentional array is set up, and it seems to pass the variables to the server OK.
However, dependant on what other inputs are set to on the test form, the [prod_type] (and others) may need to change to "OTO" This is obviously going to be a javascript function, (but not the variant that starts with "$" on code lines ... whatever that type is!)
I have tried
document.zaxaa.products[0].prod_type.value
document.getElementById('products[0][prod_type]').value
document.getElementsByName('products[0][prod_type]').value
but in everycase, I get "products is not defined". (I have simplified the form as there are ten product[0] fields)
I've solved it... mainly a glaring error on my part. The getElementById worked fine ... except in my test script I'd used getElementById[xxx] and not getElementById(xxx)!! ie "[" rather than "(" Does help if you get the syntax right!
But I will take notice of those other methods, such as enclosing both array arguments in ["xxx"].
getElementById didn't work because the only one of those elements that has an id is the second input, with id="pt".
On any modern browser, you can use querySelector to get a list of the inputs using a CSS selector:
var nameInput = document.querySelector('input[name="products[0][prod_name]"]');
var typeInput = document.querySelector('input[name="products[0][prod_type]"]');
Then use their value property. So for instance, to set the name to "OTO":
document.querySelector('input[name="products[0][prod_name]"]').value = "OTO";
Use querySelectorAll if you need a list of relevant inputs, e.g.:
var nameInputs = document.querySelectorAll('input[name="products[0][prod_name]"]');
Then loop through them as needed (the list as a length, and you access elements via [n] where n is 0 to length - 1).
Re
* This is my understanfing of how a multdimentional array is set up...
All that HTML does is define input elements with a name property. That name property is sent to the server as-is, repeated as necessary if you have more than one field with that name. Anything turning them into an array for you is server-side, unrelated to JavaScript on the client. (The [0] is unusual, I'm used to seeing simply [], e.g name="products[][prod_name]".)
You can access it in this syntax:
document.zaxaa['products[0][prod_name]'].value
document.zaxaa.products[0].prod_type.value
The name is a single string, not making a nested structure to access the input. It would need to be
document.zaxaa["products[0][prod_type]"].value
// or better:
document.forms.zaxaa.elements["products[0][prod_type]"].value
The complicated name does only serve to parse the data into a (multidimensional) array on the server side, but all data will be sent "flattened".
document.getElementById('products[0][prod_type]').value
The id of your input is pt, so this should work as well:
document.getElementById("pt").value
document.getElementsByName('products[0][prod_type]').value
getElementsByName does return a collection of multiple elements - which does not have a .value property itself. Instead, access the first element in the collection (or iterate it completely):
document.getElementsByName('products[0][prod_type]')[0].value
I need to use the 1.3.2 library which unfortunately does not support the last functionality. This causes my function to fail:
$op.last().next().after($op);
"$op.last is not a function"
Demo:
http://jsfiddle.net/uscyH/
I have been unsuccessful at rewriting this functionality in pure js, any suggestions? Note, I will also need the .first(), but I'm assuming I will be able to extrapolate that from the .last alternate code. Many thanks-
You can use the :last selector, which existed since 1.0:
$op.filter(':last')
To get the last element, do this:
$op.slice( -1 )
Live demo: http://jsfiddle.net/uscyH/4/
The jQuery .slice() method is patterned after the JavaScript .slice()
method for arrays. One of the features that it mimics is the ability
for negative numbers to be passed as either the start or end
parameter. If a negative number is provided, this indicates a position
starting from the end of the set, rather than the beginning.
Source: http://api.jquery.com/slice/
To get the first element do this:
$op.eq( 0 )
Live demo: http://jsfiddle.net/uscyH/5/
Assuming $op is the collection of options, get the first DOM element in the collection using:
var first = $op[0];
and the last using:
var last = $op[$op.length-1];
It looks like you could find the last or first item with this method
http://jsfiddle.net/uscyH/3/
alert("Last is: "+$("option:last").html()+" and first is: "+$("option:first").html());
Update: Looks like you have lots of ideas to choose from now. Feel free to use whatever approach you would like. This approach is probably not the fastest one since it is doing two DOM queries instead of operating on the list you already appear to have stored in an array. It's nice to see how jQuery has been so powerful even back in these versions. Thanks for the ideas everyone!
$($op[$op.length-1]).next().after($op);
You can also choose to extend jquery and create your own last method.
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.
I have an array I've created in JavaScript. The end result comes out to element1,element2,,,element5,element6,,,element9.... etc
Once passed to ColdFusion, it removes the null elements, I end up with element1,element2,element5,element6,element9
I need to maintain these spaces, any ideas? My problem may begin before this, to explain in more detail...
I have a form with 13 elements that are acting as a search/filter type function. I want to "post" with AJAX, in essence, i'm using a button to call a jQuery function and want to pass the fields to a ColdFusion page, then have the results passed back. The JavaScript array may not even be my best option.
Any ideas?
Are you deserializing the jS array into a list? CF ignores empty list fields using its built-in functions. This can be worked around by processing the text directly. Someone has already done this for you, fortunately. There are several functions at cflib.org, like:
ListFix
ListLenIncNulls
etc, etc, etc.
In exchanging data between javascript and coldfusion have a look at using JSON.
http://www.json.org
http://www.epiphantastic.com/cfjson/
Instead of using the CF ListToArray function, use the Java String methods to split the string into an array. This will maintain the empty list items.
<cfset jsList = "item1,item2,,item4,item5,,item6">
<cfset jsArray = jsList.split(",")>
<cfdump var="#jsArray#">
you are using array in JavaScript,Fine. instead of assigning by default empty value,assign some dummy value. whenever you use this array value ignore dummy value using condition.