I am so confused! I am attempting to target a form on my page and use the jQuerys serializeArray() function to grab all the values of the form.
<div class="page-width">
<header class="section-header text-center">
<h1 class="section-header__title h2">{{ page.title }}</h1>
</header>
<script>
$(document).ready(function () {
$( "#form" ).submit(function( event ) {
var fields = $( "form" ).serializeArray();
console.log(fields)
event.preventDefault();
});
});
</script>
<div class="grid">
<div class="grid__item medium-up--four-fifths medium-up--push-one-tenth">
<div class="rte">
{{ page.content }}
<form action="#" method="#" id="form">
<fieldset>
<legend>Have you ever felt any of the below symptoms after consuming coffee or tea or other caffeinated beverage (cola, hot chocolate...) Select the boxes that apply.</legend>
<input type="checkbox" id="heartburn" >
<label for="heartburn">Heartburn</label><br/>
<input type="checkbox" id="jitters" >
<label for="jitters">Jitters</label><br/>
<input type="checkbox" id="anxiety" >
<label for="anxiety">Anxiety</label><br/>
<input type="checkbox" id="upset-stomach" >
<label for="upset-stomach">Upset Stomach</label><br/>
<input type="checkbox" id="bathroom" >
<label for="bathroom">Urgent need to go the bathroom</label><br/>
<input type="checkbox" id="heart" >
<label for="heart">Racing Heart</label>
</fieldset>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
</div>
Right now it logs as a mysterious form ( I assume this has something to do with Shopifys template)
If I change the selector to
var fields = $( this ).serializeArray();
It logs as an empty array.
Questions
- What is this random form I am targeting?
- How can I target the form on this page?
2
Answers
Well you are serializing ALL forms at the moment with this line
$( "form" ).serializeArray();
on the page.Change it to
$(this).serializeArray()
in order to serialize only the submitted form and not all forms. (in the submit scope)And add name attributes to your inputs if you like to serialize it.
"name" attribute is missing in the form fields. If you want to get all the field values you should provide "name" and "value" attribute is optional.
Please check below working example.