如何获得<选择>带有jquery的id

How to get the <select> id with jquery

本文关键字:jquery id 带有 选择 何获得 lt gt      更新时间:2023-09-26

使用jquery脚本浏览HTML表单元素,我发现我可以使用以下代码获得标签的id:

$(":checkbox,:radio,:text,:selected", this).each(function(){
    var controlName = $(this).attr("id");
    var controlType = $(this).attr("type");
    alert(controlName);
    if(controlType=="checkbox" || controlType=="radio"){
        if ($(this).attr('checked')=="checked"){cadena += "&" + controlName + "=on";}
        else{ cadena += "&" + controlName + "=off";}    
    }
    else{
        cadena += "&" + controlName + "=" + $(this).attr('value');
    }               
});

它可以使用复选框、radioButtons和textInputs,为我提供正确的id。但对于select标记,它总是返回"undefined"。

我做错了什么?

谢谢。

*更新*这是我当前的表单。我知道这不是一个"正常"表单,但我正在一个特殊的应用程序中使用它。感谢大家的耐心:

    <form action="#" id="ejemplo" class="ejemplo">
    <fieldset>
        <legend> Formulario de ejemplo </legend>
        <input id="Nombre" type="text" value="Texto1" name="Nombre" />    <label for="Nombre">Nombre</label> <br/>
        <input id="Apellidos" type="text" value="Texto1"  name="Apellidos" /> <label for="Apellidos">Apellidos</label> <br/>
        <label for="campo2">Campo 2</label>
        <select id="coches">
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="mercedes">Mercedes</option>
            <option value="audi">Audi</option>
        </select>
        <br/>
        <input type="checkbox" id="option1"> <label for="option1"> Milk   </label>
        <input type="checkbox" id="option2"> <label for="option2"> Butter </label>
        <input type="checkbox" id="option3"> <label for="option3"> Cheese </label>
        <br/>
        <input type="radio" name="group1" id="radio1"> <label for="radio1"> Milk   </label> <br/>
        <input type="radio" name="group1" id="radio2"> <label for="radio2"> Butter </label> <br/>
        <input type="radio" name="group1" id="radio3"> <label for="radio3"> Cheese </label>
        <br/>
        <textarea cols="40" rows="5" id="areaTexto">Inside de text area!</textarea>
        <br/>
        <input id="boton" type="button" value="Boton"><br>
    </fieldset>
</form>

获取select"coche"id后,返回"undefined"。但是,让它的值返回正确的值。

运行我的代码后,它返回:

&Nombre=文本1&Apellidos=文本1&undefined=volvo&option1=关闭&option2=关闭&option3=关闭&radio1=关闭&radio2=关闭&radio3=关闭

查看undefined=volvo:S

:选择的不是你想象的那样。

jQuery:选择

描述:选择所有选定的图元。

添加的版本:1.0

jQuery( ":selected" ):选定的选择器适用于元素。它不适用于复选框或无线电输入;使用:已检查。

您希望使用select来获取select元素。

或者,您可以使用:input来获取所有输入元素。

:selected匹配选定的<option>元素,而不是<select>元素。更改选择器:

$(":checkbox,:radio,:text,select", this)

N.B.$(this).attr('id')总是可以替换为this.id

<select id="foo">
  <option value="1">a</option>
  <option value="2">b</option>
  <option value="3">c</option>
</select>

对于select标签,您可以使用:selected过滤器来获取select选项的父项的id:

var id = $(this).children(":selected").attr("id");