簡體   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