Home » Jquery » javascript – Continuing list numbering (changing value of "start" for <ol>) based on previous list if radio is selected-Exceptionshub

javascript – Continuing list numbering (changing value of "start" for <ol>) based on previous list if radio is selected-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

Thanks for your help in advance – much appreciated!
I’m trying to give a user the ability to see continued list numbering based on their selection of a radio button, however I’m struggling to get it to work. I need it to count the “li” instances in the previous list, then change value of the next list’s “start” value if a “yes” radio button is selected.

HTML:

<div class="form-1">
<ol class="list-1" start="1">
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
</div>

<div class="form-2">
<form>
   <label>Start from 1?</label><br>
    <input type="radio" name="refresh-list" id="yes" value="yes"><label>Yes</label><br>
    <input type="radio" name="refresh-list" id="no" value="no"><label>No</label><br>
</form>
<ol class="list-2" start="">
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
</div>

And the jQuery:

var form1total = $(".form-1 ol").children("li").length;

$(".form-2 input[name=refresh-list]:radio").click(function () {
        if ($('input[value=yes]:checked')) {
            $('.form-2 ol').attr('start', form1total);
        } else {

        }
})

Thanks again!

How to&Answer:

You can simply use $(this).val() in your event handler to get the current state of the radio buttons, and if yes then set the start to the number of elements in the first list + 1, otherwise set it to 1:

var form1total = $(".form-1 ol").children("li").length;

$(".form-2 input[name=refresh-list]:radio").click(function() {
  if ($(this).val() == 'yes') {
    $('.form-2 ol').attr('start', form1total + 1);
  } else {
    $('.form-2 ol').attr('start', 1);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-1">
  <ol class="list-1" start="1">
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
  </ol>
</div>

<div class="form-2">
  <form>
    <label>Start from 1?</label><br>
    <input type="radio" name="refresh-list" id="yes" value="yes"><label>Yes</label><br>
    <input type="radio" name="refresh-list" id="no" value="no"><label>No</label><br>
  </form>
  <ol class="list-2" start="">
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
  </ol>
</div>