0

I have two custom styled radio buttons that look like below [just an example]

li {
  width: 100px;
  border: 1px solid black;
  display: inline-block;
}
<ul>
  <li>
    <input type="radio" name="radio-test" id="radio1">
    <div>
      <label for="radio1">Radio One</label>
    </div>
  </li>
  <li>
    <input type="radio" name="radio-test" id="radio2">
    <div>
      <label for="radio2">Radio Two</label>
    </div>
  </li>
</ul>

Once this has been made to look prettier, I would ideally want that clicking anywhere inside the box enclosing a radio button should trigger activation of that choice.

My team mates have used custom styles and images to show selection and hence I do not want to modify CSS.

I was trying to think of a way to implement mentioned functionality with Javascript.

Attack a click event-handler on the li and trigger a click on the underlying input but that causes an infinite recursion of event triggers.

This raised 2 questions in my mind:

  1. Is there a way to stop the the click recursion? I tried preventDefault and stopPropagation on the JS triggered click but they do not seem to accomplish what I want.

  2. Can we user JavaScript(or jQuery if needed) to differentiate between a real mouse click and a JS triggered click event?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Sinstein
  • 887
  • 11
  • 42

1 Answers1

0

You were on the right track. You just need to stop the propagation from the input back up to the list item:

$('li').click(function() {
  $(this).find('input').click()
})
$('input').click(function(e) {
  e.stopPropagation();
})
li {
  width: 100px;
  border: 1px solid black;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>
    <input type="radio" name="radio-test" id="radio1">
    <div>
      <label for="radio1">Radio One</label>
    </div>
  </li>
  <li>
    <input type="radio" name="radio-test" id="radio2">
    <div>
      <label for="radio2">Radio Two</label>
    </div>
  </li>
</ul>
j08691
  • 204,283
  • 31
  • 260
  • 272
  • This sure does what I want :) Just for curiosity, do you have an answer for the 2nd question I had? Is it possible? – Sinstein Oct 27 '15 at 13:48
  • Sure. See http://stackoverflow.com/questions/7635274/how-to-detect-if-a-click-is-a-mouse-click-or-triggered-by-some-code or http://stackoverflow.com/questions/6674669/in-jquery-how-can-i-tell-between-a-programmatic-and-user-click – j08691 Oct 27 '15 at 13:51