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

标签 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>

最佳答案

$('.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');
  });
});

关于javascript - 如何从文本输入中的复选框选择中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43724523/

相关文章:

javascript - 仅为输入日期最小/最大属性指定 YEAR 和 MONTH

javascript - 当输入类型 ="file"隐藏时,如何指示文件已被选择?

javascript - 访问对象数组的属性

javascript - firebase简单登录教程缺少用户

javascript - 将 jQuery 移动到 body 标记的末尾?

jquery - 在页面加载时添加类

c - 读取未知行数

javascript - Angular 中有主 Controller 好吗?

javascript - 元素仅在 Safari 10 中消失(9 没问题),当我更改任何 css 时显示

javascript - 将 Flex/Flash 交叉编译为 Javascript