I'm currently trying to use jQuery to collect information from a HTML form, but I'm stuck.
Every time I console.log payload its empty and didn't capture the input values.
Questions:
Why is payload empty at the end, after I input values into the form?
how to correct it?
Should I use document.ready for this or window.onload?
Please any help is appreciated.
Here is my last attempt jQuery:
$(document).ready(function() {
const ApplyOpeningPayloadBuilder = function() {
let payload = {
"fields": []
};
return {
withKeyValue: function(key, value) {
let param = {};
param.key = key;
param.value = value;
payload.fields.push(param);
return this;
},
withFile: function(key, encoded_data, filename) {
let value = {};
value.encoded_data = encoded_data;
value.file_name = filename;
this.withKeyValue(key, value);
return this;
},
build: function() {
return payload;
}
}
}
let encoded_file = "aGVsbG8gd29ybGQ=";
let apply_for_an_opening_payload_builder = new ApplyOpeningPayloadBuilder();
$(".applicantForm input[type=text]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=email]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=tel]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=url]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
apply_for_an_opening_payload_builder.withFile("resume", encoded_file, "resume.txt");
let payload = apply_for_an_opening_payload_builder.build();
console.log("Log payload:", payload)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" id="json-response">
<div class="form-container">
<div class="header">
<h1>Application form</h1>
</div>
<form action="#" class="applicantForm">
<div class="form-group">
<div class="input-group">
<label for="First Name">First Name <span>*</span></label>
<input type="text" name="First Name">
</div>
<div class="input-group">
<label for="Last Name">Last Name <span>*</span></label>
<input type="text" name="Last Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Email">Email <span>*</span></label>
<input type="email" name="Email">
</div>
<div class="input-group">
<label for="Phone">Phone <span>*</span></label>
<input type="tel" name="Phone">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Resume">Resume <span>*</span></label>
<input class="form-control" type="file" name="Resume">
</div>
<div class="input-group">
<label for="LinkedIn Profile">LinkedIn Profile<span>*</span></label>
<input type="url" name="LinkedIn Profile">
</div>
<div class="input-group">
<label for="Website link">Website Link <span>*</span></label>
<input type="url" name="Website link">
</div>
<div class="input-group">
<label for="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?"> In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?<span>*</span></label>
<input type="text" name="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?">
</div>
</div>
<button class="submit" type="submit">Apply Now</button>
</form>
</div>
</div>
Here is the structure of how the payload object should look like in the end:
let payload = {
"fields": [
{ "key" : "candidate_first_name", "value" : "John"},
{ "key" : "candidate_last_name", "value" : "Doe"},
{ "key" : "candidate_email", "value" : "john.doe#gmail.com"},
{ "key" : "candidate_phone", "value" : "1234567890"},
{ "key" : "resume", "value": {
"encoded_data" : "aGVsbG8gd29ybGQ=",
"file_name" : "resume.txt"
}
}
]
};
Note the payload structure is from this link, specifically the "Apply for a Opening" section.
You are running all the code at once (document.ready()), instead you need to run it inside form submit, like $('.applicantForm').on('submit', function(e){}).
Check the updated fiddle
var $ = jQuery;
$(document).ready(function() {
const ApplyOpeningPayloadBuilder = function() {
let payload = {
"fields": []
};
return {
withKeyValue: function(key, value) {
let param = {};
param.key = key;
param.value = value;
payload.fields.push(param);
return this;
},
withFile: function(key, encoded_data, filename) {
let value = {};
value.encoded_data = encoded_data;
value.file_name = filename;
this.withKeyValue(key, value);
return this;
},
build: function() {
return payload;
}
}
}
let encoded_file = "aGVsbG8gd29ybGQ=";
$('.applicantForm').on('submit', function(e) {
e.preventDefault();
let apply_for_an_opening_payload_builder = new ApplyOpeningPayloadBuilder();
$(".applicantForm input[type=text]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=email]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=tel]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=url]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
apply_for_an_opening_payload_builder.withFile("resume", encoded_file, "resume.txt");
let payload = apply_for_an_opening_payload_builder.build();
console.log("Log payload:", payload);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="container" id="json-response">
<div class="form-container">
<div class="header">
<h1>Application form</h1>
</div>
<form action="#" class="applicantForm">
<div class="form-group">
<div class="input-group">
<label for="First Name">First Name <span>*</span></label>
<input type="text" name="First Name">
</div>
<div class="input-group">
<label for="Last Name">Last Name <span>*</span></label>
<input type="text" name="Last Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Email">Email <span>*</span></label>
<input type="email" name="Email">
</div>
<div class="input-group">
<label for="Phone">Phone <span>*</span></label>
<input type="tel" name="Phone">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Resume">Resume <span>*</span></label>
<input class="form-control" type="file" name="Resume">
</div>
<div class="input-group">
<label for="LinkedIn Profile">LinkedIn Profile<span>*</span></label>
<input type="url" name="LinkedIn Profile">
</div>
<div class="input-group">
<label for="Website link">Website Link <span>*</span></label>
<input type="url" name="Website link">
</div>
<div class="input-group">
<label for="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?"> In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?<span>*</span></label>
<input type="text" name="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?">
</div>
</div>
<button class="submit" type="submit">Apply Now</button>
</form>
</div>
</div>
I'm using PHP 7 (Phalcon 3), Bootstrap 3 and JQuery 3. Here is my codepen. When you click on the add button it will clone the form inline.
HTML
<div class="row form-inline">
<div class="form-group col-xs-4">
<label>First name</label>
<input type="text" id="firstname" name="firstname" class="form-control">
</div>
<div class="form-group col-xs-4">
<label>Last name</label>
<input type="text" id="lastname" name="lastname" class="form-control">
</div>
<div class="form-group col-xs-4">
<label>check</label> <br>
<input type="checkbox" class="checkbox" name="check">
</div>
</div>
<button type="button" class="btn btn-primary" id="btn-add">Add</button>
JS
$("#btn-add").click(function() {
$('.row.form-inline:last').clone(true).insertAfter('.row.form-inline:last');
// Don't care about this, it's a checkbox library
$('input').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
increaseArea: '20%',
checked: false
});
$('.row.form-inline:last .checkbox').iCheck('uncheck');
return false;
});
So now I need to send the data to the server but I don't know how can I create a good formatted JSON through Ajax.
I'd like to create an JSON Array based on the number of created clone like this :
[
{
"firstname" : "John",
"lastname" : "Doe",
"check" : true
},
{
"firstname" : "Mark",
"lastname" : "Davidson",
"check" : false
},
{
"firstname" : "Mike",
"lastname" : "Green",
"check" : true
}
]
And in my PHP script I gonna loop through this data easily. So how can I build this JSON array ?
Your first issue is the duplication of id attributes, which is invalid. You can change them to classes, or remove them.
Then, based on your HTML structure, you can use map() to build the array:
var data = $('.form-inline').map(function() {
var $container = $(this);
return {
firstname: $container.find('.firstname').val(),
lastname: $container.find('.lastname').val(),
checkbox: $container.find('.checkbox').prop('checked'),
}
}).get();
Here's a full working example:
$("#btn-add").on('click', function() {
$('.row.form-inline:last').clone(true).insertAfter('.row.form-inline:last');
});
$('#test').on('click', function() {
var data = $('.form-inline').map(function() {
var $container = $(this);
return {
firstname: $container.find('.firstname').val(),
lastname: $container.find('.lastname').val(),
checkbox: $container.find('.checkbox').prop('checked'),
}
}).get();
console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row form-inline">
<div class="form-group col-xs-4">
<label>First name</label>
<input type="text" name="firstname" class="form-control firstname">
</div>
<div class="form-group col-xs-4">
<label>Last name</label>
<input type="text" name="lastname" class="form-control lastname">
</div>
<div class="form-group col-xs-4">
<label>check</label> <br>
<input type="checkbox" class="checkbox" name="check">
</div>
</div>
<button type="button" class="btn btn-primary" id="btn-add">Add</button>
<button id="test">Test</button>
I need to pass the data in the given format.
rules : [{
name:null,
section:null,
data : [{head:null,value:null}]
}],
This is the problem I am facing. Hope somebody could help me sort out a solution. The snippet is given. I need to pass data in the format given above. If another array is needed inside rules[], it is also fine
Is another array needed for head and value inside data[]. This will be also fine, if needed. Hoping for a help. Please help me to have a solution.
Please change the select to read the issues
addForm = new Vue({
el: "#addForm",
data: {
rules: [{
name: null,
section: null,
data: [{
head: null,
value: null
}]
}],
},
methods: {
addNewRules: function() {
this.rules.push({
name: null,
section: null,
data: [{
head: null,
value: null
}]
});
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="addForm">
<div class="card-content" v-for="(bok, index) in rules" :key="index">
<p>This is the first part which is fine for me</p>
<div class="row">
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<select class="form-control" v-model="bok.name">
<option value="Act,1972">Act,1972</option>
<option value="Rule,2012">Rule,2012(CEMR)</option>
<option value="Act,1961">Act,1961</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Section</label>
<input type="text" class="form-control" v-model="bok.section">
</div>
</div>
<div class="row" v-if="bok.name == 'Act,1972'">
<p>When selecting Act,1972 is here rules.data.head. Fine for me</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Arms</label>
<input type="text" class="form-control" v-model="bok.data[0].head" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == 'Rule,2012'">
<p>When Selecting Rule,2012 HOW TO PASS values rules.data.head in this case . There are two input fields here???</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Item</label>
<input type="text" class="form-control" v-model="bok.data[0].head" required="">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Quantity Seized</label>
<input type="text" class="form-control" v-model="bok.data[0].head" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == 'Act,1961'">
<p>When selecting Act,1931 Its a select option, I need to select multiple options from here and pass values as rules.data.head. //After I select multiple options I have input fields corresponding to the options. This to be send as rules.data.value.. How
to do this?</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Select</label>
<select class=" form-control" v-model="bok.data[0].head" multiple="">
<option value="1">life</option>
<option value="2">Enment</option>
</select>
</div>
</div>
</div>
<div class="row" v-if="bok.data[0].head == 1">
<p>If option is 1, i should display this and pass value as rules.data.value . HERE THERE ARE TWO INPUT FIELDS How to pass the values</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area1</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area2</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value">
</div>
</div>
</div>
<div class="row" v-if="bok.data[0].head == 2">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">No.</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Model</label>
<input type="text" class="form-control" required="">
</div>
</div>
</div>
</div>
<a #click="addNewRules">Add Another Rule</a>
</div>
My approach is basically change the type of the data[0].head and data[0].value depending on the options you selected.
So for example, if you select Rule,2012, then data[0].head would be an object with item and qty as its items. And if you select Act,1961, data[0].head would be an array of numbers (e.g. ['1', '2']) and data[0].value would be an object with area_1 and area_2 or number and model or all the four items.
See and try the code snippet to see the code I added/changed.
(Or compare your code with mine and you'd see the changes.)
addForm = new Vue({
el: "#addForm",
data: {
rules: [{
name: null,
section: null,
data: [{
head: null,
value: null
}]
}],
},
methods: {
addNewRules: function() {
this.rules.push({
name: null,
section: null,
data: [{
head: null,
value: null
}]
});
},
removeRuleDataValueProps: function(i) {
var d = this.rules[i].data[0];
if (jQuery.inArray('1', d.head) < 0) {
Vue.delete(d.value, 'area_1');
Vue.delete(d.value, 'area_2');
}
if (jQuery.inArray('2', d.head) < 0) {
Vue.delete(d.value, 'number');
Vue.delete(d.value, 'model');
}
},
_setRuleDataHeadDataType: function(i) {
var d = this.rules[i].data[0],
h = d.head,
_h = d._head,
_restore = true;
if (undefined === _h) {
d._head = h;
_restore = false;
}
switch (this.rules[i].name) {
case 'Rule,2012':
var a = Array.isArray(h);
if (a || null === h || 'object' !== typeof h) {
Vue.set(d, 'head', {});
}
break;
case 'Act,1961':
if (!Array.isArray(h)) {
Vue.set(d, 'head', []);
}
break;
default:
if (_restore && undefined !== _h) {
d.head = _h;
}
break;
}
},
_setRuleDataValueDataType: function(i) {
var d = this.rules[i].data[0],
v = d.value,
_v = d._value,
_restore = true;
if (undefined === _v) {
d._value = v;
_restore = false;
}
switch (this.rules[i].name) {
case 'Act,1972':
case 'Act,1961':
var a = Array.isArray(v);
if (a || null === v || 'object' !== typeof v) {
Vue.set(d, 'value', {});
}
if (_restore) {
this.removeRuleDataValueProps(i);
}
break;
default:
if (_restore && undefined !== _v) {
d.value = _v;
}
break;
}
},
setRuleDataType: function(i, k) {
if (this.rules[i] && this.rules[i].data[0]) {
if (!k || 'head' === k) {
this._setRuleDataHeadDataType(i);
}
if (!k || 'value' === k) {
this._setRuleDataValueDataType(i);
}
}
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="addForm">
<h3>Try the different options and see the JSON output changes.</h3>
<div class="card-content" v-for="(bok, index) in rules" :key="index">
<p>This is the first part which is fine for me</p>
<div class="row">
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<!-- Here we change the type of `bok.data[0].head` depending on the selected option. -->
<select class="form-control" v-model="bok.name" #change="setRuleDataType(index)">
<option value="Act,1972">Act,1972</option>
<option value="Rule,2012">Rule,2012(CEMR)</option>
<option value="Act,1961">Act,1961</option>
</select>
</div>
</div>
<!--</div>-->
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Section</label>
<input type="text" class="form-control" v-model="bok.section">
</div>
</div>
<!-- Here, `bok.data[0].head` is expected to be a `string`. -->
<div class="row" v-if="bok.name == 'Act,1972'">
<p>When selecting Act,1972 is here rules.data.head. Fine for me</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Arms</label>
<input type="text" class="form-control" v-model="bok.data[0].head" #change="setRuleDataType(index, 'value')" required="">
</div>
</div>
</div>
<!-- Here, `bok.data[0].head` is an `object` with 'item' and 'qty'. -->
<div class="row" v-if="bok.name == 'Rule,2012'">
<p>When Selecting Rule,2012 HOW TO PASS values rules.data.head in this case . There are two input fields here???</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Item</label>
<input type="text" class="form-control" v-model="bok.data[0].head.item" required="">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Quantity Seized</label>
<input type="text" class="form-control" v-model="bok.data[0].head.qty" required="">
</div>
</div>
</div>
<!-- Here, `bok.data[0].head` would be an array of numbers. -->
<div class="row" v-if="bok.name == 'Act,1961'">
<p>When selecting Act,1931 Its a select option, I need to select multiple options from here and pass values as rules.data.head. //After I select multiple options I have input fields corresponding to the options. This to be send as rules.data.value.. How
to do this?</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Select</label>
<select class=" form-control" v-model="bok.data[0].head" #change="removeRuleDataValueProps(index)" multiple="">
<option value="1">life</option>
<option value="2">Enment</option>
</select>
</div>
</div>
</div>
<div class="row" v-if="jQuery.inArray('1', bok.data[0].head) > -1">
<p>If option is 1, i should display this and pass value as rules.data.value . HERE THERE ARE TWO INPUT FIELDS How to pass the values</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area1</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value.area_1">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area2</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value.area_2">
</div>
</div>
</div>
<div class="row" v-if="jQuery.inArray('2', bok.data[0].head) > -1">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">No.</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value.number">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Model</label>
<input type="text" class="form-control" required="" v-model="bok.data[0].value.model">
</div>
</div>
</div>
<h3>The JSON value of <code>bok</code></h3>
<textarea rows="3" cols="75%" readonly>{{ JSON.stringify(bok) }}</textarea>
</div>
<a #click="addNewRules">Add Another Rule</a>
</div>
My opinion,
Based on the HTML you provied, create one data property=ruleTemplate (it makes sure v-model with related form controls).
When add new rules, push one clone of the template to the rules
When you need the data, just convert the rules to the specific format like
this.getFormattedRules in below demo.
Below is the demo:
addForm = new Vue({
el: "#addForm",
data: {
ruleTemplates: {
name: '',
section: '',
subMenu: {
'Act,1972': '',
'Rule,2012': {'item': '','qty': ''},
'Act,1961': {'head':[], options:{'option1':'', 'option2':''}}
}
},
rules: [{
name: '',
section: '',
subMenu: {
'Act,1972': '',
'Rule,2012': {'item': '','qty': ''},
'Act,1961': {'head':[], options:{'option1':'', 'option2':''}}
}
}
],
},
computed: {
formatedJson: function () {
let handler1972 = function (data) {
return [{'head': 'Arms', 'value': data}]
}
let handler2012 = function (data) {
return [{'head': 'item', 'value': data.item},{'head': 'qty', 'value': data.qty}]
}
let handler1961 = function (data) {
return [{'head': 'option1', 'value': data.options.option1},{'head': 'option1', 'value': data.options.option2}]
}
let handlers = {'Act,1972': handler1972, 'Rule,2012': handler2012, 'Act,1961': handler1961
}
return this.rules.map((rule) => {
let formatedRule = new Object()
// convert the rule to the specific format
formatedRule.name = rule.name
formatedRule.section = rule.section
handler = handlers[rule.name]
formatedRule.data = handler ? handler(rule.subMenu[rule.name]) : []
return formatedRule
})
}
},
methods: {
addNewRules: function() {
this.rules.push(Object.assign({},this.ruleTemplates))
}
}
})
.show-format {
position:absolute;
top:2px;
right -4px;
background-color:gray
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="addForm">
<div class="show-format">Format: {{formatedJson}}</div>
<div class="card-content" v-for="(bok, index) in rules" :key="index">
<p>This is the first part which is fine for me</p>
<div class="row">
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<select class="form-control" v-model="bok.name">
<option value="Act,1972">Act,1972</option>
<option value="Rule,2012">Rule,2012(CEMR)</option>
<option value="Act,1961">Act,1961</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label">Section</label>
<input type="text" class="form-control" v-model="bok.section">
</div>
</div>
<div class="row" v-if="bok.name == 'Act,1972'">
<p>When selecting Act,1972 is here rules.data.head. Fine for me</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Arms</label>
<input type="text" class="form-control" v-model="bok.subMenu['Act,1972']" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == 'Rule,2012'">
<p>When Selecting Rule,2012 HOW TO PASS values rules.data.head in this case . There are two input fields here???</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Item</label>
<input type="text" class="form-control" v-model="bok.subMenu['Rule,2012']['item']" required="">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Quantity Seized</label>
<input type="text" class="form-control" v-model="bok.subMenu['Rule,2012']['qty']" required="">
</div>
</div>
</div>
<div class="row" v-if="bok.name == 'Act,1961'">
<p>When selecting Act,1931 Its a select option, I need to select multiple options from here and pass values as rules.data.head. //After I select multiple options I have input fields corresponding to the options. This to be send as rules.data.value.. How
to do this?</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Select</label>
<select class=" form-control" v-model="bok.subMenu['Act,1961'].head" >
<option value="1">life</option>
<option value="2">Enment</option>
</select>
</div>
</div>
</div>
<div class="row" v-if="bok.subMenu['Act,1961'].head == 1">
<p>If option is 1, i should display this and pass value as rules.data.value . HERE THERE ARE TWO INPUT FIELDS How to pass the values</p>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area1</label>
<input type="text" class="form-control" required="" v-model="bok.subMenu['Act,1961'].options.option1">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Area2</label>
<input type="text" class="form-control" required="" v-model="bok.subMenu['Act,1961'].options.option2">
</div>
</div>
</div>
<div class="row" v-if="bok.subMenu['Act,1961'].head == 2">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">No.</label>
<input type="text" class="form-control" required="" v-model="bok.subMenu['Act,1961'].options.option1">
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Model</label>
<input type="text" class="form-control" required="" v-model="bok.subMenu['Act,1961'].options.option2">
</div>
</div>
</div>
</div>
<a #click="addNewRules" style="background-color:green">Add Another Rule</a>
</div>
hey why don't you go with multi-select checkbox drop-down and apply v-model on checkbox. ?
Link: How to use Checkbox inside Select Option
I have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.