0

I have a form with multiple divs that are not visible (Toggle jQuery) because of user interaction. After submitting the form I would like to save only the visible (filled by user) elements. Can't get it to work. Thanks in advance!

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $('#content').text($('#myform').serialize());
    });
});
</script>
</head>
<body>

<form action="" id="myform">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
  <div style="display:none;"><input type="text" name="isthishidden" value="maybe"></div>
 <input type="hidden" name="action" value="verwerk">
</form>
<button>Serialize form values</button>
<p></p>
<div id="content"></div>

</body>
</html>

1 Answers1

2

One little tweak to your code makes this possible:

$('#content').text($('#myform :visible').serialize());

$(document).ready(function(){
  $("button").click(function(){
    $('#content').text($('#myform :visible').serialize());
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form action="" id="myform">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
  <div style="display:none;"><input type="text" name="isthishidden" value="maybe"></div>
 <input type="hidden" name="action" value="verwerk">
</form>
<button>Serialize form values</button>
<p></p>
<div id="content"></div>
Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • And what if I would like to post the hidden field? – user1725719 Nov 23 '21 at 20:53
  • Maybe I misunderstood your question. I thought you only wanted to post visible fields. Or did you mean only post fields with values (hidden or not-hidden)? – Kinglish Nov 23 '21 at 21:13
  • No, you did not misunderstood. It is an additional question. How can I post visible fields, but do post the hidden fields. – user1725719 Nov 23 '21 at 21:29
  • The way you had it initially posted all fields in the form, visible or non-visible. `#form :visible` only finds form elements which are visible. You could also do something like `#form :not(:empty)` if you wanted to just post data from inputs that had values in them (ignoring empty inputs)... – Kinglish Nov 23 '21 at 22:15