JS class not applying on datapicker - javascript

Good morning,
I've got some javascript to check if inputs are empty before printing and if so, cancel the print.
I have added jquery datepicker to one of the fields as a class and now it only applies one class or the other. (I have tried the datepicker as an ID instead) but doesn't work.
Javascript:
function checkForm(thisForm) {
var len = thisForm.elements.length ;
var cnt = 0 ;
for ( var i=0; i < len; i++) {
var elem = thisForm.elements[i] ;
if (elem.className == "formFieldRequired") {
if ((elem.value == "" || elem.value == -1)) {
alert("WARNING:\n You must supply information for the " + elem.name + " field");
elem.focus();
return false;
}
}
}
window.print();return true;
}
Input:
<input name="Effective Date" type="text" style="width:12%;" class="formFieldRequired datepicker" placeholder="DD/MM/YYYY" onkeyup="javascript:return mask(this.value,this,'2,5','/');" maxlength="10">
Any ideas on why this is happening and any fixes? - I may be missing something completely obvious!

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/jquery.datetimepicker.js"></script>
<form id="myform">
<input name="Effective Date" type="text" style="width:12%;" class="formFieldRequired datepicker" placeholder="DD/MM/YYYY" onkeyup="javascript:return mask(this.value,this,'2,5','/');" maxlength="10">
</form>
<script>
function checkForm(thisForm) {
var len = thisForm.elements.length;
var cnt = 0 ;
for ( var i=0; i < len; i++) {
var elem = thisForm.elements[i] ;
console.log(elem.className)
if (elem.className.indexOf("formFieldRequired") != -1) {
if ((elem.value == "" || elem.value == -1)) {
alert("WARNING:\n You must supply information for the " + elem.name + " field");
elem.focus();
return false;
}
}
}
window.print();return true;
}
checkForm(document.getElementById("myform"));
</script>

Related

Can I select a multi-dimensional HTML array in JavaScript as a multi-dimensional array?

If I have the following HTML on a page:
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
I would like to select the items using JavaScript (or JQuery) in such a way that I can loop over the items using the outer array.
Currently I have the following JQuery/JavaScript to handle the items:
var items = ($('[name*="item["]'));
var i = 0;
while (i < items.length) {
if (items[i++].value === '') {
// No ID set.
}
else if (items[i++].value === '') {
// No title set.
}
else if (items[i++].value === '') {
// No description set.
}
}
Is there a way to select the elements so that I can loop over them using notation more like the following (Where items.length is 3)?
for (var i = 0; i < items.length; i++) {
if (items[i][0].value === '') {
// No ID set.
}
else if (items[i][1].value === '') {
// No title set.
}
else if (items[i][2].value === '') {
// No description set.
}
}
Or even more like this?
for (var i = 0; i < items.length; i++) {
if (items[i].id.value === '') {
// No ID set.
}
else if (items[i].title.value === '') {
// No title set.
}
else if (items[i].description.value === '') {
// No description set.
}
}
Or would this require more manipulation and processing to go from selecting from the DOM to creating the data structure to loop over?
I think this is exactly what you are looking for (which is not really related to selectors):
function serialize () {
var serialized = {};
$("[name]").each(function () {
var name = $(this).attr('name');
var value = $(this).val();
var nameBits = name.split('[');
var previousRef = serialized;
for(var i = 0, l = nameBits.length; i < l; i++) {
var nameBit = nameBits[i].replace(']', '');
if(!previousRef[nameBit]) {
previousRef[nameBit] = {};
}
if(i != nameBits.length - 1) {
previousRef = previousRef[nameBit];
} else if(i == nameBits.length - 1) {
previousRef[nameBit] = value;
}
}
});
return serialized;
}
console.log(serialize());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
See the related JSFiddle sample.
Here's a way to add a custom function into JQuery to get the data structure you're looking for.
$.fn.getMultiArray = function() {
var $items = [];
var index = 0;
$(this).each(function() {
var $this = $(this);
if ($this.attr('name').indexOf('item[' + index + ']') !== 0)
index++;
if (!$items[index])
$items[index] = {};
var key = $this.attr('name').replace('item[' + index + '][', '').replace(']', '');
$items[index][key] = $this;
});
return $items;
};
var $items = $('input[name^="item["]').getMultiArray();
This allows you to have the references in your "ideal" example.
var $items = $('input[name^="item["]').getMultiArray();
$items[0].id;
JS Fiddle: https://jsfiddle.net/apphffus/

How to check value in input using getElementsByClassName , Like this?

How to check value in input using getElementsByClassName , Like this ?
When i load page, I want to alert
HAVE VALUE 3 INPUT
NOT HAVE VALUE 2 INPUT
How can i do that ?
................................................................................................................................................
http://jsfiddle.net/3AaAx/37/
<input type="text" class="xxx" value="111"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="222"/>
<input type="text" class="xxx" value=""/>
<input type="text" class="xxx" value="333"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
// this function for use getElementsByClassName on IE 7 and 8 //
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', #class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
var xxx_var = document.getElementsByClassName('xxx');
alert(xxx_var.length);
});
</script>
Add below code after var xxx_var = document.getElementsByClassName('xxx');
var inputCount=0,nonInputCount=0;
for(var i=0;i<xxx_var.length;i++){
if(xxx_var[i].value != ""){
inputCount++;
}else{
nonInputCount++;
}
}
alert("Input Count " + inputCount + " , and non input count " +nonInputCount );
If you use jquery it will be very easier code.
Let me know if you didn't understand.
Thanks
Raviranjan

Js validate multipe input fields with same name

Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle

Validating a single radio button is not working in available javascript validation script Part-2

I am available with the solution given by #Tomalak for MY QUESTION could you pls help me out with it as its giving me an error in firebug as : frm.creatorusers is undefined
[Break On This Error] var rdo = (frm.creatorusers.length >...rm.creatorusers : frm.creatorusers;
I used the code for validating radio button as:
function valDistribution(frm) {
var mycreator = -1;
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : frm.creatorusers;
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
mycreator = 1;
//return true;
}
}
if(mycreator == -1){
alert("You must select a Creator User!");
return false;
}
}
Here is how to use the code you were given by #Tomalak but did not copy correctly
function valDistribution(frm) { // frm needs to be passed here
var myCreator=false;
// create an array if not already an array
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : [frm.creatorusers];
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
myCreator=true;
break; // no need to stay here
}
if (!myCreator){
alert("You must select a Creator User!");
return false;
}
return true; // allow submission
}
assuming the onsubmit looking EXACTLY like this:
<form onsubmit="return valDistribution(this)">
and the radio NAMED like this:
<input type="radio" name="creatorusers" ...>
You can try this script:
<html>
<script language="javascript">
function valbutton(thisform) {
myOption = -1;
alert(thisform.creatorusers.length);
if(thisform.creatorusers.length ==undefined) {
alert("not an array");
//thisform.creatorusers.checked = true;
if(thisform.creatorusers.checked) {
alert("now checked");
myOption=1;
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers.value);
}
}
else {
for (i=thisform.creatorusers.length-1; i > -1; i--) {
if (thisform.creatorusers[i].checked) {
myOption = i; i = -1;
}
}
if (myOption == -1) {
alert("You must select a radio button");
return false;
}
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers[myOption].value);
}
}
</script>
<body>
<form name="myform">
<input type="radio" value="1st value" name="creatorusers" />1st<br />
<!--<input type="radio" value="2nd value" name="creatorusers" />2nd<br />-->
<input type="button" name="submitit" onclick="valbutton(myform);return false;" value="Validate" />
<input type="reset" name="reset" value="Clear" />
</form>
</body>
</html>

Basic javascript loop/validation question

So im trying to perform a basic validation to check if a field is empty. I want to do it in a loop..
<input type="text" size="25" name="q170_Name" class="text" value="" id="q170" maxlength="100" maxsize="100" />
function validateMe() {
var dropdowns = ["q170","q172","q173","q174","q175","q176","q177"];
var totalz = (dropdowns.length);
//loop through the array
for ( var i in dropdowns ) {
if (document.getElementById(dropdowns[i]) == "") {
alert('missed one!');
}}}
I appreciate the help
if (document.getElementById(dropdowns[i]).value == "") {
alert('missed one!');
--edit
but probably there is a better way to do this:
for (var i = 0; i < document.myFormName.length; ++i) {
if( document.myFormName.elements[i].type == "text" &&
document.myFormName.elements[i].value == "") {
alert('missed one!');
}
}
I recommend you to do a simple for loop since for..in is meant to iterate over object properties, also note that you need to check the value attribute of the fields:
function validateMe() {
var dropdowns = ["q170","q172","q173","q174","q175","q176","q177"],
totalz = dropdowns.length,
i;
for (i = 0; i < totalz; i++) {
if (document.getElementById(dropdowns[i]).value == "") {
alert('Check the value of ' + dropdowns[i]);
}
}
}

Categories