check atleast 2 of 5 input fields were not empty - javascript

How to check of two out of five inputted fields and get the value? I'm using jQuery, and I'm not sure what is the proper positioning of this code. Maybe you guys can help me.
Here is my code:
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
}
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
The result that I get is that it only trigger the res variable if the execution reach into 2 above.
I want to submit the form only when there are at least two fields were inputted.
Thanks!

You're checking if any value other than the first two has value
The correct way to implement your check would be:
$(document).ready(function(){
$("#btnSubmit").on('click', function(){
var val = $(".validate");
var res = "";
var reqCount=0
for(var i = 0; i < val.length; i++){
if(val[i].value){
reqCount++;
}
if(reqCount >= 2){
res = "Code Execution here";
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
I don't know why there's a C# tag on this question, if you mean to do this on the server side, that'd be a whole different question

Change you logic to count number of filed having value in for loop
than base don count change alert message
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = ""; let count=0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
count++;
}
}
if (count >= 2) {
res = "Code Execution here";
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>

If all you want to do is make sure you have atleast 2 feilds filled before the user submits the form , you can do the below:
function isEmpty(validateElem) {
return (validateElem === "" || typeof validateElem === 'undefined') ? true : false;
}
$(function(){
var InputValidateCount = 0;
$('form').submit(function(){
$('input').each(function(e , i){
if(!isEmpty($(this).val())) {
InputValidateCount++;
}
});
if(InputValidateCount < 2) {
return false; // Stop from from submitting;
}
});
});

You should count the validated fields before submission.
Upvote if this answered you. :P
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var minimumNonEmptyFields = 2;
var validatedNonEmptyFieldsCount = 0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
validatedNonEmptyFieldsCount++;
}
}
if(validatedNonEmptyFieldsCount >= minimumNonEmptyFields) {
alert( validatedNonEmptyFieldsCount + " fields are non-empty");
} else {
alert("Please fill " + (minimumNonEmptyFields - validatedNonEmptyFieldsCount) + " more fields");
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>
Validate any 2 input
</title>
</head>
<body>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<input type="text" class="validate" id="req6" name="req6">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
<script></script>
</body>
</html>

if atleast two input is not empty then return true else return false .
if return's true it submit's the form else it will not.
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
console.log("success");
return true;
}
}
}
console.log("fail");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>

Related

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

Checkbox checked input required , if checkbox is unchecked input not required

This is my html
<input type="checkbox" name="checked" id="check" onclick="unlocking()">
<label for="checkbox">If checked</label>
<fieldset id="unlock" style="display:none;">
<input type="text" name="Name" value="Name" id="inside" required>
<input type="text" name="email" value="email" id="inside" required>
<input type="text" name="Adress" value="Adress" id="inside" required>
</fieldset>
And this is my js with the function to hide and show the fieldset.
function unlocking() {
var checkBox = document.getElementById("check")
var form = document.getElementById("unlock")
if(checkBox.checked) {
form.style.display="block";
}else {
form.style.display="none";
}
}
If the fieldset is show i want the input to be required and if not just to skip it.
You could loop through each child and set its required attribute to either true or false depending on if the checkbox is checked or not, like so:
for (child of form.children) {
child.required = true;
}
Please check the snippet below:
function unlocking() {
var checkBox = document.getElementById("check");
var form = document.getElementById("unlock");
if (checkBox.checked) {
form.style.display = "block";
for (child of form.children) {
child.required = true;
console.log(child);
}
} else {
form.style.display = "none";
for (child of form.children) {
child.required = false;
console.log(child);
}
}
}
<input type="checkbox" name="checked" id="check" onclick="unlocking()" />
<label for="checkbox">If checked</label>
<fieldset id="unlock" style="display: none;">
<input type="text" name="Name" value="Name" id="inside" />
<input type="text" name="email" value="email" id="inside" />
<input type="text" name="Adress" value="Adress" id="inside" />
</fieldset>
//element.setAttribute("required", ""); turns required on
//element.removeAttribute("required"); turns required off
function unlocking() {
var checkBox = document.getElementById("check")
var form = document.getElementById("unlock")
var inputs = document.querySelectorAll('input[type=text]')
if(checkBox.checked) {
form.style.display="block";
for(var i = 0; i < inputs.length; i++)
inputs[i].setAttribute("required", "");
}else {
form.style.display="none";
for(var i = 0; i < inputs.length; i++)
inputs[i].removeAttribute("required");
}
}

jQuery - What is the good way to implement continouns ranking

Suppose I have 4 input fields now:
<table>
<tr><th></th><th>Factor 1</th></tr>
<tr><td>Company A</td><td><input type="text" name="text1" id="text1"></td></tr>
<tr><td>Company B</td><td><input type="text" name="text2" id="text2"></td></tr>
<tr><td>Company C</td><td><input type="text" name="text3" id="text3"></td></tr>
<tr><td>Company D</td><td><input type="text" name="text4" id="text4"></td></tr>
</table>
The inputs are integer from 1 to 4 uniquely in each input field. It is like a ranking for which Company is the best for this Factor, and which is the second and so on.
For example:
When we input 1, 3, we alert 2 is missing in the ranking.
When we input 1, 2, 4, then we alert 3 is missing.
Inputs are not required, but when there are inputs, the sequence must from 1 to 4.
Here is the code I tried.
function checkMissingRank(object){
object.change(function() {
var max = 0;
var actSum = 0;
var rows = object.length;
for(var i=1 ; i<=rows ; i++){
if($('#text'+i+'').val() != ""){
var actVal = parseInt($('#text'+i+'').val());
//alert("actVal: "+actVal);
actSum = actSum + actVal;
if(actVal>max){
max=actVal;
//alert("max: "+ max);
}
}
}
//alert("actSum: "+ actSum);
totalSum = ((1+max)*max)/2;
//alert("totalSum: "+ totalSum);
var missVal = totalSum - actSum;
//alert("missVal "+ missVal);
if(missVal != 0){
alert("Ranking "+missVal+" is missing.");
}
});
}
checkMissingRank($('input[name^="text"]'));
It is working fine when just one Value missing (1 missing from 1 ,2 ,3, 4). But when 1, 2 both missing, it return 3 is missing which is the sum of 1 and 2. Is there a better way to do this?
HTML :
<input type="text" name="text1" id="text1">
<input type="text" name="text2" id="text2">
<input type="text" name="text3" id="text3">
<input type="text" name="text4" id="text4">
<input type="button" id="btnTest">
and Jquery:
$("#btnTest").click(function() {
$('input[type=text]').each(function() {
var msg = $(this).prop("id");
if ($(this).val() == "") {
switch (msg) {
case ("text1"):
alert('miss 1');
break;
case ("text2"):
alert('miss 2');
break;
case ("text3"):
alert('miss 3');
break;
case ("text4"):
alert('miss 4');
break;
}
}
})
});
Fiddle Sample https://jsfiddle.net/shree/5ucxau2n/1/
I create a sample on button click.Hope its help.
This alerts each input that is missing.
$(function(){
$("button").on("click", function(){
$("input").each(function(){
if($(this).val() == ""){
alert($(this).attr("id") + " is missing");
}
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm">
<input type="text" name="text1" id="text1">
<input type="text" name="text2" id="text2">
<input type="text" name="text3" id="text3">
<input type="text" name="text4" id="text4">
</form>
<button>Enter</button>
This is if you just want a list of all the input elements that are missing. Only one alert box:
$("button").on("click", function(){
var str = ""
$("input").each(function(){
if($(this).val() == ""){
str += $(this).attr("id") + " and "
}
})
alert(str + " is missing");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form name="myForm" id="myForm">
<input type="text" name="text1" id="text1" placeholder = "type 1">
<input type="text" name="text2" id="text2" placeholder = "type 2">
<input type="text" name="text3" id="text3" placeholder = "type 3">
<input type="text" name="text4" id="text4" placeholder = "type 4">
</form>
<button>Enter</button>
Any Questions? let me know.

Form won't call javascript function when I press enter

<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="go" onclick="go()">
</form>
I have the function in an external javascript document that I have sourced at the bottom of my webpage, the function works when I click the submit button, just not when I hit enter.
My go function:
function go() {
var input = document.getElementById('searchbar').value;
var words = input.split(" ");
var wordsLength = words.length;
var searchWords = '';
if(words[0] == 'search' || words[0] == 'Search') {
for(var x = 1; x < wordsLength; x++) {
searchWords += words[x];
if(x == wordsLength-1) {
} else {
searchWords += '+';
}
}
window.location.replace("http://www.google.com/#q=" + searchWords);
} else if(words[0] == 'navigate' || words[0] == 'Navigate') {
for(var x = 1; x < wordsLength; x++) {
searchWords += words[x];
if(x == wordsLength-1) {
} else {
searchWords += '+';
}
}
window.location.replace("http://www.google.com/maps/place/" + searchWords);
}
}
You need to change
<input type="button" value="Go" class="go" id="go" onclick="go()">
to
<input type="submit">
<form id="search" onsubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit">
</form>
Your id of the button and the function name is same change one of those.
<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="_go" onclick="go()">
</form>
Try this, it is working.
HTML
<form id="search" onSubmit="return false">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="go">
</form>
JavaScript
$('form').keypress(function (e) {
if (e.which == 13) {
go($('#searchbar').val());
$('form#search_form').submit();
return false;
}
});
function go(keyword){
alert('Your search keyword is [' + keyword + ']');
}
Live Example
Try using jQuery solution.
<form id="search">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit" value="Submit">
</form>
On Form Submit call go().
$(document).ready(function() {
$('#search').submit(function() {
//Add code from go() or just call go()
});
});
UPDATE :
<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit" value="Submit">
</form>
Jquery Part.
$(document).ready(function() {
$('#searchbar').live("keypress", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
e.preventDefault();
e.stopPropagation();
$(this).closest('form').submit();
}
});
});

multiple forms with javascript

I am trying to show forms according to user input in the text box but it is showing it one time only...please help...
index.html:
<html>
<head>
<script type="text/javascript" src="demo1.js"></script>
</head>
<body>
<form name="su">
<input type="text" name="tt" onkeyup="javascript:toggleFormVisibility();" id="sub"/> </a>
</form>
<form id="subscribe_frm" style="display:none">
NAME:<input type="text" name="text">
EMAIL:<input type="text" name="text">
PASSWORD:<input type="text" name="text">
</form>
demo.js:
function toggleFormVisibility()
{
var txt = document.getElementById('sub').value;
for(var i=0;i<txt;i++)
{
var frm_element = document.getElementById('subscribe_frm');
var vis = frm_element.style;
vis.display = 'block';
}
}
A bit of a guess, but I think you are trying to create multiple copies of your form. Try this out:
http://jsfiddle.net/QnrM9/
JS
function toggleFormVisibility() {
var txt = document.getElementById('sub').value;
var neededChildren = txt.length - document.getElementById('form_container').children.length + 1;
for (var i = 0; i < neededChildren; i++) {
var frm_element = document.getElementById('subscribe_frm').cloneNode(true);
var vis = frm_element.style;
vis['display'] = 'block';
document.getElementById("form_container").appendChild(frm_element);
}
}
document.getElementById('sub').addEventListener('keyup', toggleFormVisibility);
HTML
<form name="su">
<input type="text" name="tt" id="sub" />
</form>
<div id="form_container">
<form id="subscribe_frm" style="display:none">NAME:
<input type="text" name="text" />EMAIL:
<input type="text" name="text" />PASSWORD:
<input type="text" name="text" />
</form>
</div>

Categories