0

I am trying to copy all input values of a div to another div with the same exact inputs, based on a checkbox press.

This is my HTML Form:

<div id="0">Name*
    <input type="textbox" name="name0" required/>Sex*
    <input type="radio" name="sex0" value="M" required/>M
    <input type="radio" name="sex0" value="F" required/>F
    <br>Location
    <input type="textbox" name="location0" />Age
    <input type="textbox" name="age0" size="2">
    <br>Ethnicity
    <input type="textbox" name="ethnicity0">
</div>
<input type="checkbox" class="copy" name="copy1" value="1" />Check to copy below
<br>
<div id="1">Name*
    <input type="textbox" name="name1" required/>Sex*
    <input type="radio" name="sex1" value="M" required/>M
    <input type="radio" name="sex1" value="F" required/>F
    <br>Location
    <input type="textbox" name="location1" />Age
    <input type="textbox" name="age1" size="2">
    <br>Ethnicity
    <input type="textbox" name="ethnicity1">
</div>

This is my Javascript:

$(document).ready(function () {
    $('input[type="checkbox"]').change(function() {
        var whichDiv = this.value;
        var divFrom= $("#"+(whichDiv-1)).children();
        var divTo = $("#"+whichDiv).children();
        if(this.checked) {
            //COPY previous elements
            for (var i = 0; i < divFrom.length; i++) {
                var tableChild = divFrom[i];
                var tableChildTo = divTo[i];
                tableChildTo.value = tableChild.value;
            } 
        }
        else {
            for (var p = 0; p<divTo.length; p++){
                $(divTo[p]).val('');
            }
        }
    });
});

The tableChildTo.value works for copying the value of textboxes but not the radio button for M or F. How would I do this?
Using Jquery 1.11.1

hellslam
  • 1,550
  • 11
  • 17
user3264659
  • 341
  • 2
  • 7
  • 20
  • possible duplicate of [How to get the value of a selected radio button using its name in jQuery?](http://stackoverflow.com/questions/986120/how-to-get-the-value-of-a-selected-radio-button-using-its-name-in-jquery) – hellslam Dec 11 '14 at 20:17
  • no it's not, that's just getting the value, not setting it as well. – user3264659 Dec 14 '14 at 05:40

1 Answers1

2

Have you tried using:

$("input:radio[name=sex1]:checked").val();

The same setup would go for the other radio box but use sex0 obviously.

Edit: Here is a good reference source for that actually in the jQuery api: http://api.jquery.com/val/

dhershman
  • 341
  • 2
  • 12
  • That does get the value of the checked box but it doesn't select the radio button for it. I think you have to do something like $("input:radio[name=sex1][value=M]").prop("checked", true), but instead of M you have to substitiute what the checked value is for sex0. – user3264659 Dec 11 '14 at 21:01