what can be the alternative for $('form')[0]? - javascript

I am using $('form')[0] in following syntax
var formData = new FormData($('form')[0]);
I have following question regarding above syntax
What is the meaning of $('form')[0]?
Main Question: what can be the alternative for $('form')[0]? i have 2 forms in page

The meaning of this is the following:
find all elements on the page with the tag name form and take the first one.
If you want to take the second one just do $('form')[1]
Alternatives could be: .get(0) or .first(), also I do not see a reason for doing this, because in my opinion all of them are kind of straightforward. Although actually .first returns jquery element, not DOM element.

What is the meaning of $('form')[0]?
This gets first form among your forms. If you want to get second from the you could do $('form')[1].
what can be the alternative for $('form')[0]?
There is various methods but what if there are many forms in your document and want to get some of them but you don't need to worry about the order of the form. You can get them by name like this: $('form')['your_form_name]
If you want to use vanilla javascript then you can do any of the followings to get the forms:
document.forms[0] //gets first form
document.forms[1] //gets second form
document.forms['form_name'] //get form which has name == form_name
document.forms.form_name //get form which has name == form_name
document.form_name //get form which has name == form_name
And if you google about this you may know more info.

$('form')[0] gives the reference of the first form element in your
document.
If you want to refer form specifically you can give an ID to it and get reference using $("#formID")

$('form')[0] returns the first for element in the page, $('form') returns a jQuery object which is not accepted by FormData, the jQuery object allows you to access its members using index, so [0] gives you the first element in the jQuery object, it is the same as $('form').get(0)
If you have multiple elements then you need to give an id or class to the form and use it as a selector like <form id="x"></form>, so you can use $('#x')[0]

meaning of $('form')[0] is that if you have n forms in your page this selector will gather data of first form.
and if you want to get rid of this way coding give an Id to your forms and then select each form by its id.

1). $('form') is a jQuery instance which is an array like object with numeric indexes. You can access the first element from a collection with square brackets, by index 0.
2). Alternatively you can give form a name and access it with pure Javascript by name:
document.formName
or there is a froms property of the document that stores references to all HTMLFormElement elements. So your jQuery code is equivalent to
document.forms[0]

Related

Cannot find labels with that class

Hi I have an array called "arrayRestado1" from which I want to extract the first element and save that value in the value property of an html input. If it extracts the value but, it does not find the input with that class so the input does not show anything.
The code is in JavaScript:
const col1_f1 = document.getElementsByClassName("col1_f1").value = arrayRestado1[0]
console.log(col1_f1)
the function document.getElementsByClassName() returns an array of elements (an HTML Collection to be correct), not only a single DOM element.
Here's the documentation: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
So with your current code you could try this:
const col1_f1 = document.getElementsByClassName("col1_f1")[0].value = arrayRestado1[0]
console.log(col1_f1)
See the [0] after the function? This means we want the first element of the array. Doesn't matter if there is only one with the given class name col1_f1.
Otherwise you could give your inputs/elemets specific (unique) ids and then use the document.getElementById() function to get them as single elements "directly" in the first place.
More on that here: https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Have a good day!
Nico

meteor template array of html objects

I'm trying to work out how best to handle an input form that is for order processing that basically has a number of identical lines on it for ordering items of clothing.
The controls are all drop down selectors (4 different ones to a line).
At the moment I've just give each one a unique ID and am working through them one by one, but that strikes me as very inefficient.
Is there some way I can use a loop in the html (I don't think this can be done) or some other way to use an array of controls and just iterate over them on the form submit?
Meteor projects usually include jQuery. jQuery is pretty useful for grabbing groups of elements and running them through a function so that you don't have to repeat yourself as much.
In addition to unique ids, you can add the same class to all or a group of the form elements, and then in the onSubmit callback grab them all with a class selector in jQuery and send them all to a function that combines them into a useful object, e.g.
// collect the form inputs in class salesform into an object
var formResult = {};
$(".salesform").each(function(el){ formResult[$(this)[0].id]=$(this).val() });
// form ids and values are now in formResult
There may also be other selectors you can use instead of tagging the elements you want with a class.

querySelectorAll to find matching data-attribute

My app uses a Parse backend to keep a running list of all the concerts in my area that my friends and I are interested in.
On the main page I use a parse query display a module for each show stored in the database. As each module is created, I use this code to add a data attribute to the show's outermost div, corresponding to the show's object ID in parse:
var showId = object.id;
$("div.show_module:last").data("showId", showId);
I'm successfully able to retrieve the showId of a specific show when the user clicks on the show's module:
$("#showsList").delegate(".showModuleBody", "click", function() {
var storeObjectId = $(this).closest("div.show_module").data("showId");
});
That all works great, proving that assigning the data-attribute is working.
Where I'm running into trouble is trying to find an element with a specific data attribute or a specific value for that attribute on a given page. The end goal is to get the y-offset of that div so I can scroll the page to the appropriate spot. I assumed I could use the following code to find the element, but it isn't working -
// find all elements with class .show_module
var allShows = document.querySelectorAll('.show_module');
// find all elements with showId data attribute
var showsWithShowId = document.querySelectorAll('[data-showId]');
// find all elements with a specific showId data attribute
var showToFind = document.querySelectorAll("[data-showId='2']");
The first of those 3 works, proving that all the elements I'm interested in are loaded into the page by the time I'm calling this function, but the 2nd and 3rd queries return nothing.
Any idea what I'm doing wrong here? Is it something with syntax? Is querySelectorAll just incompatible with how I'm setting the data attribute?
I tried to include only what I figured are the salient bits of code, but if more is necessary please let me know.
Try This
$('*[data-customerID="22"]');
For more info, look here:
Selecting element by data attribute
jQuery's .data method does not create a HTML attribute, but associates a value in its internal data store with the element.
If you want to set a data attribute with jQuery, then you need to use:
$("div.show_module:last").attr("data-showId", showId);
To get the value, you can use .data('showId') or .attr('data-showId').
(note that HTML attributes are case-insensitive, so you can also write "data-showid" instead.)

How to get multiple "listKey" values from a Struts 2 <s:select>?

I have a code like this:
<s:select id="s" list="list" listKey="id" listValue="displayValue">
When I get the value from the object I'll always get the id.
How can I change the "listKey" value dinamically so I could get for example, the name of the object (supposing other of my attributes besides id is name ) instead always de id?
I was trying some code in jQuery like this:
function changeListKey(){
var id = $("#s").val();
$('#s').attr('listKey','name');
var name = $("#s").val();
document.write(name); // Only to test if I could get the value
}
When I execute it it doesn't seem to change the "lisKey" value so I could get another one, what would be the solution?
Thanks a lot in advance.
John Smith.
Why would you want to mix up what's used as the key value? That would make a mess on the server side.
In any case, listKey isn't an HTML attribute, it's a custom tag attribute, and is meaningless after the HTML has been rendered and sent to the client. You would need to iterate over the HTML select element's options collection and change the values on the options.
All this said, you'd be much better off doing any bizarre manipulations like this in the action itself, and exposing only the desired key/value pairs to the JSP, either in a list, or more easily, in a map. Using a map eliminates the need to provide listKey/listValue attributes--just use the map's key as the option text, and the value as the option's value.

How to get added token id, name list from the jquery-tokeninput plugin via Javascript?

How can I get the id, name value pairs of the tokens (entered by a user) via Javascript from the jquery-tokeninput plugin found here? https://github.com/loopj/jquery-tokeninput
Is it just me or isnt it surprising that this plugin has a lot of features except a straight forward getEnteredTokens() method?
Thanks in advance.
I know this is kind of late coming, but have you tried:
selector.tokenInput("get");
for example:
var selectedValues = $('#myinputbox').tokenInput("get");
(where selector is whatever jQuery selector you need to return the tokeninput input object)
It returns all of the currently selected id/name values in an object.

Categories

Resources