-1
    $('div').on('click', function (ev) {
    if (ev.target.tagName === 'SPAN') {
        if ($(ev.target).prev().is(':checked') === false) {
            $(ev.target).prev().attr('checked', true)
        }
        else {
            $(ev.target).prev().attr('checked', false)
        }
    }
});

so, when i click on my span element the radio from unchecked becomes checked and then when i click again it becomes unchecked as it should, but then it breaks, thats it... that's my problem. When i click on it more then 2 times in doesn't changes the checked value to anything. Here is my HTML

<div>
    <input type="text" placeholder="Answer...">
    <input type="radio" name="1"> <span>Answer 1</span>
    <input type="radio" name="1"> <span>Answer 2</span>
    <input type="radio" name="1"> <span>Answer 3</span>
    <input type="radio" name="1"> <span>Answer 4</span>
</div>
Все Едно
  • 746
  • 3
  • 10
  • 24

2 Answers2

3

You want to use .prop instead of .attr:

$('div').on('click', function(ev) {
  if (ev.target.tagName === 'SPAN') {
    if ($(ev.target).prev().is(':checked') === false) {
      $(ev.target).prev().prop('checked', true)
    } else {
      $(ev.target).prev().prop('checked', false)
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" placeholder="Answer...">
  <input type="radio" name="1"> <span>Answer 1</span>
  <input type="radio" name="1"> <span>Answer 2</span>
  <input type="radio" name="1"> <span>Answer 3</span>
  <input type="radio" name="1"> <span>Answer 4</span>
</div>

see How to check a radio button with jQuery ?

Community
  • 1
  • 1
Fabricator
  • 12,722
  • 2
  • 27
  • 40
  • ok,the link you gave at the bottom in your comment, it didn't popped up on my search, so basically `.prop` is the new one and `.attr` is outdated? – Все Едно May 15 '16 at 19:29
1

Well, here's a simple solution. Not pretty, but it does the job. Just remember to ALWAYS reset all inputs, since it's radio with the same name, you can't have more then one checked.

$('span').on('click', function (ev) {
    if (ev.target.tagName === 'SPAN') {
        if ($(ev.target).prev().is(':checked') === false) {
            $('input[type="radio"]').attr('checked', false);
            $(ev.target).prev().attr('checked', true);
        }
        else {  
            $(ev.target).prev().attr('checked', false);
        } 
    }
});

http://jsbin.com/wabecaboha/1/edit

uglycode
  • 3,022
  • 6
  • 29
  • 55