简体   繁体   中英

Retrieve data from a form using jquery

I'm trying to get information from a form and passing it to mysql. Here is my method:

var form = [];

$("input").each(function(){
var id = $(this).attr("name");
var value = $(this).val();
alert(id);

var item = {};
item ["name"] = id;
item ["value"] = value;

form.push(item);        
});

return JSON.stringify(form);

The problem is when i try to get the checked and unchecked values from the radio buttons. The query string that I want to pass to mysql outputs like this:

insert into contatos (nome, rua, sexo, sexo, ncasa, civil, civil, civil, bairro, aniversario, cidade, rg, cpf, usuario, telefone, senha, email, confirmasenha) values ('', '', 'M', 'F', '', 'S', 'C', 'D', '', '', '', '', '', '', '', '', '', '')

The fields "sexo" and "civil" are repeating. How do I make the input to read the radio buttons only 1 time?

It is because you are iterating over each text field and if you have 3 radio button you are pushing all 3 values to array so I took 2 radio fields sexo and civil outside loop so It will be pushed only 1 time and not be repeated.

$("input").each(function(){



if(id!='sexo' || id!='civil'){

     var id = $(this).attr("name");
     var value = $(this).val();

     var item = {};
    item ["name"] = id;
    item ["value"] = value;

    form.push(item);

}


});

 var value1 =$('input:radio[name=sexo]:checked').val();
 var value2 =$('input:radio[name=civil]:checked').val();

    var item = {};
    item ["name"] = "sexo";
    item ["value"] = value1;

    form.push(item);

    var item = {};
    item ["name"] = "civil";
    item ["value"] = value2;

    form.push(item);


return JSON.stringify(form);

If you call serializeArray on a jQuery form element you'll get an array of objects, similar to the one you are creating, and will avoid duplicates:

$('form').serializeArray();

will return:

[
  {
    name: "firstfield",
    value: "1"
  },
  {
    name: "secondfield",
    value: "2"
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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