Ricki
Ricki

Reputation: 943

When div is clicked, check corresponding radio input jquery

Here's my problem, I want an entire div to be click able, when clicked I need the radio button contained in the div to be checked, so the div acts as a radio itself. Here's what I thought I could use;

$('#content').click(function(e) { $('input:radio[name="id_"]').prop('checked', true); });

But this is not selecting the relative radio inside the div. I think I can use a this selector, am I right?

Upvotes: 0

Views: 8191

Answers (6)

DF_
DF_

Reputation: 3973

Yes you can use the this selector. I have made a quick jsfiddle to show you an example.

Upvotes: 3

sohel khalifa
sohel khalifa

Reputation: 5578

Try with this:

$('div').click(function(){
     if( $('div').find('input:checkbox').prop("checked") == true){
         $('div').find('input:checkbox').prop("checked", false);
     }
     else{
         $('div').find('input:checkbox').prop("checked", true);
     }
});

LIVE DEMO

Upvotes: 1

Pedro del Sol
Pedro del Sol

Reputation: 2841

building on Deif's solution this will toggle the checked status when clicking on the div

fiddle

<div id="content">
    Some content
    <input type="radio" id="radio1" value="test" />
</div>

<script type="text/javascript">
$('#content').click(function () {    
   var val =  $(this).find('input:radio').prop('checked')?false:true;
   $(this).find('input:radio').prop('checked', val);
});
</script>

Upvotes: 1

Byscripts
Byscripts

Reputation: 2588

You don't give any code, so I guess:

DEMO

See my demo on CodePen

HTML

<div class="content">
  <input type="radio" name="foo">
</div>

<div class="content">
  <input type="radio" name="foo">
</div>

<div class="content">
  <input type="radio" name="foo">
</div>

CSS (for example)

.content {
  float: left;
  width: 100px;
  padding-top: 100px;
  background-color: #eee;
  margin-left: 10px;
}

JS (JQUERY)

$('.content').click(function(){
  $(this).find('input[type=radio]').prop('checked', true);
})

Upvotes: 4

Taron Mehrabyan
Taron Mehrabyan

Reputation: 2229

$('#content').click(function(){
$(this).children('radio').attr('checked','checked')
})

Upvotes: 2

Arindam
Arindam

Reputation: 998

This should do it.

$('input:radio[name*="id_"]'), assuming the name starts with id_

And yes you can use this. Use it to filter down its children like:

$(this).children('input:radio[name*=id_]').prop("checked", true)

The key is using name*=id_

This means select element whose name starts with id_. Isn't that what you wanted ?

Upvotes: 2

Related Questions