User-1404740798 posted
After you convert the form data to JSON, you want to save the JSON as a json file on your computer.
If you press the button now, the json format is displayed on the screen, and after downloading the file, the file is downloaded by pressing the download button.
Is there any way to convert and download it at the same time as pressing the button?
<form class="form-control m-t-3" id="info" method="post">
<div class="pull-right">
<input type="submit" class="btn btn-primary" value="save" id="save" />
</div>
<pre id="output"></pre>
</form>
<a href="#" class="btn btn-primary" id="link" download="JSON1.json">down</a>
<script>
(function() {
function toJSONString(form){
var obj = {};
var elements = form.querySelectorAll("input, select");
for(var i = 0; i < elements.length; ++i){
var element = elements[i];
var id = element.id;
var value = element.value;
if(id) obj[id] = value;
}
var obj_s = JSON.stringify(obj, null, "\t");
var dataUri = "data:application/json;charset=utf-8,"+ encodeURIComponent(obj_s);
var link = $("#link").attr("href", dataUri);
return JSON.stringify(obj, null, "\t");
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "info" );
var output = document.getElementById( "output" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString(this);
output.innerHTML = json;
}, false);
});
})();
</script>