How to check how many empty input fields there are? - javascript

I've about 5 input fields and before checking them I want to be able to alert using javascript to let the user know that there are empty fields which must be filled in before checking.
So I want to be able to alert using js if 2 of the 5 input fields are empty!
Can anybody please help me with this! I've research a lot and read some blogs that saying to use the "length" but couldn't figure it out!
So as soon as the user clicks on the submit button with the id of "submit", an alert would prompt saying must fill in at least 2 out of the 5 input boxes...
Here is my code:
<input type="text" id="a" value="" />
<input type="text" id="b" value="" />
<input type="text" id="c" value="" />
<input type="text" id="d" value="" />
<input type="text" id="e" value="" />
<input type="submit" id="submit" value="Check Form" />
Thanks

document.getElementById('submit').onclick = function() {
var inputs = document.getElementsByTagName('input'),
empty = 0;
for (var i = 0, len = inputs.length - 1; i < len; i++) {
empty += !inputs[i].value;
}
if (empty > 3) {
alert('You must fill in at least 2 fields');
}
};
Example: http://jsfiddle.net/Fn8cw/

With jquery you can loop through all of your input fields and increment a variable if the input field is empty:
$("#your_form_div").change(function(){
$(this).parents('form')
.find(':input').each(function(i) {
if( $(this).val() )
//here your incremented variable
}); });

this will tell you how many are empty
var empty = $('input:text').filter(function() { return $(this).val() == ""; });
if (empty.length > 3){
alert("you must fill in at least two inputs");
}
here is a working demo
of course I'm assumming you can use jQuery

Related

One javascript prompt overwrites the other prompt and i have to click submit twice to send the form

I am trying to create a form which will (a) prompt user to fill in the missing fields and (b) prompt user to check at least one checkbox. But somehow the prompt textbox.setCustomValidity('Choose at least one.'); is always overwritten by e.target.setCustomValidity("Fill in the missing field");.
And there is one more problem in Chromium. It looks like I have to click Submit button twice to be able to submit...
//Function that checks if any input text field is empty and prompts user
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Fill in the missing field");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
});
//Functions which checks if at least one checkbox is checked and prompts user to check at least one
function chooseKrozek() {
if (document.querySelectorAll('input[name="krozek"]:checked').length > 0){
document.querySelector("#krozki-checkbox-placeholder").value = document.querySelector('input[name="krozek"]:checked').value;
}
else {
document.querySelector("#krozki-checkbox-placeholder").value = "";
}
}
function promptIzberiKrozek(textbox) {
if (textbox.value == ''){
textbox.setCustomValidity('Choose at least one.');
}
else {
textbox.setCustomValidity('');
}
}
<form target="_blank">
name:<br>
<input class="vnos" type="text" name="ime" value="" required><br>
surname:<br>
<input class="vnos" type="text" name="priimek" value="" required>
<br><br>
checkboxes:<br>
<!-- placeholder to be able to display the prompt on invalid value -->
<input id="krozki-checkbox-placeholder" type="text" value="" oninvalid="promptIzberiKrozek()" required style="width:5px;height:5px;opacity:0;position:absolute;"/>
<!-- On checkbox click function chooseKrozek() is called -->
<input type="checkbox" name="krozek" onClick="chooseKrozek()" value="linux-c-arm">LINUX/C/ARM™
<input type="checkbox" name="krozek" onClick="chooseKrozek()" value="linux-desktop">LINUX/DESKTOP™
<input type="checkbox" name="krozek" onClick="chooseKrozek()" value="linux-office">LINUX/OFFICE™
<br><br>
<input type="submit" value="Submit">
</form>

Limit number of boxes checked when arrays are involved

I'm pretty amateurish when it comes to JavaScript stuff, so I apologize if this question comes off as a bit dumb.
I'm currently trying to code something that involves forms with a limit on how many checkboxes can be selected. The method I've come across that has worked best for my purposes so far is the one detailed here:
http://www.javascriptkit.com/script/script2/checkboxlimit.shtml
It works for the most part but I run into an issue when checkboxes need to output an array. For example, if I write the input line as:
<input type="checkbox" name="choice[]" value="One" /> One<br />
<input type="checkbox" name="choice[]" value="Two" /> Two<br />
<input type="checkbox" name="choice[]" value="Three" /> Three<br />
I've tried quite a few things but I can't figure out how to change the code so that it works with the brackets in the input's name field.
Couple things here:
The tutorial references checkboxlimit(document.forms.world.countries, 2). This will not work with []. You can use getElementsByClassName
It doesn't look like this will work as expected if you uncheck a box because it works on 'onclick', and never increases the number of checked boxes.
I've adapted the code in this fiddle: https://jsfiddle.net/ad8t5sju/
What I changed:
var elems = form.getElementsByClassName('checkbox');
I used getElementsByClassName here so that we can easily fetch the checkboxes that are the particular form's children. HTMLElement only has getElementsByTagName and getElementsByClassName unfortunately, so we can't easily use names here.
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked) {
++count;
}
You'll see here that I take into account the already checked boxes. That way if you have 1 checked by default, you can check another 4 if your limit is 5.
elems[i].addEventListener('click', function() {
if (this.checked) {
if (count + 1 > limit) {
alert ("no more than " + limit + " must be checked");
this.checked = false;
return false;
}
++count;
} else {
--count;
if (count < 0) {
count = 0;
}
}
});
Here, instead of adding 0 when a box is being unchecked, we reduce the count. That's so the same box won't count twice if we untick and tick again.
Using that script above, you can change it into using .elements to get the group of elements and applying that same custom function:
<script type="text/javascript">
// Syntax: checkboxlimit(checkbox_reference, limit)
var world_form = document.forms.choices; // the form
var my_checkboxes = world_form.elements['choice[]']; // check boxes
checkboxlimit(my_checkboxes, 2);
</script>
Fiddle
Simple and easy way
<form id="world" name="world">
<input type="checkbox" name="countries[]" /> USA<br />
<input type="checkbox" name="countries[]" /> Canada<br />
<input type="checkbox" name="countries[]" /> Japan<br />
<input type="checkbox" name="countries[]" /> China<br />
<input type="checkbox" name="countries[]" /> France<br />
<input type="submit" />
</form>
<script type="text/javascript">
$('input:checkbox').change(function() {
var limit = 2;
if($("[type='checkbox']:checked").length > limit)
{
alert("You can only select a maximum of "+limit+" checkboxes")
this.checked=false;
}
});
</script>

How to disable submit button until all text fields are full and file is selected

I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.
The distilled version of the code I'm working with is here:
HTML
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
JS
$('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
$('.submit').prop('disabled', false);
}
});
})()
Thanks for your help
https://jsfiddle.net/xG2KS/482/
Try capture the event on those field and checking the empty values by using another function, see below code :
$(':input').on('change keyup', function () {
// call the function after
// both change and keyup event trigger
var k = checking();
// if value inc not 0
if (k) $('.submit').prop('disabled', true);
// if value inc is 0
else $('.submit').prop('disabled', false);
});
// this function check for empty values
function checking() {
var inc = 0;
// capture all input except submit button
$(':input:not(:submit)').each(function () {
if ($(this).val() == "") inc++;
});
return inc;
}
This is just an example, but the logic somehow like that.
Update :
Event Delegation. You might need read this
// document -> can be replaced with nearest parent/container
// which is already exist on the page,
// something that hold dynamic data(in your case form input)
$(document).on('change keyup',':input', function (){..});
DEMO
Please see this fiddle https://jsfiddle.net/xG2KS/482/
$('input').on('change',function(){
var empty = $('div').find("input").filter(function() {
return this.value === "";
});
if(empty.length>0) {
$('.submit').prop('disabled', true);
}
else{
$('.submit').prop('disabled', false);
}
});
[1]:
The trick is
don’t disable the submit button; otherwise the user can’t click on it and testing won’t work
only when processing, only return true if all tests are satisfied
Here is a modified version of the HTML:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file"><br>
<input type="text" name="name"><br>
<input type="text" name="email"><br>
<button name="submit" type="submit">Upload</button>
</form>
and some pure JavaScript:
window.onload=init;
function init() {
var form=document.getElementById('test');
form.onsubmit=testSubmit;
function testSubmit() {
if(!form['file'].value) return false;
if(!form['name'].value) return false;
if(!form['email'].value) return false;
}
}
Note that I have removed all traces of XHTML in the HTML. That’s not necessary, of course, but HTML5 does allow a simpler version of the above, without JavaScript. Simply use the required attribute:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file" required><br>
<input type="text" name="name" required><br>
<input type="text" name="email" required><br>
<button name="submit" type="submit">Upload</button>
</form>
This prevents form submission if a required field is empty and works for all modern (not IE8) browsers.
Listen for the input event on file and text input elements, count number of unfilled inputs and, set the submit button's disabled property based on that number. Check out the demo below.
$(':text,:file').on('input', function() {
//find number of unfilled inputs
var n = $(':text,:file').filter(function() {
return this.value.trim().length == 0;
}).length;
//set disabled property of submit based on number
$('#submit').prop('disabled', n != 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
For my approach, I'd rather use array to store if all the conditions are true. Then use every to make sure that all is true
$(function(){
function validateSubmit()
{
var result = [];
$('input[type=file], input[type=text]').each(function(){
if ($(this).val() == "")
result.push(false);
else
result.push(true);
});
return result;
}
$('input[type=file], input[type=text]').bind('change keyup', function(){
var res = validateSubmit().every(function(elem){
return elem == true;
});
if (res)
$('input[type=submit]').attr('disabled', false);
else
$('input[type=submit]').attr('disabled', true);
});
});
Fiddle

Javascript/ HTML Transferring form Controls to submit

I have been attempting to create a form with 5 text boxes, 1 drop down and a text area. My intention is simple; select an option from the Drop down( except the first i.e "--Select--"), enter the contents into the text box and text area. Once I click submit all the above entered information should get appended to specific links that is hard coded into each drop down option.
My challenge here is that when I click submit, the controls are no getting passed to the new form i.e. the desired page opens,but the form fields do not get entered. I have cross verified and confirmed that the ids are correct.. I'm guessing that i have made a mistake in the validation. Kindly point out my mistake..
Javascript Code
<script type="text/javascript">
function dpdown(form)
{
var a="&name="+document.getElementById('name').value; //textbox
var b="&job_id="+document.getElementById('job_id').value;//textbox
var c="&major"+document.getElementById("major').value;//textbox
var d="&native="+document.getElementById('native').value;//textbox
var e="&age="+document.getElementById('age').value;//textbox
var f="&details="+encodeURIComponent(document.getElementById('details').value);//textarea
var i, counter = 0;
var ddl = document.getElementById("jobs");//dropdown
var selectedValue = ddl.options[ddl.selectedIndex].value;
for(var i=0; i < obj.options.length; i++)
{
if(obj.options[i].selected) // to check if the person has chosen a suitable degree
if (selectedValue == "selectdegree")
{
alert("Please select your correct degree");
}
else
{
++counter;
window.open('https://'+form.elements[i].value+a+b+c+d+e+f,'_blank'); // when the submit button is clicked, all the above fields should get appended to a preset link which has been hardcoded for each degree.
}
}
}
function cleartext()// to clear the form (works correctly)
{
document.form.details.value='';
}
HTML Code
<form onsubmit="dpdown(this); return false;"> // at the beginning of the form
'
'
'
'
<input type="submit" value=" Create form" /> // not working
<input type='reset' value='Clear Ticket' name='reset' onclick="return resetForm(this.form);cleartext();"> // works well
Please check it.
<html>
<head>
<script language="javascript">
function dpdown(){
var a="&name="+document.getElementById('name').value; //textbox
var b="&job_id="+document.getElementById('job_id').value;//textbox
var c="&major"+document.getElementById('major').value;//textbox
var d="&native="+document.getElementById('native').value;//textbox
var e="&age="+document.getElementById('age').value;//textbox
var f="&details="+encodeURIComponent(document.getElementById('details').value);//textarea
var i, counter = 0;
var ddl = document.getElementById("jobs");//dropdown
var selectedValue = ddl.options[ddl.selectedIndex].value;
for(var i=0; i < ddl.length; i++)
{
if(ddl.options[i].selected) // to check if the person has chosen a suitable degree
if (selectedValue == "selectdegree")
{
alert("Please select your correct degree");
}
else
{
++counter;
value=ddl.options[i].value;
window.open('https://'+value+a+b+c+d+e+f,'_blank'); // when the submit button is clicked, all the above fields should get appended to a preset link which has been hardcoded for each degree.
}
}
}
function cleartext()
{
document.form.details.value='';
}
</script>
</head>
<body>
<form>
<input type="text" id="name"/>
<input type="text" id="job_id"/>
<input type="text" id="major"/>
<input type="text" id="native"/>
<input type="text" id="age"/>
<input type="textarea" id="details"/>
<select id="jobs" >
<option value="www.google.com">google</option>
<option value="www.yahoo.com">yahoo</option>
<option value="www.stackoverflow.com">stackoverflow</option>
</select>
<input type="button" value=" Create form" onclick="dpdown();"/>
<input type='reset' value='Clear Ticket' name='reset' onclick="return resetForm(this.form);cleartext();">
</form>
</body>
</html>

Populating a tag input based on other inputs in same form

I have a form with a bunch of inputs. Sometimes the form will have 1 input and sometimes up to 10 inputs. When someone fills out each input I want a tag field at the bottom to be populated also. Right now I have it working but only with a set number of inputs. (3 at the moment).
Im trying to figure out how to make it work regardless of how many inputs there are on the page.
HTML
Input1 <input id="input1" name="input1" type="text" value="" />
<br/>
Input2 <input id="input2" name="input2" type="text" value="" />
<br/>
Input3 <input id="input3" name="input3" type="text" value="" />
<br/>
<p>List of inputed text</p>
<span id="allInputs"></span>
Jquery
$("#input1,#input2,#input3").change(function () {
var inputArray = [$("#input1").val(), $("#input2").val(), $("#input3").val()];
$("#allInputs").text(inputArray.join(' '));
});
A nice to have also would be putting them into another input instead of a span and adding a comma after each one except for the last one.
I know Im probably missing something very simple here.
In your example you are only allowing for 3 inputs as you have 3 input boxes, when any of those input boxes change your tags are then being transferred to the span.
Now it sounds like you wish to allow for multiple entries regardless of how many inputs. You could try something simple such as the below fiddle.
http://jsfiddle.net/K2g4z/
Html:
<div>
<strong>Enter your tag and click add</strong>
<br/>
<input type="text" id="tagEntry" />
<button id="tagAdd">Add</button>
</div>
<div>
<strong>Entered Tags</strong>
<br/>
<input type="text" id="tagsEntered" />
</div>
Javascript:
var tags = [];
$(function() {
$('#tagAdd').click(function(){
//get the tag value and trim the spaces
var tVal = $('#tagEntry').val().trim();
if(tVal == '')
return;
//reset the entry box
$('#tagEntry').val('');
//verify tag not already saved
for(var i=0;i<tags.length;i++)
if(tags[i] == tVal)
return;
//add the tag to the array
tags.push(tVal);
//set the tags entry box
$('#tagsEntered').val(tags.join(', '));
});
});
UPDATE:
The JSFiddle link http://jsfiddle.net/K2g4z/1/ now supports using multiple inputs of as many as you need. To achieve this instead of selecting on element ID we bind to a class name. Given the following Html.
<div>
<strong>Enter your tag and click add</strong>
<br/>
<strong>Tag 1</strong>
<input type="text" id="tagEntry" class="tagEntry" />
<br/>
<strong>Tag 2</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 3</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 4</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 5</strong>
<input type="text" class="tagEntry" />
</div>
<div>
<strong>Entered Tags</strong>
<br/>
<input type="text" id="tagsEntered" />
</div>
All the tag input boxes have a class of tagEntry now this class will become our selector. With the following JS we can bind the blur event to every tag that has a class of tagEntry. This will now update the tags box every time any of the inputs changed.
var tags = [];
$(function() {
$('.tagEntry').blur(function(){
//get the tag value and trim the spaces
var tVal = $(this).val().trim();
if(tVal == '')
return;
//reset the entry box
$(this).val('');
//verify tag not already saved
for(var i=0;i<tags.length;i++)
if(tags[i] == tVal)
return;
//add the tag to the array
tags.push(tVal);
//set the tags entry box
$('#tagsEntered').val(tags.join(', '));
});
});
As you can see our handler binds to all the inputs, as any of the inputs receives the blur event the method of extracting the tags is executed.
$("#input1,#input2,#input3").change(function () {
var inputArray = [$("#input1").val(), $("#input2").val(), $("#input3").val()];
$("#masterinput").val(inputArray.join(' '));
});
You probably want to narrow the selector so it isn't selecting all text inputs on the page.
var inputs$ = $("input:text").change(function () {
var inputArray = [];
$.each(inputs$, function(i, v) {
inputArray.push($(v).val());
}
$("#allInputs").text(inputArray.join(' '));
});
Here you go:
var str = "";
$("input[type=text]").change(function () {
$("input[type=text]").each(function(){
str += $(this).val()+",";
};
});
$("#allInputs").html(str);

Categories

Resources