繁体   English   中英

单击单选按钮时,将值附加到 div 并在单击另一个单选按钮时从 div 中删除

[英]On click radio button append value to div and remove from div when another radio button is clicked

基本上,我试图在单击时将单选按钮值附加到 div。 这可以正常工作,但是在单击另一个单选按钮时我似乎无法清除 div。

div 中应该只有 1 条附加数据。

我尝试在附加值之前使用 innerHTML 清除 div,但似乎不起作用

 $('input[type="radio"]').one('click', function () { var getVal = $(this).val(); if ($('.selections').text().length < 0) { console.log('less than'); } else if ($('.selections').text().length > 0){ console.log('more than'); $('.selections').innerHTML = ""; $('.selections').append(getVal); } console.log(getVal); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <label> <span class="radio-c"> <input type="radio" name="q1" value="Between £381K and £450K" id="between381"> Between £381K and £450K </span> </label> <label> <span class="radio-c"> <input type="radio" name="q1" value="Over £450K" id="over450"> Over £450K </span> </label> </form> <div class="selections"> </div>

使用 vanilla JS 时使用innerHTML 您应该在 jQuery 引用的对象上使用text() 您也不需要在此处附加。

我也相信你错误地使用了.one() ,它应该是.on()

 $('input[type="radio"]').on('click', function () { var getVal = $(this).val(); if ($('.selections').text().length < 0) { //console.log('less than'); } else if ($('.selections').text().length > 0){ //console.log('more than'); $('.selections').text(getVal); } //console.log(getVal); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <label> <span class="radio-c"> <input type="radio" name="q1" value="Between £381K and £450K" id="between381"> Between £381K and £450K </span> </label> <label> <span class="radio-c"> <input type="radio" name="q1" value="Over £450K" id="over450"> Over £450K </span> </label> </form> <div class="selections"> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM