取消选择选项后删除值

时间:2020-01-21 18:49:38

标签: javascript jquery html

编辑::我要实现的目标是获取每个option text而不是value,因此可以将其发送到API。从选择中获取文本效果很好。当我再次从input value中取消选择某个选项时,我想将其删除。例如,如果我选择多个,则会得到Medit-4-packs, Swiss-Gear-Bag,当我一一单击它时,它将删除它,但是当我取消选择多个时,会得到另一个值。我想像往常一样取消选择时将值替换为空。希望有助于澄清

使用jquery从输入值中取消选择选项的任何帮助吗?这些是我到目前为止尝试过的。感谢您的帮助

取消选择选项后,尝试删除<input>中的值。

<input class="form-check-input" type="text" value="" id="equipment" name="equipmentitems" >

 <select multiple class="image-picker show-labels show-html" data-limit="16"  name="packages[]" id="group_psoft">
<option value=" " data-img-class="first" selected></option>
<option data-img-src="/images/" data-img-label="Scanner Tips(4Pcs)" name="packs" data-img-alt="KeepSame" value="400" >Medit-4-packs</option>
<option data-img-src="/images/" data-img-label="SwissGear Bag" name="bagoriginal" data-img-alt="Aggresive" value="200"> Swiss-Gear-Bag</option> 
</select>

Js

$('.image-picker').imagepicker({
   show_label: true,
   limit: 15,

//This is setting the text in the input
   selected: function($items) {
     $('#equipment').val($(this).find('option:selected').text());
   },

// Here I want to remove it if clicked again
   changed: function(){
      $('#equipment').val($(this).unbind('option:selected').text()); // This removes it but add all the other options text in the input

 $('#equipment').val($(this).unbind('option:selected').val( )); // Here It removes it but I get the value of the next selected option. 

     $('#equipment').val($(this).unbind('option:selected').text(' ' )); This I get Js [object,object]

   }

});



2 个答案:

答案 0 :(得分:0)

当我将代码移到函数外部时,我解决了它。我也将unbind()更改为on()方法。

$('.image-picker').on('change', function() {
  $('#equipment').val($(this).find('option:selected').text());

});

答案 1 :(得分:-1)

尝试一下,看看是否可行。

$('.image-picker').imagepicker({
   show_label: true,
   limit: 15,

//This is setting the text in the input
   selected: function($items) {
     $('#equipment').val($(this).find('option:selected').text());
   },

// Here I want to remove it if clicked again
   changed: function(){
      var equiValue = $('#equipment').val();
      var selectedValue = $(this).find('option:selected').text();
      if(equiValue === selectedValue) {
        $('#equipment').val("");
      }

   }

});