【问题标题】:how to add value of input textfield that is next to an element?如何添加元素旁边的输入文本字段的值?
【发布时间】:2014-05-07 07:14:17
【问题描述】:

我有一个由 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>';

我想更改输入类型 hidden 的值,该类型的类为 your,位于 div .choices 旁边。我使用了下面的 jQuery。

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

});

但它不起作用。有什么建议吗?

编辑:

HTML

【问题讨论】:

  • 我不知道您使用的“旁边”的什么定义会将.your 元素放在.choices 元素旁边。他们根本不是互相发短信的。 .your.choices 的一个孩子,在这种情况下是最后一个孩子。然而,.your 是被点击元素的 *sibling*`,所以 $(this).nextAll(".your")$(this).nextUntil(".your").next()
  • 试试$(this).next().val(this.value);
  • 是的..它会工作,但如果你有 5 组 HTML 代码怎么样。
  • 为什么会有问题?
  • 你为什么要使用.answer 来访问类your 的元素?

标签: javascript php jquery


【解决方案1】:

首先,您在多个元素上具有相同的 ID。 ID 应该是唯一的。我不清楚 input.your 的位置,您的描述说它是 div.choices 的兄弟,但代码表明它是 div.choices 的子...

如果 input.your 是 div.choices 的兄弟:

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

如果 input.your 是 div.choices 的子级:

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

编辑:被误解的问题

【讨论】:

  • 没有一个radio 元素将使用.next() 到达类your 的目标元素。
  • 编辑了答案。没有意识到隐藏的输入 .your 是 div.choices 的兄弟。其实......看OP,它是div.choices的孩子......?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多