简体   繁体   English

未获取名称属性

[英]Not getting name Attribute

I am not getting value from name Attribute. 我没有从名称属性获得价值。 What I am doing wrong? 我做错了什么?

For example 例如

$(function() {
    $("#orderForm").submit(function(e){
        e.preventDefault();
        var statusName = $(this).attr('input[name="name"]').val();
        var statusDesc = $(this).attr('input[name="description"]').val();
        alert(statusName);
    });
});

HTML Code: HTML代码:

<form id='orderForm'>
   <input type="text" name="name">
  <textarea name="description"></textarea>
 <button type="Submit">Add</button>
</form>

You are searching for attribute equals selector , 您正在搜索的attribute equals selector

$("#orderForm").submit(function(e){
  e.preventDefault();
  var statusName = $('input[name="name"]', this).val();
  var statusDesc = $('textarea[name="description"]', this).val();
  alert(statusName);
});

And here i have used $("selector", context) version, So the elements which matches the selector would be searched inside the context not out of it. 在这里我使用了$("selector", context)版本,因此匹配选择器的元素将在上下文中搜索而不是从上下文中搜索出来。 And it is very similar to $(context).find("selector") 它非常类似于$(context).find("selector")

jQuery attr function get the value of an attribute, not the value of an text input. jQuery attr函数获取属性的值,而不是文本输入的值。

You should use children() for get the user input value of the orderForm module. 您应该使用children()获取orderForm模块的用户输入值。 I prepared a Js Bin with the correct code. 我用正确的代码准备了一个Js Bin

try this, 尝试这个,

$(function() {
  $("#orderForm").submit(function(e) {
    e.preventDefault();
    var statusName = $(this).find('input[name="name"]').val();
    var statusDesc = $(this).find('*[name="description"]').val();
// or var statusDesc = $(this).find('textarea[name="description"]').val();
    alert(statusDesc);
  });
});

i would recommend you to assign Id's for each field while dealing with forms 我建议您在处理表格时为每个字段分配ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM