I have 4 inputs on my page, and on a button onClick, i want to check, that all the inputs are filled with text.
<input type="text" value="" id="input1">
<input type="text" value="" id="input2">
<input type="text" value="" id="input3">
<input type="text" value="" id="input4">
What i want : Store all the required inputs ID in an array, and on click, check, that is there any input, that is empty.
How can i do this at the simplest way?
Use required tag instead as given below
<input type="text" value="" id="input1" required>
you can also try adding REGEX for more strict checking
// using Plain JavaScript
var input1= document.getElementById('input1').value;
if(input1 == "" ){
alert("Input 1 is Empty");
return false;
}
var input2 = document.getElementById('input2').value;
if(input12 == "" ){
alert("Input 2 is Empty");
return false;
}
var input3 = document.getElementById('input3').value;
if(input3 == "" ){
alert("Input 3 is Empty");
return false;
}
var input4 = document.getElementById('input4').value;
if(input4 == "" ){
alert("Input 4 is Empty");
return false;
}
just incase the required attribute fails.. you can do this..
add a validate function to the blur event, that is when the user leaves the field..
<input type="text" onblur="validate(this)" value="" id="input1">
<input type="text" onblur="validate(this)" value="" id="input2">
<input type="text" onblur="validate(this)" value="" id="input3">
<input type="text" onblur="validate(this)" value="" id="input4">
<button> ... </button>
and using jquery you can do this..
function validate(obj){
if($(obj).val() == ''){
alert('this Field cannot be empty');
$(obj).focus(); //send focus back to the object...
}
}
<input type="text" value="" id="input1">
<input type="text" value="" id="input2">
<input type="text" value="" id="input3">
<input type="text" value="" id="input4">
jQuery(function($){
var arr = [];
// number of input elements
var count = $("input").length;
// store list of input ids
$("buttonName").on('click', function(event) {
$("input").each(function(i){
var currId = $(this).attr('id');
arr.push(currId);
if ($(this).val()=="") {
alert(currId+": has no input");
}
});
});
});
Related
I have 3 inputs on a div (repeated several times), I want to validate that if the user enters a value on coreid it's necessary to insert the amount, and to have a value on fullname(it is given with the id from sql automatically, if it doesn'thave a value..the id is incorrect) this on the same row, as they have all the same class and names, it makes the validation but it doesn't matter if they're at the same row or not.. it makes the submit even if I insert a coreid at the 1st row, the fullname on the 3rd row and the amount at the 2nd row.
Any help, please?
$("#myform").submit(function() {
var currentForm = this;
var allinputs = 0;
var coreid = 0;
var fullname = 0;
var amount = 0;
//if all inputs are empty
$(this).find('input.cardField').each(function() {
if ($(this).val() != "") allinputs += 1;
});
if (allinputs) {
//checks if coreid has a value
$(this).find('input.cardField.id').each(function() {
if ($(this).val() != "") coreid += 1;
});
//checks if fullname has a value
$(this).find('input.cardField.name').each(function() {
if ($(this).val() != "") fullname += 1;
});
//checks if amount has a value
$(this).find('input.cardField.cardAmount').each(function() {
if ($(this).val() != "") amount += 1;
});
//if user inserts an id it must have a value on name
if (coreid) {
var empty = $(this).parent().find("input.cardField.name").filter(function() {
if ($(this).val() != "") fullname += 1;
});
if (fullname) {
//the name is given when the user inserts the id
alert("it has a name, the id is correct");
} else {
bootbox.alert('Please insert a valid id');
return false;
}
//the user inserts an amount but not an id
} else {
bootbox.alert('Please insert an employee id');
return false;
}
} else {
//the user can continue if he confirms
bootbox.confirm("Empty fields, Do you want to continue?",
function(result) {
if (result) {
currentForm.submit();
}
});
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
If a user inserts one of the three inputs it is mandatory that he inserts the 3 values...
No matter if the other rows (other divs) are empty.
You should loop over the DIVs. In each DIV, get the value of the id field. If it's not empty, check the other two fields.
$("#myform").submit(function() {
var currentForm = this;
var allinputs = 0;
var missinginputs = false;
//if all inputs are empty
$(this).find('input.cardField').each(function() {
if ($(this).val() != "") allinputs += 1;
});
if (allinputs) {
//checks if coreid has a value
$(this).find('div').each(function(index) {
var coreid = $(this).find("input.cardField.id").val();
var fullname = $(this).find("input.cardField.name").val();
var amount = $(this).find("input.cardField.amount").val();
if (coreid == "" && fullname == "" && amount == "") {
// all inputs in row are empty, skip it
return;
} else if (coreid == "" || fullname == "" || amount == "") {
bootbox.alert(`Enter all fields in row #${index}`);
missinginputs = true;
}
});
return !missinginputs;
} else {
//the user can continue if he confirms
bootbox.confirm("Empty fields, Do you want to continue?",
function(result) {
if (result) {
currentForm.submit();
}
});
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
</form>
So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.
This would look like
The first criteria_name is default and the others are appendend.
<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">
I am trying to check each one of those if there is no duplicated else proceed.
var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;
for(var ab = 2; ab<=acappended; ab++){
var crit_arr;
if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;
}else{
input_check = $('input.criteria_each_name'+ab);
input_check.each(function(){
crit_arr = $.trim($(this).val());
});
critname_arr.push(crit_arr);
}
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;
}
count_to++;
}
console.log(critname_arr);
Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:
jsFiddle: https://jsfiddle.net/o52gjj0u/
<script>
$(document).ready(function(){
$('.ter').click(function(e) {
var stored = [];
var inputs = $('.criteria_name');
$.each(inputs,function(k,v){
var getVal = $(v).val();
if(stored.indexOf(getVal) != -1)
$(v).fadeOut();
else
stored.push($(v).val());
});
});
});
</script>
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />
i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.
I'm been trying to validate my fields by using 'getElementById()' with '.value'. However, it seems like either getElementById.value is not working or some codes has overlap the function.
Updated Javascript function:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("Don leave blank!")
return false;
}
if (isNaN(Tel)) //check only numbers. Same code for FaxNo.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("invalid");
return false
}
return true; //doesn't go to next.php
}
My Form:
<Form action ="next.php" method="post">
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
<input type="submit" name="submit" onclick="return validate();"/>
</Form>
I have already defined my onclick function to my Javascript and tried to add return false too. But the alert still cant appear. Kindly advise.
Your markup is invalid:
<input name="Name" type="text" id="Name" " value=""/>
^-----------should be removed
so correction would be removing all extra " characters:
<input name="Name" type="text" id="Name" value=""/>
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
For preventing submition,when input is invalid, you can try something like a:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
alert("Correct")
else {
alert("Don leave blank!")
return false;
}
if (isNumeric(Tel)) //check only numbers. Same code for FaxNo.
alert("Correct")
else {
alert("invalid");
return false;
}
}
//Borrowed from jQuery lib
function isNumeric( obj ){
return !isNaN( parseFloat(obj) ) && isFinite( obj )
}
<input type="submit" name="submit" onclick="return validate()"/>
Try this,
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") {}
else {alert("Don leave blank!"); return false;}
if (isNaN(Tel)){ alert("invalid"); return false;}
else { }
return true;
}
Your HTML submit button code should be
<input type="submit" name="submit" onclick="return validate()"/>
Use return false to prevent submitting form in case of any validation errors.
<pre>
<script>
// here i want to check form validation
//if i use for loop txtbox2 is not exist in my form so i am getting Js error
//Don't write individual validation
//check element is exist or not if exist check for validation
//I need know how to check an element is exist or not
</script>
<form
<input type="text" id="txtbox1" name="txtbox1" />*
<input type="text" id="txtbox3" name="txtbox3" />*
<input type="text" id="txtbox4" name="txtbox4" />*
<input type="text" id="txtbox5" name="txtbox5" />*
<input type="text" id="txtbox15" name="txtbox15" />*
<input type="text" id="txtbox28" name="txtbox28" />*
</pre>
Apply a class to them:
<input type="text" id="txtbox1" name="txtbox1" class="txt" />
<input type="text" id="txtbox3" name="txtbox3" class="txt" />
<input type="text" id="txtbox4" name="txtbox4" class="txt" />
<input type="text" id="txtbox5" name="txtbox5" class="txt" />
<input type="text" id="txtbox15" name="txtbox15" class="txt" />
<input type="text" id="txtbox28" name="txtbox28" class="txt" />
and go about like this:
function validate(){
var elms = document.getElementsByTagName('input');
for (var i = 0; i < elms.length; i++){
if (elms[i].className === 'txt'){
if (elms[i].value === ''){
alert('Make sure to fill in all required fields');
// now focus it
elms[i].focus();
return false;
}
}
}
return true;
}
And then call the above function like this:
<form ............ onsubmit="return validate();">
Post your code.
Easiest way to validate is by using jquery validate plugin.(Why write your own code when somebody else has done the same?).
An example
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#feedbackform").validate();
});
</script>
<body>
<form id = "feedbackform" method = "POST" action = "">
<h3><span>Contact Us</span></h3>
<fieldset>
<legend>Contact form</legend>
<label for="id_name">Name *</label>
<input id="id_name" class="required" type="text" name="name" />
<label for="id_email">Email</label>
<input id="id_email" type="email" name="email" class="email"/>
<label for="id_comments">Message *</label>
<textarea id="id_comments" class="required" name="comments"></textarea>
<button type="submit">Send</button>
</fieldset>
</form>
The elements that you want to validate add class="required". I hope the example provided is self-explainatory
You can get a reference to the element and check if the reference is null or not:
for (var i=1; i<=100; i++) {
var elem = document.getElementById('txtbox' + i);
if (elem != null) {
...
}
}
Another approach is to look at the elements in the form, but then you need a way to access the form of course:
var elems = document.getElementById('IdOfTheForm').elements;
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
if (elem.tagName == 'INPUT' && elem.type == 'text' && elem.id.length > 6 && elemt.id.substr(0,6) == 'txtbox') {
...
}
}