I need to get value from form, format it to JSON and post it via AJAX. This is the format I want to achieve:
{
items: [
{ id: 7, name: 'Book', price: 5.7 },
{ id: 5, name: 'Pencil', price: 2.5 }
]
}
Here's the HTML:
(function($){
var $form = $('form');
// serializeArray format is way off from what I need
var rawData = $form.serializeArray();
console.log(rawData)
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset>
<h2>Product 1</h2>
<input type="hidden" name="items[0][id]" value="7">
<input type="text" name="items[0][name]" value="Book">
<input type="number" name="items[0][price]" value="5.7">
</fieldset>
<fieldset>
<h2>Product 2</h2>
<input type="hidden" name="items[1][id]" value="5">
<input type="text" name="items[1][name]" value="Pencil">
<input type="number" name="items[1][price]" value="2.5">
</fieldset>
</form>
Should I loop and use regex to parse the name? or is there built-in way?
I can change the <form> format if needed.
You can't use the default serialization here, instead you can do a manual serialization like
(function($) {
var $fieldsets = $('form fieldset');
var items = $fieldsets.map(function(i, fs) {
var obj = {};
$(fs).find('input').each(function() {
obj[this.name.match(/\[([^\[]*)\]$/)[1]] = this.value;
});
return obj;
}).get();
var rawData = {
items: items
};
console.log(rawData)
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset>
<h2>Product 1</h2>
<input type="hidden" name="items[0][id]" value="7">
<input type="text" name="items[0][name]" value="Book">
<input type="number" name="items[0][price]" value="5.7">
</fieldset>
<fieldset>
<h2>Product 2</h2>
<input type="hidden" name="items[1][id]" value="5">
<input type="text" name="items[1][name]" value="Pencil">
<input type="number" name="items[1][price]" value="2.5">
</fieldset>
</form>
Please take a look at this approach. We can't just use $.serializeArray() but also we need some custom code as follows. Actually we need to iterate over all <fieldset> to get JSON as we needed:
(function($) {
var $form = $('form');
var fieldSets = $form.find("fieldset");
var result = {
items: []
};
fieldSets.each(function() {
var fields = {};
$.each($(this).serializeArray(), function() {
fields[this.name] = this.value;
});
result.items.push(fields);
});
console.log(result);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset>
<h2>Product 1</h2>
<input type="hidden" name="id" value="7">
<input type="text" name="name" value="Book">
<input type="number" name="price" value="5.7">
</fieldset>
<fieldset>
<h2>Product 2</h2>
<input type="hidden" name="id" value="5">
<input type="text" name="name" value="Pencil">
<input type="number" name="price" value="2.5">
</fieldset>
</form>
Note: Modified the HTML a bit as instead of name="items[0][id]" i have given as name="id"
Yes, you will need to parse the name field yourself. There is no automated method of parsing a custom field. There are, of course, multiple methods of doing so.
NOTE: I'm assuming that your name="items[0][id]" field specifies that this must be the 0th item in the resulting array, and that such sets of <input> fields are not, necessarily, in ascending order by item # within the DOM. In other words, the item[N] should be controlling over it being the Qth <fieldset> in the <form>.
You could use serializeArray() and then process that data:
(function($){
var $form = $('form');
var data = $form.serializeArray();
var result = {items:[]};
data.forEach(function(input){
nameArray = input.name.split(/[[\]]/);
item = nameArray[1];
prop = nameArray[3];
if(typeof result.items[item] !== 'object'){
result.items[item]={};
}
if(typeof result.items[item][prop] !== 'undefined'){
//Consistency check the name attribute
console.log('Warning duplicate "name" property =' + input.name);
}
result.items[item][prop]=input.value;
});
console.log(result);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset>
<h2>Product 1</h2>
<input type="hidden" name="items[0][id]" value="7">
<input type="text" name="items[0][name]" value="Book">
<input type="number" name="items[0][price]" value="5.7">
</fieldset>
<fieldset>
<h2>Product 2</h2>
<input type="hidden" name="items[1][id]" value="5">
<input type="text" name="items[1][name]" value="Pencil">
<input type="number" name="items[1][price]" value="2.5">
</fieldset>
</form>
Or, you could directly process it from the DOM:
(function($){
var result = {items:[]};
$('form fieldset input').each(function(){
nameArray = this.name.split(/[[\]]/);
item = nameArray[1];
prop = nameArray[3];
if(typeof result.items[item] !== 'object'){
result.items[item]={};
}
if(typeof result.items[item][prop] !== 'undefined'){
//Consistency check the name attribute
console.log('Warning duplicate "name" property =' + this.name);
}
result.items[item][prop]=this.value;
});
console.log(result);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset>
<h2>Product 1</h2>
<input type="hidden" name="items[0][id]" value="7">
<input type="text" name="items[0][name]" value="Book">
<input type="number" name="items[0][price]" value="5.7">
</fieldset>
<fieldset>
<h2>Product 2</h2>
<input type="hidden" name="items[1][id]" value="5">
<input type="text" name="items[1][name]" value="Pencil">
<input type="number" name="items[1][price]" value="2.5">
</fieldset>
</form>
Related
I have questions array in which I want to add HTML form data when I hit the submit button in the format as shown below:
var questions = [
new Question("What language are we learning today?", ["Java", "C#","C++", "JavaScript"], "JavaScript"),
new Question("Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS")
];
HTML form that I have created
<form action="" method="post" >
<label>Enter question:</label>
<input type="text" id="question" name="question" /><br/>
<label>Option1:</label>
<input type="text" id="option1" name ="option1"/><br/>
<label>Option2:</label>
<input type="text" id="option2" name ="option2"/><br/>
<label>Option3:</label>
<input type="text" id="option3" name ="option3"/><br/>
<label>Option4:</label>
<input type="text" id="option4" name ="option4"/><br/>
<label>Enter answer</label>
<input type="text" id="answer" name="answer" /><br/>
<input type="submit" name="submit" value="Add quiz" />
</form>
So, I want to add data into array like this: new question("question?",["option1","option2","option3","option4"],"answer")
You can do it like this:
function Question (pquestion, poptions, panswer) {
this.question = pquestion;
this.options = poptions;
this.answer = panswer;
}
var questions = [
new Question("What language are we learning today?", ["Java", "C#","C++", "JavaScript"], "JavaScript"),
new Question("Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS")
];
function addQuestion() {
var question = document.getElementById("qs").value;
var option1 = document.getElementById("option1").value;
var option2 = document.getElementById("option2").value;
var option3 = document.getElementById("option3").value;
var option4 = document.getElementById("option4").value;
var answer = document.getElementById("answer").value;
var numberOfQuestions = questions.length;
questions[numberOfQuestions] = new Question(question, [option1, option2, option3, option4], answer);
alert("Thank you. We now have " + questions.length + " questions.");
}
<head>
<title>test</title>
</head>
<body>
<form>
<label>Enter question:</label>
<input type="text" id="qs" name="qs" /><br/>
<label>Option1:</label>
<input type="text" id="option1" name ="option1"/><br/>
<label>Option2:</label>
<input type="text" id="option2" name ="option2"/><br/>
<label>Option3:</label>
<input type="text" id="option3" name ="option3"/><br/>
<label>Option4:</label>
<input type="text" id="option4" name ="option4"/><br/>
<label>Enter answer</label>
<input type="text" id="answer" name="answer" /><br/>
<input type="button" name="submit" onclick="addQuestion();" value="Add quiz" />
</form>
</body>
Example code:
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
On form submission the URL should look like:
http://some-website.tld/action?anythingOne=one,three&otherThingTwo=Fifty
What I am observing now is,
http://some-website.tld/action?anythingOne=one&anythingOne=three&otherThingTwo=Fifty
The serialize() or serializeArray() is not working in this case. Any ideas?
You could grab the result of .serializeArray and transform it into the desired format:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serializeArray();
var dataByKey = data
.reduce((result, entry) => {
var name = entry.name.replace(/\[\]$/, '');
(result[name] || (result[name] = [])).push(entry.value);
return result;
}, {});
Object.keys(dataByKey)
.forEach((key, _) => dataByKey[key] = dataByKey[key].join(','));
console.log(dataByKey);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<fieldset>
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
</fieldset>
<fieldset>
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
</fieldset>
<input type="submit" />
</form>
If you want, you can also use pure javascript without jQuery to get all the checked checkboxes' value, http://jsfiddle.net/jx76dpkh/1/
<form id="myForm" method="get">
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
<input type="submit" />
</form>
JS:
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (e) => {
e.preventDefault();
let checkboxes = Array.from(myForm.querySelectorAll('input[type="checkbox"]:checked');// build the array like element list to an array
let anythingOne = checkboxes.filter( box => box.name === 'anythingOne[]').map(item => item.value);
let otherThingTwo = checkboxes.filter( box => box.name === 'otherThingTwo[]').map(item => item.value);
});
In case, you are allowed to change html, here is a solution using hidden fields.
function updateChecks() {
$.each(['anythingOne', 'otherThingTwo'], function(i, field) {
var values = $('input[type=checkbox][data-for=' + field + ']:checked').map(function() {
return this.value;
}).get().join(',');
$('input[type=hidden][name=' + field + ']').val(values);
});
}
$(function() {
$('form').on('submit', function(e) {
updateChecks();
});
updateChecks();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="hidden" name="anythingOne" value='' />
<input type="hidden" name="otherThingTwo" value='' />
<input type="checkbox" data-for="anythingOne" value='one' checked='' />
<input type="checkbox" data-for="anythingOne" value='two' />
<input type="checkbox" data-for="anythingOne" value='three' checked='' />
<input type="checkbox" data-for="otherThingTwo" value='Forty' />
<input type="checkbox" data-for="otherThingTwo" value='Fifty' checked='' />
</form>
You could get query string parameters using by serializeArray() method. Then use reduce() to group parameter values by name, and map() to get array of key-value pairs. Then it is possible to concatenate the pairs separated by & using join() method. For example the following snippet creates a target URL using actual value of the form action (current URL by default) and values of checked checkboxes:
$('form').submit(function() {
var queryString = $(this).serializeArray()
.reduce(function(transformed, current) {
var existing = transformed.find(function(param) {
return param.name === current.name;
});
if (existing)
existing.value += (',' + current.value);
else
transformed.push(current);
return transformed;
}, [])
.map(function(param) {
return param.name + '=' + param.value;
})
.join('&');
var action = $(this).prop('action');
var delimiter = (~action.indexOf('?')) ? '&' : '?';
$(this).prop('action', action + delimiter + queryString);
// Only for display result. Remove on real page.
var url = $(this).prop('action');
console.log(url);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="GET">
<input type="checkbox" name="anythingOne" value='one'>
<input type="checkbox" name="anythingOne" value='two'>
<input type="checkbox" name="anythingOne" value='three'>
<input type="checkbox" name="otherThingTwo" value='Forty'>
<input type="checkbox" name="otherThingTwo" value='Fifty'>
<button type="submit">Show target URL</button>
</form>
The latest 3 lines are used only to prevent the form sending and display resulted URL.
Also it is possible to solve the question using only serialize() mathod and regular expressions, but it requires lookbehind assertion support in browsers.
You can collect all the checked boxer and join the different parts of the strings.This may not be the most neat or efficient solution, but it works. I used a button to trigger the concatenation. See my comments within the code.
$(document).ready(function(){
$("button").click(function(){
/* concatenate anythingOne form*/
//collect anythingOne input
var joined_serialized = []
var anythingOne = [];
$.each($("input[name='anythingOne[]']:checked"), function(){
anythingOne.push($(this).val());
});
//join otherThingTwo input
var anythingOne_serialized = "";
if(anythingOne.length > 0){ //only collect if checked
anythingOne_serialized = "anythingOne=" + anythingOne.join(",");
joined_serialized.push(anythingOne_serialized)
}
/* concatenate otherThingTwo form*/
//collect otherThingTwo input
var otherThingTwo = []
$.each($("input[name='otherThingTwo[]']:checked"), function(){
otherThingTwo.push($(this).val());
});
//join otherThingTwo input
var otherThingTwo_serialized = "";
if(otherThingTwo.length > 0){ //only collect if checked
otherThingTwo_serialized = "otherThingTwo=" + otherThingTwo.join(",");
joined_serialized.push(otherThingTwo_serialized)
}
/*join different form names*/
var joined_serialized = joined_serialized.join("&")
if(joined_serialized.length == 1){ //remove last & if only one form is checked
joined_serialized = joined_serialized.slice(0, -1)
}
/*concatenated forms with website*/
var result = "http://some-website.tld/action?"+joined_serialized
console.log(result) //E.g. when Two, Three and Forty are checked: http://some-website.tld/action?anythingOne=two,three&otherThingTwo=Forty
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
<button>submit<button/>
I created a form with three fields first_name, Last_name, city and in the fourth field, I am having an Id column which is read-only. When the user fills the first three fields in the form, before submitting it should generate an id in the fourth column but here it should use the first two alphabets that are in the fields to generate an Id
For eg. First_name = Roid, Last_name = Steve, city = California then in the fourth field it should automatically generate this id = rostca (all the first two alphabets)
How to achieve this?
Here is a JavaScript version to answer to your issue.
(function () {
populate();
})();
function populate () {
var str = "";
Array.from(document.getElementsByClassName("inputs")).forEach(function (element) {
str += element.value.substr(0, 2).toLowerCase();
});
document.getElementById("output").value = str;
}
<div>
<input type="text" class="inputs" value="Roid" oninput="populate();" />
<input type="text" class="inputs" value="Steve" oninput="populate();" />
<input type="text" class="inputs" value="California" oninput="populate();" />
<input id="output" type="text" readonly disabled />
</div>
Here is a jQuery answer to your issue.
$(function () {
populate();
$(".inputs").on("input", function() {
populate();
});
});
function populate () {
var str = "";
$(".inputs").each(function () {
str += $(this).val().substr(0, 2).toLowerCase();
});
$("#output").val(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" class="inputs" value="Roid" />
<input type="text" class="inputs" value="Steve" />
<input type="text" class="inputs" value="California" />
<input id="output" type="text" readonly disabled />
</div>
Check below code,
function TextChanged(){
var first_name = document.getElementById("first_name").value;
var Last_name = document.getElementById("Last_name").value;
var city = document.getElementById("city").value;
document.getElementById("id").value = first_name.substring(0, 2) +Last_name.substring(0, 2) +city.substring(0, 2);
}
<input type="text" id="first_name" onblur="TextChanged()">
<input type="text" id="Last_name" onblur="TextChanged()">
<input type="text" id="city" onblur="TextChanged()">
<input type="text" id="id" readonly>
Check here jsbin demo, https://jsbin.com/qegazab/edit?html,js,console,output
I have 3 textboxs.Their names and ids are different.I can merge their values with their names or ids but I need to merge their values with type. How can I do it.
<input type="text" id="txt1" name="textbox1">
<input type="text" id="txt2" name="textbox2">
<input type="text" id="txt3" name="textbox3">
You can get all the textbox elements by their type using document.querySelectorAll("input[type=text]").
If by merge you mean concatenating the values.
var textBoxes= document.querySelectorAll("input[type=text]");
var mergedValue;
for(var i=0;i<textBoxes.length;i++)
{
mergedValue+=textBoxes[i].value;
}
var dataVal=document.querySelectorAll('[type=text]');
var myVal="";
dataVal.forEach(function(entry) {
myVal+=entry.value;
});
console.log(myVal);
<input type="text" id="txt1" name="textbox1" value="2">
<input type="text" id="txt2" name="textbox2" value="2">
<input type="text" id="txt3" name="textbox3" value="2">
Here is another possible solution.
function mergeData() {
var textboxes = document.getElementsByTagName("input");
var mergedText = "";
for (var i = 0; i < textboxes.length; i++) {
if (textboxes[i].type === "text" ) {
mergedText = mergedText + textboxes[i].value;
}
}
document.getElementById("merged").innerHTML = mergedText;
}
<input type="text" id="txt1" name="textbox1">
<input type="text" id="txt2" name="textbox2">
<input type="text" id="txt3" name="textbox3">
<button onclick="mergeData()">Merge</button>
<div id="merged"></div>
I have a lot of elements which are used identical class-name. Now I need to calculate the number of selected items.
For e.g. something like this: (however this example doesn't work correctly)
$("#btn").click(function(){
if($(".necessarily").val() == ''){
$(".necessarily").css('border','1px solid red');
}
// also I want the number of input.necessarily which are empty
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" /><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" /><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
Now I want the number of those inputs which are empty ..., How can I calculate that?
.val() method returns .value property of the first element in the collection. You can filter the empty inputs using the .filter() method and read the .length property of the filtered collection:
var $empty = $(".necessarily").filter(function() {
// you can use the `$.trim` method for trimming whitespaces
// return $.trim(this.value).length === 0;
return this.value.length === 0;
});
if ( $empty.length > 0 ) {
}
If you want to add a border to the empty fields you can declare a CSS class and use the .removeClass and .addClass methods:
CSS:
.red_border {
border: 1px solid red;
}
JavaScript:
var $empty = $(".necessarily").removeClass('red_border').filter(function() {
return this.value.length === 0;
}).addClass('red_border');
You'd do better looking at the HTML5 Contraint API rather than doing what you're currently doing, which is a more manual and time-consuming way.
Instead of giving each field a class 'necessarily' (sidenote: the word you need is 'necessary', not 'necessarily', or, better still, 'required') use the required attribute. So:
<input name="last-name" required type="text" />
Then in your jQuery you can target empty fields with:
$('input:invalid').css('border', 'solid 1px red');
If all you're doing is highlighting bad fields, you don't even need JavaScript for this. You can do the same thing via CSS:
input:invalid { border: solid 1px red; }
The only problem with that is the styling will be showed even before the user has filled out the form, which is almost never desirable. You could get round this by logging, via JS, when the form is submitted, and only then activating the styles:
JS:
$('form').on('submit', function() { $(this).addClass('show-errors'); });
CSS:
.show-errors input:invalid { border: solid 1px red; }
Try this code:
$("#btn").click(function(){
var selectedcount = $(".necessarily").length; //no. of elements with necessarily class name
var emptyInputCount=0;
$(".necessarily").each(function(){
if($(this).val() == ''){
emptyInputCount++;
}
});
Try with each loop on the target elements.
$(function() {
$("#btn").click(function() {
var i = 0;
$(".necessarily").each(function() {
if ($(this).val() == "") {
$(this).css('border', '1px solid red');
i++;
}
});
alert(i); //Number of input element with no value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" />
<br>
<br>
<input name="last-name" class="necessarily" type="text" />
<br>
<br>
<input name="email" class="necessarily" type="email" />
<br>
<br>
<input name="password" class="necessarily" type="password" />
<br>
<br>
<input name="address" class="anything" type="text" />
<br>
<br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
Hope this helps!
You can use filter() like following example bellow.
var empty_inputs = $('.necessarily').filter(function(){
return $(this).val()=='';
});
empty_inputs.length will return 3 in my example.
Hope this helps.
var empty_inputs = $('.necessarily').filter(function(){
return $(this).val()=='';
});
console.log(empty_inputs.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="first-name" class="necessarily" type="text" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" value="Register"/><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" value="Register"/><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
Hope this helps.
You need to:
query all elements by className
filter the jQuery Collection in order to keep only the elements that have no value
doSomethingElse
so, this maybe could help you:
function CheckEmptyCtrl($) {
'use strict';
var self = this;
self.target = $('.necessarily');
self.empty = self.target.filter(function(index, item) {
return !($(item).val().trim());
});
$('#result').append(self.empty.length + ' elements have no values.');
console.log(self.empty.length, self.empty);
}
jQuery(document).ready(CheckEmptyCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="result"></div>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" value="notEmpty" /><br><br>
<input name="last-name" class="necessarily" type="text" /><br><br>
<input name="email" class="necessarily" type="email" /><br><br>
<input name="password" class="necessarily" type="password" /><br><br>
<input name="address" class="anything" type="text" /><br><br>
<input name="btn" id="btn" type="submit" value="Register" />
</form>
You need to loop over the all of the inputs and count how many are empty. In the same loop you can also count the number of .necessarily inputs which are empty.
This example will output the result to the .result span.
$("#btn").click(function() {
var inputs = $("form input");
var emptyNecessarilyCount = 0;
var totalEmpty = 0
inputs.each(function() {
if ($(this).val() == "") {
totalEmpty++;
if ($(this).hasClass('necessarily')) {
emptyNecessarilyCount++;
}
}
});
$('.result').append("Total: " + totalEmpty);
$('.result2').append("Necessarily: " + emptyNecessarilyCount);
});
span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frm" action="#">
<input name="first-name" class="necessarily" type="text" />
<br>
<input name="last-name" class="necessarily" type="text" />
<br>
<input name="email" class="necessarily" type="email" />
<br>
<input name="password" class="necessarily" type="password" />
<br>
<input name="address" class="anything" type="text" />
<br>
<input name="btn" id="btn" type="submit" value="Register" />
<span class="result"></span>
<span class="result2"></span>
</form>