Disclaimer: This is my first HTML, CSS, JavaScript project. Please excuse any misused vocabulary here.
I am making a basic webform for the user to do some pass fail checks. I set all the radio buttons to be required. The implementation of the basic project I modified skips the button portion and instead uses an onclick
function to convert any non blank value into a JSON list. Then I wrote some JavaScript to allow the user to download that list.
While debugging I realized that the submit button ignored the required attributes but the new clear all button I'm using correctly acknowledges them.
I am currently debugging 4 approaches, but decided consulting someone with more experience would teach me better fundamentals.
There is a local storage JavaScript as well if anyone needs to see that, I can edit it in.
$(document).ready(function() {
$("#btn").click(function(e) {
var jsonData = {};
var formData = $("#myform").serializeArray();
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
e.preventDefault();
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {
type: contentType
});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(JSON.stringify(jsonData), 'list.json', 'json');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform" type="post">
<fieldset>
<legend>Some label </legend>
<div class="elements">
<label for="name">1) Test 1:</label>
<input required="required" type="radio" value="pass" name="usb1" size="20" /> [PASS]
<input required="required" type="radio" value="fail" name="usb1" size="20" /> [FAIL]
</div>
<p></p>
<div class="elements">
<label for="name">2) Test 2:</label>
<input required="required" type="radio" value="pass" name="usb2" size="20" /> [PASS]
<input required="required" type="radio" value="fail" name="usb2" size="20" /> [FAIL]
</div>
<!-- ignores required fields -->
<div class="submit">
<input type="submit" id="btn" name="btn" class="btn" value="Submit" />
</div>
<!-- Works same as above as far as I'm aware -->
<button type="button" id="btn" name="btn" class="btn">Submit</button>
<!-- //working correctly -->
<button type="button" id="clr" name="clr" class="clr">Clear</button>
</fieldset>
</form>