select - 如何使用jquery对所选选项的值求和?

时间:2016-08-01 13:44:54

标签: javascript php jquery html

如何汇总多个属性中的选择选项?知道可能是什么问题吗?

    $(document).ready(function() { $('#btn-add').click(function(){
    $('#select-from option:selected').each( function() {
            $('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        $(this).remove();
    });
});
$('#btn-remove').click(function(){
    $('#select-to option:selected').each( function() {
        $('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        $(this).remove();
    });

});

 $('.select-from option:selected').change(function() {
 var total = 0 ;
  $('.select-to option:selected').each(function() {
      total += parseInt($(this).value());
  });
               $("input[name=class]").value(total);  }); });

我有多个选择列表选项

<select name="selectfrom" id="select-from" multiple size="5">
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
  <option value="3">Item 3</option>
  <option value="4">Item 4</option>
</select>

<a href="JavaScript:void(0);" id="btn-add">Add &raquo;</a>
<a href="JavaScript:void(0);" id="btn-remove">&laquo; Remove</a>

<select name="selectto" id="select-to" multiple size="5">
</select>    <input type="text" name="class" value="" /> 

2 个答案:

答案 0 :(得分:0)

您使用.value()代替.val()

total += parseInt($(this).value());更改为total += parseInt($(this).val());,将$("input[name=class]").value(total);更改为$("input[name=class]").val(total);

答案 1 :(得分:0)

请尝试以下代码。

&#13;
&#13;
$(document).ready(function() { 
  
$('#btn-add').click(function(){
    $('#select-from option:selected').each( function() {
            $('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        $("input[name='class']").val(parseInt($(this).val()) + parseInt($("input[name='class']").val()));
    });
});
$('#btn-remove').click(function(){
    $('#select-to option:selected').each( function() {
        $('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        $(this).remove();
        $("input[name='class']").val(parseInt($("input[name='class']").val() - parseInt($(this).val())));
    });

});
  
 });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selectfrom" id="select-from" multiple size="5">
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
  <option value="3">Item 3</option>
  <option value="4">Item 4</option>
</select>

<a href="JavaScript:void(0);" id="btn-add">Add &raquo;</a>
<a href="JavaScript:void(0);" id="btn-remove">&laquo; Remove</a>

<select name="selectto" id="select-to" multiple size="5">
</select>    <input type="text" name="class" value="0" />
&#13;
&#13;
&#13;