Jquery -无法访问网页表单中列表/选择框中的单个元素

jquery- unable to access individual elements that are part of list/select box in a web page form

本文关键字:选择 元素 单个 列表 Jquery 访问 网页 表单      更新时间:2023-09-26

我正在尝试访问每个单独的元素,即选项,为列表框(或下拉框)定义。

由于某种原因,我正在使用的代码不工作。——

$(jQuery('input', $(this).parent('form'))).each(function() {
        element= $(this);
            textmsg=" Element # " + (count+1) + "...Name of this input element = " + $(this).attr('name') + " multiplechoice-" +  $(this).attr('multiple');
            textmsg= textmsg + "...Also, for this element, the value is " + $(this).val() + " and type =" +  $(this).attr('type');
            alert (textmsg);
         var listofoptions = new Array();
         type=$(this).attr('type');
         if(type=="select")//this means we have to go through the children for this select element, to obtain the values for each option
         {
             var elements= $('option', this);
             for(var i=0; i<elements.length; i++)
            {
                // add $(this).val() to your list
                alert("Value of this option=" + $elements[i].val()); 
            });
         }
});

我如何使上面的代码工作?或者你能建议一种访问每个选项值的替代方法吗?谢谢…

为了选择所有输入,您需要使用:input选择器,而不仅仅是$('input'),因为这将根据标记名称选择输入,并且选择将被排除。

$(this).parent('form').find(':input')

另外,由于select元素上没有type属性。您可以使用.is()来检查它是否是一个选择。

$(this).is('select') 

编辑:对于if语句,我将执行以下操作

if( $(this).is('select') )
{
    $(this).find('option').each(function(){ 
       alert( $(this).val() );    
    });            
}

Here's fiddle

选择标签不是一个输入,所以它永远不会成为选择的一部分

你可以试试

$("input, select")