I'm basically trying to create a 'directions' form with each 'stop' having an address input and a couple of select-box options. I want to be able to 'swap' the forms so that the data from the first 'stop' is swapped with the data from the second 'stop'. The tricky part is that there could be more than two 'stops', so the swap would need to be able to handle swapping stops 3-4, 4-5, 5-6, etc.
Here is the basic form template:
<div class="forms">
<div class="address"><input type="text" /></div>
<div class="loc">
<select name="region">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="loc">
<select>
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
<option>e</option>
</select>
</div>
</div>
<div class="swap"><a>swap</a></div>
<div class="forms">
<div class="address"><input type="text" /></div>
<div class="loc">
<select name="region">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</开发者_开发知识库option>
</select>
</div>
<div class="loc">
<select>
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
<option>e</option>
</select>
</div>
I would like to use JQuery if possible, but am really stumped on how to get started.
Thanks, Brian
In general in jQuery you can just set the value of an input using .val()
and it'll figure it out depending on its form type (drop down, text input, textarea, etc).
Taking that into consideration along with your requirements for only swapping neighboring values, you can do something simply like this:
$('.swap a').click(function() {
//Swaps previous and next address values
var prevAddress = $(this).parent().prev('.forms').find('.address input');
var nextAddress = $(this).parent().next('.forms').find('.address input');
var tmp = prevAddress.val();
prevAddress.val(nextAddress.val());
nextAddress.val(tmp);
});
Here I've only done the address field, but it should be about the same for any of them.
The proof is in the fiddle.
This may not be the best way, but it answers your question: http://jsfiddle.net/PBfvX/
Note: 0-based indexing means if you want the first and second form, form1=0 and form2=1
精彩评论