2

Suppose I have the following HTML.

<div id="bookmarksList">
  <label class="container">
    <input type="radio" name="bookmark" id="b1"
        onclick="onClicked(this);" checked="checked">
    <span class="radioTitle">2014</span>
  </label>
  <label class="container">
    <input type="radio" name="bookmark" id="b2"
        onclick="onClicked(this);" checked="checked">
    <span class="radioTitle">2015</span>
  </label> //So on upto 10
</div>

in onClicked() function, I want to change the color of the checked checkbox's label to red.

I want to do this using jQuery's find() method, but it is giving undefined

$("#bookmarksList").find("input[type=radio]").each(() => {
  console.log(this.id);
});

OR

$("#bookmarksList").find("label > input[type=radio]").each(() => {
  console.log(this.id);
});

How should I do it? Thank you.

Parth Mangukiya
  • 434
  • 3
  • 13

3 Answers3

1

Does it work right? I mean there no need JS.

function onClicked(id) {
  console.log(id)
}
input:checked+label {
  background-color: green
}
<div id="bookmarksList">
  <input type="radio" name="bookmark" id="b1"
      onclick="onClicked(this.id)" checked>
  <label for "b1">
    <span class="radioTitle">2014</span>
  </label>
  <input type="radio" name="bookmark" id="b2"
      onclick="onClicked(this.id)">
  <label for "b1">
    <span class="radioTitle">2015</span>
  </label>
</div>
Dima Vak
  • 599
  • 5
  • 20
1

You can get the ids of the inputs like this:

$(document).ready(function() {
  $("#bookmarksList input[type=radio]").each(function() {
    console.log(this.id);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="bookmarksList">
  <label class="container">
    <input type="radio" name="bookmark" id="b1" onclick="onClicked(this);" checked="checked">
    <span class="radioTitle">2014</span>
  </label>
  
  <label class="container">
    <input type="radio" name="bookmark" id="b2" onclick="onClicked(this);" checked="checked">
    <span class="radioTitle">2015</span>
  </label>
</div>
tanmay_garg
  • 377
  • 1
  • 13
1

Try it with a normal function, instead of an arrow function here, then it should work. This worked for me:

$("#bookmarksList").find("input[type=radio]").each(function() {
        console.log(this.id);
});

But anyway, I would suggest to also do a class for your inputs you want to fetch via jQuery, then you can just get it normal via $('yourClass').each(function() {....} or if you only want to get your elements w/ this class inside your #bookmarksList div: $('#bookmarkslist .yourClass').each(function() {....}

Andreas Rainer
  • 314
  • 4
  • 16