What is the jquery equivalent to: document.forms[0].elements[i].value;?
I don't know how to travel through a form and its elements in jQuery and would like to know how to do it.
-
1Can you post an example of your markup, and which values you want to pull out?Nick Craver– Nick Craver2010年07月19日 22:38:27 +00:00Commented Jul 19, 2010 at 22:38
-
Read about how to select stuff here: api.jquery.com/category/selectors and about how to traverse here: api.jquery.com/category/traversing.karim79– karim792010年07月19日 22:50:07 +00:00Commented Jul 19, 2010 at 22:50
-
I wrote a basic form validation script in javascript, and I'm trying to transition it over to JQUERY. It's a for loop that searches through all of the elements in the from checking to make sure that all the values have changed form the default (ie. first name last name) to something real. The code snippet I posted is attached to a variable that saves the current input's value and checks it against the list of default values. thisVal = document.forms[0].elements[i].value;Ian– Ian2010年07月20日 05:17:07 +00:00Commented Jul 20, 2010 at 5:17
5 Answers 5
The usual translation is the :input selector:
$("form:first :input").each(function() {
alert($(this).val()); //alerts the value
});
The :first is because your example pulls the first <form>, if there's only one or you want all input elements, just take the :first off. The :input selector works for <input>, <select>, <textarea>...all the elements you typically care about here.
However, if we knew exactly what your goal is, there's probably a very simple way to achieve it. If you can post more info, like the HTML and what values you want to extract (or do something else with).
2 Comments
Well, translated literally, it'd be:
$('form:first *:nth-child(i)').val()
But jQuery makes it easy to grab elements by other manners such as ID or CSS selector. It'd be easier to maintain if you did something like:
$('form#id input.name').val()
Comments
$("#formid input").each(function(){
alert($(this).attr("value"))
})
1 Comment
input fields, not select or textarea.This will give you all elements under the form. Including non form elements:
$("#[form id]").find()
Then you can use an each function to traverse all the children. Or you can use the input selector to only return the form elements:
$("#[form id] :input")
I'm not exactly sure what you're trying to accomplish, but you should be able to do something like this:
$('form:first').children(':first').val();
This will get the value of the first child node within the first <form> tag in the DOM.
3 Comments
<form> tag :)elements[i], which translates pretty closely to: $('form:first :input').eq(i).val();