Eri*_* V. 4 jquery select css-selectors option
我不能让这个小脚本起作用:小提琴
我想使用按钮将所选选项从"多选"传递到另一个选项.我认为在尝试选择所有" option:selected" 时jQuery选择器存在问题.
HTML:
<div>
<select id='canselect_code' name='canselect_code' multiple>
<option value='1'>toto</option>
<option value='2'>titi</option>
</select>
<input type='button' id='btnRight_code' value=' > ' />
<br>
<input type='button' id='btnLeft_code' value=' < ' />
<select id='isselect_code' name='isselect_code' multiple>
<option value='3'>tata</option>
<option value='4'>tutu</option>
</select>
</div>
Run Code Online (Sandbox Code Playgroud)
JS
$('[id^=\"btnRight\"]').click(function (e) {
var selectedOpts = $(this).prev('select option:selected');
if (selectedOpts.length === 0) {
alert('Nothing to move.');
e.preventDefault();
} else {
$(this).next('select').append($(selectedOpts).clone());
$(selectedOpts).remove();
}
});
$('[id^=\"btnLeft\"]').click(function (e) {
var selectedOpts = $(this).next('select option:selected');
if (selectedOpts.length === 0) {
alert('Nothing to move.');
e.preventDefault();
} else {
$(this).prev('select').append($(selectedOpts).clone());
$(selectedOpts).remove();
}
});
Run Code Online (Sandbox Code Playgroud)
"_code"提到了我的应用程序中的动态代码,这就是为什么我使用[^selector]
直接id选择器之类的(#).
我设法让它工作将所有代码重写为整齐的一行.
JSFiddle :( 其他元素的MOVE选项) - http://jsfiddle.net/GJJQw/
JSFiddle :( 其他元素的COPY选项) - http://jsfiddle.net/dEE7A/
下面COPIES将选择元素编码到另一个选择框中.
$('[id^=\"btnRight\"]').click(function (e) {
$(this).prev('select').find('option:selected').clone().appendTo('#isselect_code');
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).next('select').find('option:selected').clone().appendTo('#canselect_code');
});
Run Code Online (Sandbox Code Playgroud)
如果你想MOVE(即从一个删除,并添加到另一个)..使用此:
$('[id^=\"btnRight\"]').click(function (e) {
$(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
});
Run Code Online (Sandbox Code Playgroud)
// the button that was clicked
$(this)
// .next('select') = get the next <select> element
.next('select').
// .find('option:selected') = get all the selected options
.find('option:selected')
// .remove() [or .clone()] = Remove or clone the found options
.remove() // OR .clone()
// .appendTo('#id-of-element') = Append the found elements to the other select box
.appendTo('#canselect_code');
Run Code Online (Sandbox Code Playgroud)
因此,通过更改为.remove()将.clone()您将选项复制到另一个选择,否则remove()将从此选择元素中删除它,并将其附加到另一个.
| 归档时间: |
|
| 查看次数: |
8423 次 |
| 最近记录: |