Check if checkbox or radio button inside div is seleted
Using jQuery I want to check if checkboxes or radio button inside a div tag is selected and get the value of selected checkbox and radio buttons.
For Example:
<div>
Question
<div>
What is your name?
</div>
<div>
<input type="radio" name="r1" checked/>abc<br/>
<input type="radio" name="r1"/>pqr<br/>
<input type="r开发者_如何学编程adio" name="r1"/>lmn<br/>
</div>
</div>
<div style="visibility: hidden">
Question
<div>
What is your company name?
</div>
<div>
<input type="checkbox" name="c1" checked/>comp1<br/>
<input type="checkbox" name="c1"/>Comp2<br/>
<input type="checkbox" name="c1"/>Comp3<br/>
</div>
</div>
on button click I want to show question and in front of that the answer of that question. Like as follows
What is your name = abc
What is your company name = comp1, comp2
Thanks.
Here you go dude some code sample
var chk = $('#dvTest input:radio:checked');
chk.attr('value');
It will give you which radio buttton is checked. Whaever value you want keep that in that value property for ex:
<input type="radio" name="r1" checked="checked" value="abc"/>
Same you can do for checkbox.
See http://api.jquery.com/checked-selector/ on how to use the :checked selector.
Maybe something like this:
http://jsfiddle.net/magicaj/xFqHN/
HTML:
<div>
Question
<div>
What is your name? <span id="your-name"></span>
</div>
<div>
<input type="radio" name="r1" value="abc" checked="checked" />abc<br/>
<input type="radio" name="r1" value="pqr" />pqr<br/>
<input type="radio" name="r1" value="lmn" />lmn<br/>
</div>
</div>
<div id="comp" style="visibility: hidden">
Question
<div>
What is your company name?<span id="comp-name"></span>
</div>
<div>
<input type="checkbox" name="c1" value="comp1" checked/>comp1<br/>
<input type="checkbox" name="c1" value="Comp2" />Comp2<br/>
<input type="checkbox" name="c1" value="Comp3" />Comp3<br/>
</div>
</div>
JS:
$("input[name='r1']").click(function() {
$("#your-name").html($(this).val());
updateCompName();
$("#comp").css("visibility", "visible");
});
var updateCompName = function() {
var element = $("#comp-name");
var compNames = "";
compCheckboxes.each(function() {
if (this.checked === true) {
compNames += " " + $(this).val();
}
});
$("#comp-name").html(compNames);
}
var compCheckboxes = $("input[name='c1']");
compCheckboxes.click(updateCompName);
You were missing the value
attribute on your radios and checkboxes. I added spans placeholders to update the text with the current value of the radio/checkboxes.
精彩评论