How To Swap Values In Select Lists With Jquery?
I have two simple select lists and want to add an option to swap values in them. So, there is the first list with e. g. value 'ONE' and the other list has value 'TWO'. When you cli
Solution 1:
Something like this will work:
$("#SwapButton").click(function(e) {
e.preventDefault();//This prevents the A tag from causing a page reload//Get the valuesvar fromVal = $("#form-item-from option:selected").val();
var fromText = $("#form-item-from option:selected").text();
var toVal = $("#form-item-to option:selected").val();
var toText = $("#form-item-to option:selected").text();
//Set the values
$("#form-item-from option:selected").val(toVal);
$("#form-item-from option:selected").text(toText);
$("#form-item-to option:selected").val(fromVal);
$("#form-item-to option:selected").text(fromText);
});
NOTE: This will only switch the option
items that are selected. If this is not what you want then I have misunderstood and you may be better to use Adam's solution. Here is a better example that illustrates the fact it only swap the selected values.
Solution 2:
Try something like this: jsfiddle
When you click on the link... 1) save all the options in #form-item-from into a variable 2) save all the options in #from-item-to into a variable 3) update #from with the options from #to 4) update #to with the options from #from
$(function() {
$("a").click(function() {
var selectOne = $("#form-item-from").html();
var selectTwo = $("#form-item-to").html();
$("#form-item-from").html(selectTwo);
$("#form-item-to").html(selectOne);
// stops the link going anywherereturnfalse;
});
});
Solution 3:
Try this,
$("a").click(function(e){
e.preventDefault();
var a = jQuery("#form-item-from").html();
var b = jQuery("#form-item-to").html();
jQuery("#form-item-from").html(b);
jQuery("#form-item-to").html(a);
})
Post a Comment for "How To Swap Values In Select Lists With Jquery?"