如何在jquery中显示除输入标签之外的文本

时间:2015-01-27 08:03:24

标签: javascript jquery

我想在单击按钮时显示另一个元素中单选按钮旁边的文本。

我的HTML:

<p>
<input type="radio" value="1" name="General">
I need a simple template
</p>
<p>
<input type="radio" value="2" name="General">
I need a simple template based
</p>
<p>
<input type="radio" value="3" name="General">
I need a simple template based type
</p>

我想在类display的元素中显示结果,如下所示:

$('.display').val();

我试过了:

$('.display').val($('input[type=radio]:checked').closest('p').html());

2 个答案:

答案 0 :(得分:3)

我猜你想要做的是将与所选单选按钮关联的文本放在.display元素中。如果是这样,使用您当前的HTML,您可以在父元素上使用.text来获取文本,然后在.text元素上使用.val(不是.display)显示它(如果.val是表单字段,则为.display):

&#13;
&#13;
$("input[name=General]").on("click", function() {
  var text = $(this).closest('p').text();
  $(".display").text(text);
});
&#13;
<p>
<input type="radio" value="1" name="General">
I need a simple template
</p>
<p>
<input type="radio" value="2" name="General">
I need a simple template based
</p>
<p>
<input type="radio" value="3" name="General">
I need a simple template based type
</p>
<p class="display"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;


,最好使用label元素,以便用户点击这些字词以及实际的单选按钮:

&#13;
&#13;
$("input[name=General]").on("click", function() {
  var text = $(this).closest('label').text();
  $(".display").text(text);
});
&#13;
<p>
  <label>
    <input type="radio" value="1" name="General">
    I need a simple template
  </label>
</p>
<p>
  <label>
    <input type="radio" value="2" name="General">
    I need a simple template based
  </label>
</p>
<p>
  <label>
    <input type="radio" value="3" name="General">
    I need a simple template based type
  </label>
</p>
<p class="display"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是在名称相同时将复选框的关联文本放在单独的行中的问题的解决方案。

HTML代码 -

<p><input name="SiteLayoutDesign" value="5" type="checkbox"> I do not need any unique graphics designed (0 Hours)</p>
<p><input name="SiteLayoutDesign" value="6" type="checkbox"> I will supply images (0 Hours)</p>
<p><input name="SiteLayoutDesign" value="7" type="checkbox"> I have a template but it needs minor customization (0 Hours)</p>
<p><input name="SiteLayoutDesign" value="8" type="checkbox"> I need a template customized (0 Hours)</p>
<p><input name="SiteLayoutDesign" value="9" type="checkbox"> I would like a custom design created for my site (0 Hours)</p>

jQuery代码 -

$(document).ready(function(){
    $('input').click(function(){
        var $check = $('input[type=checkbox]:checked');
        $check.each(function(){
            var id = $(this).val();
            var did = $('input[type=checkbox][value='+id+']:checked').closest('p').text();

        });
    });
});

did变量存储关于该checkBox值的关联文本。