Print all form values in the console with Jquery?

Asked

Viewed 1,319 times

0

Is there any way to capture all the data selected in selects and inserted into the inputs of a form?

I’ve tried using $('#form1').serialize(); but I didn’t get a result, in php I use the global variable $_GET and $_POST and use the var_dump() to print the results, I wanted to know how to do this in jquery?

  • 1

    Because the $('#form1').serialize() didn’t work? What happened?

  • @Arturotemplário do not know if it can be the fact of the form is dynamic and the data he understands that do not exist yet, for having been created after the declaration of the function

2 answers

3


Just serialize with serializeArray and turn into JSON.

var dados = JSON.stringify( $(#form1).serializeArray() ); //  <-----------

console.log( dados );
  • thanks for the tip, but it only works for inputs know if you can get the values of the selects as well?

  • 1

    This method takes all inputs, revises your select, it may be that the structure or Names are incorrect, anything edits the question with them.

  • 1

    you were right about mine selects were without the attribute name, I believed and now it worked.

1

Well from what I saw serialize() did not serve, so how do you just want to get the values of inputs and selects. You can use $.each(). As follows :

$(function(){
  var print=function(){
    var data = {};
    $('#form1 input, #form1 select').each(function(){
      data[$(this).attr("name")] = $(this).val();
    });
    console.log(data);
  };

  print(); // irá printar o objeto no console
});

Basically what this code does is go in each select and each input present within the form, take the name attribute and its value. Then add this to the date object so that the, the key is the field name (which can be input or select) and the value is the field value.

Enclosed within a function, it can be called when and the way you need it.

I hope I’ve helped ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.