如何从文本输入中的复选框选择中获取值

时间:2017-05-01 18:40:47

标签: javascript jquery input each

我正在尝试进行自定义输入,这将在输入中显示多个选项。我部分工作,但我似乎无法弄清楚如何在proposal-type输入中显示多个值。无论我选择什么,它只显示A的值。然后,如果选择了多个选项,它们就不会出现。

有人看到我做错了吗?

Here is a fiddle.

$('#proposal-type').click(function() {
  $('#proposal-type-drop').addClass('active');
});
$('.drop-item-input').on('change', function() {
  var typeVal = $('.drop-item-input').val();
  $('.drop-item-input').each(function() {
    if ($(this).is(":checked")) {
      console.log(typeVal);
      $('#proposal-type').val(typeVal).text(typeVal);
    };
  });
});
#proposal-type-drop {
	width: 45%;
	display: none;
	position: absolute;
}
#proposal-type-drop.active {
	background: rgba(0,0,0,1);
	display: block;
	height: auto;
	z-index: 1;
}
.drop-item {
	color: #FFF;
	font-size: .9rem;
	padding: 5px;
	background: #000;
	display: block;
	width: 100%;
	cursor: pointer;
}
.drop-item-input {
	display: none;
}
.proposal-text {
	width: 95%;
	display: block;
	height: 6em;
	margin: 1.5% 2% 2.5% 2%; !important
}
#proposal-check {
	display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panel-input">
  <input type="text" id="proposal-type" name="proposal_type" class="proposal-input" placeholder="Selection">
  <div id="proposal-type-drop">
    <label class="drop-item">A<input type="checkbox" class="drop-item-input" value="A"></label>
    <label class="drop-item">B<input type="checkbox" class="drop-item-input" value="B"></label>
    <label class="drop-item">C<input type="checkbox" class="drop-item-input" value="C"></label>
  </div>
</div>

2 个答案:

答案 0 :(得分:2)

$('.drop-item-input').on('change', function() {
  var proposalVal = "";
  $('.drop-item-input').each(function() {
    if ($(this).is(":checked")) {
    proposalVal += $(this).val();      
    };
    $('#proposal-type').val(proposalVal).text(proposalVal);
    $('#proposal-type-drop').removeClass('active');
  });
});

答案 1 :(得分:0)

$('#proposal-type').click(function() 
{
   $('#proposal-type-drop').addClass('active');
});
$('.drop-item').click(function() 
{
  var seleVal = [];
  $('.drop-item-input').each(function()
    {
      if ($(this).is(':checked'))
        {
          seleVal.push($(this).val());
        }
    })
  $('#proposal-type').val(seleVal.join(','));
});