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

Viewed 262

Basically, I'm trying to append a radio button value to a div on click. This works as it should, but I can't seem to clear the div when clicking another radio button.

There should only ever be 1 piece of appended data within the div.

I tried to clear the div with innerHTML before appending the value but doesn't seem to work

$('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>

1 Answers

innerHTML is used when using vanilla JS. You should use text() on jQuery referenced object. You also do not need to append here.

I also believe you have mistakenly used .one(), which should be .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>

Related