Reputation: 513
This is an example code,
<select id="select1">
<option value="1">Option 1 </option>
<option value="2">Option 2 </option>
<option value="3">Option 3 </option>
<option value="4">Option 4 </option>
</select>
<input type="text" id="input1"/>
<select id="select2">
<option value="1">Option 1 </option>
<option value="2">Option 2 </option>
<option value="3">Option 3 </option>
<option value="4">Option 4 </option>
</select>
<input type="text" id="input2"/>
My question is, let say I use jQuery to grab an input field, i.e. $("#input1"), how can I grab the previous form element without hard coding? In this case it is $("#select1"), I dont want to manually travel through the DOM with prev(),parent(),children(), etc., because my form structure can change in the future (like add fieldset, td, tr, etc.)
Thank you for helping me!
Upvotes: 1
Views: 4624
Reputation: 5161
Not a easy way on this. You could write a small plugin to do the job:
$.fn.previousFormElement = function () {
var element = this[0],
$formElements = $("input, select, textarea"),
previousFormElementIndex = $formElements.index(element) - 1;
return $formElements.eq(previousFormElementIndex);
};
See the Fiddle with a running example. I should note that this only works if you call the previousFormElement
on an element that satisfies the selector "input, select, textarea"
. An added bonus is that if you run the plugin on the first form element on the page, it gives you the last.
Upvotes: -1
Reputation: 207901
Use jQuery's .prev() method, but specify the elements you want it to look for, in your case other form fields.
$("#input1").prev('select,input,textarea');
As the documentation for .prev() says:
The method optionally accepts a selector expression of the same type that can be passed to the $() function. If the selector is supplied, the preceding element will be filtered by testing whether it match the selector.
Upvotes: 0
Reputation: 5269
Not a problem.
//pass in the id of the current input
function selectPrev(input) {
//find parent form, then get all descendant input-type elements
var inputs = $("#" + input).parents("form").find("input,select,textarea");
var prev = -1;
//loop through list of inputs to find current input
inputs.each(function(i, el) {
//select previous input once current is found
if (el.id == input) prev += i;
})
return inputs[prev];
}
Upvotes: 1
Reputation: 218732
use the jquery prev()
method
$("#input1").prev();
will return the select element before the input
Sample : http://jsfiddle.net/m8Tst/1/
you can use the length property to check whether the previous element exist before accessing that.
Upvotes: 2