I'm aware (from this) I can explicitly convert a value to an integer before passing it to JSON.stringify
. But this approach is not useful when you want to serialize a form data. I have a generic code:
let myform='#my_form_id`;
$(myform).submit(function(event) {
event.preventDefault();
const formData = new FormData($(myform)[0]);
const json = JSON.stringify(Object.fromEntries(formData));
ws.send(json); // send over websocket
});
And I really don't want to manually convert each field to the appropriate type before serialization. It's against all the rules of a "well-written" code.
So, how can I serialize the form fields in JSON keeping their native data types?
CodePudding user response:
You can map over the inputs and use a switch case to choose what data and type is returned.
$('form').on('submit', function(e) {
e.preventDefault();
let json = JSON.stringify($(this).find('input').get().map(function(input){
switch (input.type) {
case 'checkbox':
case 'radio': return input.checked; break;
case 'number':
case 'range': return (input.value || 0); break;
default: return input.value || ''
}
}));
$('.json').html(json);
});
<form>
<div>
<input>
<input type="number">
<input type="checkbox">
<input type="radio">
<input type="color">
<input type="date">
<input type="range">
</div>
<div>
<input>
<input type="number">
<input type="checkbox">
<input type="radio">
<input type="color">
<input type="date">
<input type="range">
</div>
<button action="submit">SERIALIZE</button>
</form>
<p class="json"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>