【问题标题】:get the value of input field of radio type in jquery获取jquery中radio类型的输入字段的值
【发布时间】:2014-02-17 11:33:47
【问题描述】:

我有一个如下所示的输入字段

<input class="d_o" type="radio" value="super" name="old_or_new" checked="checked"> Get this value actually</input><br/>

我必须得到输入字段的值,即Get this value actually,所以尝试了下面的jquery代码

console.log($('.d_o').text());

但令我惊讶的是,它什么也没返回,并且在尝试获取 $('.d_o').val() 之类的值时可以正常工作

那么如何使用 jquery 从上述输入字段中获取文本值,我错过了什么吗?

【问题讨论】:

标签: javascript jquery input radio


【解决方案1】:

您的整个&lt;input&gt; 元素是

<input class="d_o" type="radio" value="super" name="old_or_new" checked="checked">

它后面的文本和 invalid html &lt;/input&gt; 是 DOM 树中完全不同的节点。所以val 按预期返回值“super”,但text 没有返回文本。

【讨论】:

  • 添加到此:W3C 对规范的声明:内容模型:普通类型的 html 元素的文本,如 .. 但是对于输入类型,内容模型为空.. Jquery 可能会遵循这个.. 对此事实有任何验证吗?
  • @user1428716 是的,确切地说——&lt;input&gt; 元素不能包含任何子元素或文本节点。感谢您链接到 W3 规范!
【解决方案2】:

.text() 方法不能用于表单输入或脚本

http://api.jquery.com/text/

虽然我不确定 jQuery 在这方面遵循什么方法:一种解释可以是每个 HTMLElement 的“内容模型”规范。

  Content model
  A normative description of what content must be included as children and descendants of the      element.

例如: 对于输入类型:http://www.w3.org/TR/html5/forms.html#the-input-element

内容模型:空。

但是对于标题元素,这被定义为

     Content model : Text 

http://www.w3.org/TR/html5/document-metadata.html#the-title-element

渴望看到这个假设的验证:)

【讨论】:

    【解决方案3】:

    &lt;input class="d_o" type="radio" value="super" name="old_or_new" checked="checked"&gt; Get this value actually&lt;/input&gt;&lt;br/&gt;

    这不是处理&lt;input&gt; 标记的正确方法。您应该改用 :checked 和 .val()

    $(document).ready(function(){
        $('#hey').on('click', function(event){
            alert($('.check:checked').val());
        });
    });
    
    <h2>Select old or new</h2><br>
    
    <b>Old</b>:<br>
    <input type="radio" class="check" name="old_or_new" value="old"><br>
    
    <br>
    
    <b>New</b>:<br>
    <input type="radio" class="check" name="old_or_new" value="new"><br>
    
    <br>
    
    <input type="button" id="hey">
    

    检查小提琴:http://jsfiddle.net/MLWCK/

    【讨论】:

    • 抱歉回复晚了,实际上我只需要在输入标签后获取文本Get this value actually,因为我有很多上面的输入标签,比如收音机类型和之后的文本。所以我需要在输入标签之后获取文本并在那个地方填充另一个值
    • K 我同意并将输入标签修改为&lt;input type="radio" class="check" name="old_or_new" value="old"&gt;Get this value actually,但是像这样我有很多输入标签,所以需要在每个输入单选类型标签之后获取文本并用其他值进行更改?
    猜你喜欢
    • 2014-12-26
    • 2018-08-22
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2018-02-06
    • 2016-11-20
    • 2015-02-12
    • 1970-01-01
    相关资源
    最近更新 更多