Is not function JQUERY

1
$(".add").click(function(event){
  save($(this).parent().attr("id"));
});
function save(docName){
  var inputs = $('#' + docName + ' input');
  var selects = $('#' + docName + ' select');
  var obj;
  console.log(inputs);
  for (let i = 0; i < inputs.length; i++) {
    console.log(inputs[i]);
    obj[inputs[i].attr("id")] = inputs[i].val();
    inputs[i].val() = "";
  }
  for (let i = 0; i < selects.length; i++) {
    obj[selects[i].attr("id")] = inputs[i].val();
    selects[i].val() = "";
  }
  firebase.database().ref().child(docName).push(obj);
}

I'm trying to create a function to add a dynamic form, but attr ("id") is giving an error.     "inputs [i] .attr is not function".  Could someone help me solve this problem?

    
asked by anonymous 16.05.2017 / 01:58

1 answer

3

var divs = $(".div");
for (var i = 0; i < divs.length; i++) {
  console.log(divs[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="div1" class="div" >1</div>
<div id="div2" class="div" >1</div>
<div id="div3" class="div" >1</div>
<div id="div4" class="div" >1</div>

When you do this, you are not traversing a collection of jQUery objects, but the collection of DOM that the jQuery object is encapsulating.

What you can do is check the id directly (without using jQuery )

var divs = $(".div");
for (var i = 0; i < divs.length; i++) {
  console.log(divs[i].id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="div1" class="div" >1</div>
<div id="div2" class="div" >1</div>
<div id="div3" class="div" >1</div>
<div id="div4" class="div" >1</div>

Of course, if you need to manipulate each DOM object as a jQuery object, you will have to encapsulate them using $ , although it is possible to $(divs[i]) , you better make use of $.each %.

var divs = $(".div");
divs.each(function (indice, elem) {
  var that = $(this);
  console.log(that.attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="div1" class="div" >1</div>
<div id="div2" class="div" >1</div>
<div id="div3" class="div" >1</div>
<div id="div4" class="div" >1</div>

In the above example, this is just the DOM object that is encapsulated by jQuery .

SUGGESTION

$(".add").click(function(event){
  // passe o doc como argumento, utilize ele como escopo para a sua função.
  save($(this).parent());
});
function save(doc){
  // listando todos os inputs e selects dentro do doc.
  var inputs = $('input, select', doc);
  // você não estava iniciando a variavel obj.
  var obj = {};
  inputs.each(function () {
    // encapsulando o objeto DOM no jQuery.
    var input = $(this);
    obj[input.attr("id")] = input.val();
  });
  // val não é uma propriedade, mas sim uma função.
  inputs.val("");  
  // Quanto ao Firebase, não tenho como lhe ajudar.
  firebase.database().ref().child(doc.attr("id")).push(obj);
}
    
16.05.2017 / 02:19