Validating Mandatory Input Boxes Using Javascript only - javascript

I wanted to know what would be the best method to validate (to ensure that all 4 of the input boxes are not blank)?
<html>
<head></head>
<body>
<input type="text" id="i1">
<input type="text" id="i2">
<input type="text" id="i3">
<input type="text" id="i4">
</body>
</html>

If they are all to be inputs then you can use document.getElementsByTagName
var allinputs = document.getElementsByTagName("input");
console.log(allinputs);
for (var i = 0; i < allinputs.length; i++) {
if(allinputs[i].value.length == 0){
alert('need to have something here');
return;
}
}
here is a working fiddle

JQuery Validate is an really easy way to validate your fields. You can read more about it at their wiki:
http://docs.jquery.com/Plugins/Validation

My custom method, not cross-browser:
NodeList.prototype.every = HTMLCollection.prototype.every = Array.prototype.every;
var allChecked = document.querySelectorAll('input[type=text]').every(function(el) {
return el.value !== '';
});
if (allChecked) alert("All checked!");
The cross-browser (IE8 and above), not funny way:
var inputs = document.querySelectorAll('input[type=text]');
var allChecked = true;
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].value === '') {
allChecked = false;
}
}
if (allChecked) alert("All checked!");

HTML:
<input type="button" value="submit" onclick="submitForm()">
JavaScript :
function submitForm()
{
if(validate())
{
alert('No blank found!!');
}
else
{ alert('blank found!!'); }
}
function validate()
{
var i1 =document.getElementById('i1').value;
var i2 =document.getElementById('i2').value;
var i3 =document.getElementById('i3').value;
var i4 =document.getElementById('i4').value;
var result = false;
if( i1 && i2 && i3 && i4) {
result = true;
}
return result;
}

Related

Duplicate check in javascript before inserting a new record

I have a javascript which appends a string like 222222222222222 to another field (which will either be blank or already have numbers like 222222222222222 33333333333333) with a click of a button. Actually it's 15 digit IMEI of the phone. User has the option of submitting a single IMEI or bulk IMEI. When more then one IMEI is added to the bulk field by pressing the button from myVar1, the new IMEI gets inserted below the previous IMEI in the bulk field(myVar2).
Currently, I am using the below script to do this and it's working perfectly fine. The problem is that it doesn't check for duplicates before appending.
function append_myVar1_to_myVar2(){
var myVar1 = document.getElementById('myVar1_value').value;
var myVar2 = document.getElementById('myVar2_value').value;
if(document.getElementById('myVar2_value').value == ''){
document.getElementById('myVar2_value').value = myVar1;
}else{
document.getElementById('myVar2_value').value = document.getElementById('myVar2_value').value + "\r\n" + myVar1;
}
}
I have modified the script now as below (updated to include the first response, thanks to Brian) to check for duplicates, but it's not working. Request experts to have a look into it.
function append_myVar1_to_myVar2(){
var myVar1 = document.getElementById('myVar1_value').value;
var myVar2 = document.getElementById('myVar2_value').value;
if(document.getElementById('myVar2_value').value == ''){
document.getElementById('myVar2_value').value = myVar1;
}else{
var flag = 0;
var wordsarr = myVar2.split("\r\n");
for(var i = 0; i < wordsarr.length; i++)
{
if(wordsarr[i].value == myVar1)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
else{
document.getElementById('myVar2_value').value = document.getElementById('myVar2_value').value + "\r\n" + myVar1;
}
}}
Here is the html of the page:
<html>
<body>
<input id="myVar1_value" type="text" maxlength="15" name="myVar1_value">
<input id="IMEI_ADD" class="button_gray" type="button" onclick="append_myVar1_to_myVar2()" value="Add this IMEI to bulk entry" name="IMEI_ADD">
<p id="imei_bulk_field" class="form-row notes">
<textarea id="myVar2_value" class="input-text" rows="2" cols="5" placeholder="If you have more than one IMEI, insert them here by pressing the button above." name="myVar2_value"></textarea>
</p>
</body>
</html>
for(var i = 0; i < (myVar2.split("\r\n")).length; i++)
{
//here is wrong
if(myVar2[i].value == myVar1)
{
flag = 1;
}
You should change to
var wordsarr = myVar2.split("\n");
for(var i = 0; i < worsarr.length; i++)
{
if(wordsarr[i] == myVar1)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
Store splitted chunks ,and iterate over them:
var chunkArray = myVar2.split("\r\n");
for(var i = 0; i !== chunkArray.length; i++){
if(chunkArray[i] == myVar1){
flag = 1;
break;
}
}
var myVar2 = document.getElementById('myVar2_value').value;
Later...
if(myVar2[i].value == myVar1)
It looks like you are adding .value when you don't need to. Try:
if(myVar2[i] == myVar1)
This could be of assistance
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
you could change the if with:
haystack[i].value == needle

I am not able to set the Global variable in the following code. What am i doing wrong?

Here is the issue: I am trying check and uncheck the check boxes by a group.
So if you select G1 and G2, it throws a message that you cant mix groups. If you uncheck all of them, i am trying to clear the existing grouping and that is where the code seems to fail.
Any thoughts? (also,i might be having a wrong idea about that global var at the beginning. so please suggest)
<HTML>
<script language="javascript">
var prodSel="";
function VerifyGroup(a,b)
{
ClearAllSelectionsA(); // check if this is the last unselect and clear the prodSel variable
if (prodSel == "")
{
prodSel = a;
}else
{
if (prodSel != a)
{
alert ( "Please ensure that the groups are same for the items you select");
//alert(b);
document.getElementById(b).checked = false;
}
}
}
function ClearAllSelections()
{
var inputs = document.getElementsByTagName("input");
var cbs = [];
for (var i = 0; i < inputs.length; i++)
{
if (inputs[i].type == "checkbox")
{
inputs[i].checked = false;
}
}
prodSel=""; // Clear the variable; allow new selections
}
/*loop through and if all of them are unchecke,d clear the variable*/
function ClearAllSelectionsA()
{
var clre = true;
var inputs = document.getElementsByTagName("input");
var cbs = [];
for (var i = 0; i < inputs.length; i++)
{
if (inputs[i].type == "checkbox")
{
if (inputs[i].checked){clre= false;}
}
}
if (clre){
prodSel=""; // Clear the variable; allow new selections
alert(window.prodSel);
}
}
</script>
<body>
G1<input type="checkbox" value="zxc" id="12" onclick="javascript:VerifyGroup('g1',12);"><BR>
G1<input type="checkbox" value="zxcw" id="123" onclick="javascript:VerifyGroup('g1',123);"><BR>
G1<input type="checkbox" value="zxcdw" id="124" onclick="javascript:VerifyGroup('g1',124);"><BR>
G2<input type="checkbox" value="zxcf" id="125" onclick="javascript:VerifyGroup('g2',125);"><BR>
G2<input type="checkbox" value="zxcfg" id="126" onclick="javascript:VerifyGroup('g2',126);"><BR>
clear group
</body>
</html>
When you call ClearAllSelectionsA, if all the checkboxes are unchecked, then prodSel gets cleared. Then back in VerifyGroup, prodSel is immediately being reassigned to a. My recommendation would be to return true or false from ClearAllSelectionsA and act based upon that value.
<script language="javascript">
var prodSel="";
function VerifyGroup(a,b)
{
var cleared = ClearAllSelectionsA(); // check if this is the last unselect and clear the prodSel variable
if (prodSel == "" && !cleared) //only reset prodSel if there is a checkbox checked
{
prodSel = a;
}else
{
if (prodSel != a)
{
alert ( "Please ensure that the groups are same for the items you select");
//alert(b);
document.getElementById(b).checked = false;
}
}
}
function ClearAllSelections()
{
var inputs = document.getElementsByTagName("input");
var cbs = [];
for (var i = 0; i < inputs.length; i++)
{
if (inputs[i].type == "checkbox")
{
inputs[i].checked = false;
}
}
prodSel=""; // Clear the variable; allow new selections
}
/*loop through and if all of them are unchecke,d clear the variable*/
function ClearAllSelectionsA()
{
var clre = true;
var inputs = document.getElementsByTagName("input");
var cbs = [];
for (var i = 0; i < inputs.length; i++)
{
if (inputs[i].type == "checkbox")
{
if (inputs[i].checked){clre= false;}
}
}
if (clre){
prodSel=""; // Clear the variable; allow new selections
alert(window.prodSel);
}
return clre;
}
</script>

Validation of radio buttons with Javascript

I've combed a ton of the pages on here, and still am incapable to get my explicit validator to work. Basically, when the submit button is clicked, I want the script to verify a radio is checked, if one is checked to do nothing. If one isn't checked I want it to post an alert message.
roughly my html looks like:
<form id="myForm" onsubmit = "check()">
<input type = "radio" name = "c" id = "1" value = "1" />
<input type = "radio" name = "c" id = "2" value = "2" />
<input type = "radio" name = "c" id = "3" value = "3" />
<input type = "submit" value = "Submit" />
my JS page looks like:
function check() {
var r = document.getElementsByName("c")
var c = 0
for(var i=0; i < r.length; i++){
if(c[i].checked) {
c = i; }
}
alert("please select radio");
}
try this one
function check() {
var r = document.getElementsByName("c")
var c = -1
for(var i=0; i < r.length; i++){
if(r[i].checked) {
c = i;
}
}
if (c == -1) alert("please select radio");
}
this
c[i].check
should be
c[i].checked
and you're not actually doing anything with the result, you're just always alerting.
<html>
<head>
<script language="javascript">
function check() {
chosen = ""
len = document.myform.chk.length
for (i = 0; i <len; i++) {
if (document.myform.chk[i].checked) {
chosen = document.myform.chk[i].value
}
}
if (chosen == "") {
alert("No Option selected");
return false;
}
else {
alert("option selected");
return true;
}
}
</script>
</head>
<body>
<form name="myform" onsubmit = "return check();">
<input type = "radio" name = "chk" id = "1" value = "1" >
<input type = "radio" name = "chk" id = "2" value = "2" >
<input type = "radio" name = "chk" id = "3" value = "3" >
<input type="submit" value="submit">
</form>
</body>
</html>
Check for this validation hope its may also help you . Also check it in jsfiddle
function ShowMsg() {
if (fnSpeciality() == false)
{
document.getElementById("myform").focus();
return false;
}
function fnSpeciality()
{
return fnRblfnSpeciality();
}
function fnSpeciality() {
return fnRblfnSpeciality();
}
function fnRblfnSpeciality() {
var list = document.getElementById('myform'); //Client ID of the radiolist
var inputs = list.getElementsByTagName("input");
var isItemChecked = false;
for (var i = 0; i < inputs.length; i++) {
var listItem = inputs[i];
if (listItem.checked) {
//alert(listItem.value);
isItemChecked = true;
break;
}
}
if (isItemChecked == false) {
if (isItemChecked =="") {
alert('Please select a speciality.');
return false;
}
// else return true;
}
return true;
}
CreditCard
DebitCard
By Cash
</td>
</tr>
Am using radio button list ..pls share if have java script validation for this radio button

Javascript for showing a div using the div's class name

I have a div in my page like that,
<div class="errormsg" style="display: none;">Username is empty</div>
i am having an input field like this,
<input type=textbox id="userid" />
Now i need a javascript for showing the error message div if input field was empty. I need to use the div class rather than id. Please help.
P.S : I don't want Jquery as my page has some restriction to use library files.
Try this, assuming only one errormsg div -
Update
I've added a fiddle here. Plus, there was a typo - corrected
<div class="errormsg" style="display: none;">Username is empty</div>
<input type=textbox id="userid" onchange="validate()" />
function validate(){
var userId = document.getElementById('userId'),
errorMsg = document.getElementsByClassName('errormsg').item();
if (userId.value === ''){
errorMsg.style.display = 'block'
} else {
errorMsg.style.display = 'none';
}
}
<div class="errormsg">Username is empty</div>
<input type='textbox' id="userid" onkeyup="javascript:call(this);" />
function getElementsByClassName(className) {
// For IE
if (document.all) {
var allElements = document.all;
} else {
var allElements = document.getElementsByTagName("*");
}
var foundElements = [];
for (var i = 0, ii = allElements.length; i < ii; i++) {
if (allElements[i].className == className) {
foundElements[foundElements.length] = allElements[i];
}
}
return foundElements;
}
function call(control)
{
var userid=document.getElementById('userid');
var errorMsg = getElementsByClassName('errormsg')[0];
if(userid.value == '')
{
errorMsg.style.display = "block";
}
else
{
errorMsg.style.display = "none";
}
}
Removed the JQuery and added the Javascript code as below:
<div class="errormsg">Username is empty</div>
<input type='textbox' id="userid" onkeyup="javascript:call(this);" />
function getElementsByClassName(className) {
// For IE
if (document.all) {
var allElements = document.all;
} else {
var allElements = document.getElementsByTagName("*");
}
var foundElements = [];
for (var i = 0, ii = allElements.length; i < ii; i++) {
if (allElements[i].className == className) {
foundElements[foundElements.length] = allElements[i];
}
}
return foundElements;
}
function call(control)
{
var userid=document.getElementById('userid');
var errorMsg = getElementsByClassName('errormsg')[0];
if(userid.value == '')
{
errorMsg.style.display = "block";
}
else
{
errorMsg.style.display = "none";
}
}

checking for duplicate file while uploading multiple file in Javascript

I used the below code to upload multiple files. Its working absolutely fine but as i need to check that the file which i am uploading is duplicate or not, i am facing one problem in that. I created one function called checkDuplicate for that and calling it inside the function. But the problem is that the for loop is looping double the size of the array. I don't know why it is so. Please kindly help me if anyone has any idea.
Here is the Javascript
<script type="text/javascript">
function MultiSelector(list_target, max) {
this.list_target = list_target;
this.count = 0;
this.id = 0;
if (max) {
this.max = max;
} else {
this.max = -1;
};
this.addElement = function(element) {
if (element.tagName == 'INPUT' && element.type == 'file') {
element.name = 'file_' + this.id++;
element.multi_selector = this;
element.onchange = function() {
var new_element = document.createElement('input');
new_element.type = 'file';
this.parentNode.insertBefore(new_element, this);
this.multi_selector.addElement(new_element);
this.multi_selector.addListRow(this);
this.style.position = 'absolute';
this.style.left = '-1000px';
};
if (this.max != -1 && this.count >= this.max) {
element.disabled = true;
}
;
this.count++;
this.current_element = element;
}
else {
alert('Error: not a file input element');
}
;
};
this.addListRow = function(element) {
var new_row = document.createElement('div');
var new_row_button = document.createElement('img');
new_row_button.setAttribute("src","<%=request.getContextPath()%>/images/deletei.gif");
new_row_button.onclick = function() {
this.parentNode.element.parentNode.removeChild(this.parentNode.element);
this.parentNode.parentNode.removeChild(this.parentNode);
this.parentNode.element.multi_selector.count--;
this.parentNode.element.multi_selector.current_element.disabled = false;
return false;
};
if(checkDuplicate(element)) {
new_row.element = element;
new_row.innerHTML = element.value + " ";
new_row.appendChild(new_row_button);
this.list_target.appendChild(new_row);
}
};
};
function checkDuplicate(element) {
var arr = new Array();
var i = 0,dup=0;
//alert(new_row.element = element.value);
if(dup==0) {
arr[i++] = element.value;
dup=1;
}
alert("Length ==> "+ arr.length);
for ( var j = 0; j < arr.length; j++) {
alert("Name ==> " + arr[j]);
if(arr[j] == element.value && j>=1) {
alert("Duplicate");
} else {
alert("Not Duplicate");
arr[i++] = element.value;
}
}
}
</script>
Here is the HTML
<body>
<!-- This is the form -->
<form enctype="multipart/form-data" action=""method="post">
<input id="my_file_element" type="file" name="file_1">
<input type="submit">
<br/>
<br/>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
</form>
<script>
var multi_selector = new MultiSelector(document
.getElementById('files_list'), 15);
multi_selector.addElement(document.getElementById('my_file_element'));
</script>
</body>
</html>
because you have the arr[i++] = element.value; in the last line, and j < arr.length in the for, so every time the array.lenght gets bigger and bigger.
change the for line to these two lines:
var len = arr.length;
for ( var j = 0; j < len; j++) {

Categories