【问题标题】:return type of input with jquery使用 jquery 返回输入类型
【发布时间】:2010-12-21 13:29:16
【问题描述】:

我有一个动态创建的表单元素的表单。

我需要获取每个元素的值,并发送一个 ajax 请求以确保数据正常(简单的部分)。我可以很容易地获得每个元素的值,但问题出在单选按钮上。例如:

<input type = 'radio' class = 'form_element' value = '1'>
<input type = 'radio' class = 'form_element' value = '1'>
<input type = 'radio' class = 'form_element' value = '1'>

如果我做类似...

$('.form_element').each(function(){
     alert($(this).val());
});

它将打印所有单选按钮的值,无论是否选中。

我需要它只返回被检查的值。

那么,有没有办法从 jquery 返回输入元素的类型?

【问题讨论】:

    标签: jquery input css-selectors elements


    【解决方案1】:

    使用$('.form_element:checked') 仅获取选中的单选按钮的值。

    【讨论】:

      【解决方案2】:

      尝试:

      $('.form_element:checked').each(function(){
           alert($(this).val());
      });
      

      【讨论】:

        【解决方案3】:

        除了salgiza 提到的,您还可以使用Attribute filters 执行更通用的过滤,包括您的要求。

        喜欢:$('.form_element[checked=true]').each(function(){ 警报($(this).val()); });

        【讨论】:

          【解决方案4】:

          这个例子可能会有所改进,但应该可以解决问题。

          $('.form_element').each(function(){
              if ($(this).attr("type") == "radio") {
                  if ($(this).attr("checked") == true) {
                      alert($(this).val());
                  }
              } else {
                  alert($(this).val());
              }
          });
          

          我使用以下 HTML 对其进行了测试,以判断它是否正常工作(您的示例在每个单选选项上具有相同的值):

          <input type='radio' name="a" class="form_element" value="1">
          <input type='radio' name="a" class="form_element" value="2">
          <input type='radio' name="a" class="form_element" value="3">
          

          【讨论】:

            【解决方案5】:

            这就是你想要的。在循环内部,它离开了不需要的 jQuery 装箱。处理单选、复选框、文本、文本区域、选择一。不考虑 select-multiple, file, ....

            $('.form_element').each(function() {
              switch(this.type) {
                case 'radio':
                case 'checkbox': if (this.checked) alert(this.value); break;
                case 'text':
                case 'textarea':
                case 'select-one': alert(this.value); break;
                default: alert("unhandled type: "+this.type);
              }
            });
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-10-29
              • 1970-01-01
              • 2019-07-09
              • 1970-01-01
              • 1970-01-01
              • 2021-09-30
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多