silent_coder14
silent_coder14

Reputation: 583

how to add value of input textfield that is next to an element?

I have a dynamic form that is generated by php.

  print '<div class="choices">';
    print '<input type="radio" class="answer' . $q . '" id="answer'. $q . '" name="answer'. $q . '"value="1"/>' . $row['answer1'] .'<br/>';
    print '<input type="hidden" class="answer' . $q . '" id="answer'. $q . '" name="answer'. $q . '"value="1"/>';

    print '<input type="radio" class="answer' . $q . '" id="answer'. $q . '" name="answer'. $q . '"value="2"/>' . $row['answer2'] .'<br/>';
    print '<input type="hidden" class="answer' . $q . '" id="answer'. $q . '" name="answer'. $q . '"value="1"/>';

    print '<input type="radio" class="answer' . $q . '" id="answer'. $q . '" name="answer'. $q . '"value="3"/>' . $row['answer3'] .'<br/>';
    print '<input type="hidden" class="answer' . $q . '" id="answer'. $q . '" name="answer'. $q . '"value="1"/>';

    print '<input type="radio" class="answer' . $q . '" id="answer'. $q . '" name="answer'. $q . '"value="4"/>' . $row['answer4'] .'<br/>';
    print '<input type="hidden" class="answer' . $q . '" id="answer'. $q . '" name="answer'. $q . '"value="1"/>';

    print '<input type="hidden" class="your" id="answer" name="correctanswer'. $q . '" value="0"/>';

    print '</div>';

I want to change the value of input type hidden which has a class of your that is next to div .choices. I used the jQuery below.

$('input[type=radio]').on('click', function(){
//  alert(this.value);
    $(".choices ~ .answer").val(this.value);

});

But it is not working. Any suggestions?

EDIT:

HTML

Upvotes: 0

Views: 111

Answers (1)

Alex Heyd
Alex Heyd

Reputation: 1333

First of all, you have the same ID on multiple elements. IDs should be unique. I'm unclear as to where input.your is located, your description says it's a sibling of div.choices, but the code indicates it's a child of div.choices...

If input.your is a sibling of div.choices:

    $('input[type=radio]').on('click', function(){
        $(this).parent().siblings('.your').val($(this).val());
    });

If input.your is a child of div.choices:

    $('input[type=radio]').on('click', function(){
        $(this).siblings('.your').val($(this).val());
    });

EDIT: misunderstood question

Upvotes: 1

Related Questions