我想编辑选项文字和值选择。
<select id="sel">
<option value="Option one">Option one</option>
<option value="Option two">Option two</option>
<option value="Option three">Option three</option>
<option value="Option four">Option four</option>
</select>
$("#sel").select2({
width: 400,
tags: true
});
我们之所以选择Option one
,我想将其编辑为First Option
,包括文字和值。我该怎么做?
看起来应该是
<select id="sel">
<option value="First option">First option</option>
<option value="Option two">Option two</option>
<option value="Option three">Option three</option>
<option value="Option four">Option four</option>
</select>
像这样的东西。
在tEST
之后tEDT EDIT
之前是fs.readFile(req.files.displayImage.path, function (err, data) {
// ...
var newPath = __dirname + "/uploads/uploadedFileName";
fs.writeFile(newPath, data, function (err) {
res.redirect("back");
});
});
,所有这些我都想用select2的输入
答案 0 :(得分:1)
您可以使用内置更改事件,如下所示:
$("#sel").select2({
width: 400,
tags: true
}).on("change", function (e) {
var elem = $("#sel");
if( elem.val() == "Option one" ){
$('#sel option:contains("Option one")').val('First option').text('First option');
elem.select2("destroy");
elem.select2({
width: 400,
tags: true
});
}
});
答案 1 :(得分:1)
我已经解决了我的问题
var s = $("#sel").select2({
tags: true,
closeOnSelect: false,
width: 400,
});
var $search = s.data('select2').dropdown.$search || $el.data('select2').selection.$search;
s.on("select2:selecting", function(e) {
$search.val(e.params.args.data.text);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" />
<select id="sel">
<option value="Option one">Option one</option>
<option value="Option two">Option two</option>
<option value="Option three">Option three</option>
<option value="Option four">Option four</option>
</select>
&#13;
答案 2 :(得分:0)
试试这个:
$('#sel').click(function() {
var selectedOption = $(this).children("option").filter(":selected");
if (selectedOption.val() === 'Option one') {
selectedOption.text('First Option');
selectedOption.attr('value', 'First option');
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="Option one">Option one</option>
<option value="Option two" selected="1">Option two</option>
<option value="Option three">Option three</option>
<option value="Option four">Option four</option>
</select>
&#13;