function not working in jsp page? - javascript

<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**

I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}

The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length

Related

How can I pass the zip to the button function?

I did wrap this in a form with a submit button, but realized that this attempted to go to a new page without performing the logic. How can I pass the zip code to the onclick button event? If this is completely wrong, can you provide guidance onto how to perform this correctly.
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
}
</script>
You need to get the value of your input and you can do this with document.querySelector('[name="zip"]').value
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zip = document.querySelector('[name="zip"]').value;
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
})
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
Just use getElementById('ELEMENT_NAME_HERE').value like so:
Go!
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip){
console.log('Clicked');
var enteredZip = document.getElementById("zip").value;
console.log(enteredZip);
var zipCodes=[26505, 26501, 26507, 26506];
for(i=0; i<=zipCodes.length-1; i++){
if(zip == zipCodes[i]){
alert("YES");
break;
}}});
</script>
https://plnkr.co/edit/ptyUAItwyaSmZXsD81xK?p=preview
You can't pass it in.
basically if this myfunction() will return a false then the form would not be submitted;
Also this would only be performed at the time of submittion of the form
https://www.w3schools.com/jsref/event_onsubmit.asp
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input id='input-id' type="submit">
</form>
<script>
myfunction(){
if(/*some condition*/)
{
return false;
}
</script>
Also few things to consider since you seem new and people here are giving you very correct but specific solutions.
if you add a button to inside tag, that would submit the form on clicking it.
That is why many use a div which looks like a button by css. Mainly a clean solution to override the Button submit and also you can simply submit the form by Javascript.

multiple function not working for onsubmit

My form is validating the two java functions script and if both are true it will continue the form submit. But when i submit it validates only first function validateFormROLLNO() not the second function. Also, when the first function fails it submits the form anyway. I want to submit the form only when the two functions are passed.
first function will check if the roll no = 12 characters.
second function checks if the name is not null.
<body>
<center>
<script type="text/javascript">
function validateFormROLLNO() {
var x = document.forms["myForm"]["id"].value;
if (x !=12) {
alert("ROLLNO must be 12 characters long!!!!");
return false;
}
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
function validateFormNAME() {
var p = document.forms["myForm"]["student"].value;
if (p =='') {
alert("Name cannot be NULL!!!!");
return false;
}
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
function validate(){
return validateFormROLLNO() && validateFormNAME();
}
</script>
<br> <FORM name="myForm" ACTION="insert.jsp" onsubmit="return validate()" METHOD="POST">
Please enter the Rollno and Name you want to INSERT:
<BR> <br>
<b>ISIN :<INPUT TYPE="TEXT" NAME="id"></b>
<BR><BR>
<b> SOURCE :<INPUT TYPE="TEXT" NAME="student"></b>
<br><BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</center>
</body>
</html>
There might be some javascript errors exists on the page, that don't let second function to execute. Please use browser's inspect element to explore it.
document.forms["myForm"]["id"].value you are are checking value of the textbox. Please document.forms["myForm"]["id"].value.length to validate it.
Here is the complete method.
function validateFormROLLNO() {
var x = document.forms["myForm"]["id"].value;
if (x.length <12) {
alert("ROLLNO must be 12 characters long!!!!");
return false;
}
else
return true;
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}

javascript validation on array not running

I've read through many posts, and tried various options, but my validation check on my JavaScript doesn't seem to be running.
I used this post to try and write a validation check to see if the entered zip code is one one delivered to, but when I run it nothing happens and neither alert shows up. Any help is appreciated.
This is the JavaScript I was using:
<script type="text/javascript">
function validateZip() {
var zipCode = $("#zipCode").val();
var acceptableZipCodes = ["78205","72215","78212",];
if( $.inArray( zipCode, acceptableZipCodes)){
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
</script>
This is the form
<form name="zipForm" onsubmit="return(validateForm(zipCode))">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
function validateZip() {
var zipCode = document.zipForm.zipCode.value;
var acceptableZipCodes = ["78205","72215","78212",];
for (i = 0; i < cars.acceptableZipCodes.length; i++) {
if(acceptableZipCodes[i] == zipCode{
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
}
There are 2 mistakes I found.
1, you define the function validateZip, but you didn't call it in the script.
2, inArray() function will be return the position of the value in the array, so when a value doesnt in the array, it will return -1.
I do some changes in the code.
Hope it help you.
<form name="zipForm" onsubmit="return(validateZip())">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
<script type="text/javascript">
function validateZip() {
var zipCode = $("#zipCode").val();
var acceptableZipCodes = ["78205","72215","78212",];
if( $.inArray( zipCode, acceptableZipCodes) !== -1){
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
</script>
I would use an ID instead of name attribute for your form tag (for a quicker retrieval).
<form id="zipForm">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
Then below, I would do this:
<script>
$(function() {
// add an event handler to your form (look at adeneo's comment)
$('#zipForm').on('submit', function(e) {
// prevent form from submitting
e.preventDefault();
// call your function
validateZip($("#zipCode").val());
});
function validateZip(zipCode) {
var acceptableZipCodes = ["78205", "72215", "78212"];
// be careful with using $.inArray as the return value for no
// matches is -1 (and not false)
if ($.inArray(zipCode, acceptableZipCodes) != -1) {
alert("Yes, we can help!");
} else {
alert("Sorry, we don't deliever to your area yet.");
}
}
});
</script>
You should check if it's begger than -1:
if($.inArray( zipCode, acceptableZipCodes) > -1)
Here a jsfiddle example: JSFiddle

getting validation to check boxes

Hello all: I recently stumbled upon a question about form validation, which I'm currently trying to get working. I got the code from an answer and then customized it to more what I'm needing.:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Validate(){
if(!validateForm()){
alert("Something happened");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
</script>
</head>
<body>
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate()" method="get">
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
NOTE: The image is just from a Google Image Search, and is on Wikipedia (I do not own it).
Now, when I originally entered the HTML from the answer into the Tryit Editor at W3 Schools, it would give me a "Something Happened" alert, or do nothing. (I think that's what is was supposed to do).
Still, (now that I have my own questions) it will say "something happened" if nothing is selected, but no matter how many check (over 1 checked) it will just give me the image. Basically, what I want is it to check if ALL or ONLY SOME are checked. If all are checked i want one image, and if only some, I want a different one.
I hope this isn't too confusing, and I appreciate any help :)
P.S.:Here is the question where I got the code: Original Question
Try this for the script section, it will change the form's "action" attribute (which points the form to a the desired URL upon submitting) after validating how many checkboxes are checked:
<script type="text/javascript">
function Validate(formRef){
var checkboxes = getCheckboxes(formRef);
var checkedCount = validateForm(checkboxes);
if(checkedCount == checkboxes.length){
// All are checked!
return true;
} else if(checkedCount > 0) {
// A few are checked!
formRef.setAttribute('action', 'http://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Yahoo!_logo.svg/200px-Yahoo!_logo.svg.png');
return true;
} else {
alert("Something happened");
}
return true;
}
function getCheckboxes(formRef) {
var c = formRef.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i<c.length; i++){
if (c[i].type == 'checkbox')
{
checkboxes.push(c[i]);
}
}
return checkboxes;
}
function validateForm(checkboxes) {
var checkedCount = 0;
for (var i = 0; i < checkboxes.length; i++){
if (checkboxes[i].checked){
checkedCount++;
}
}
return checkedCount;
}
</script>
The form HTML should be updated to pass "this", the reference to the form object being validated, into the Validate() function, to avoid the need to query for it again:
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate(this)" method="get">
Try this (will alert first option if one or more but less than 3 checked, will alert second option if exactly 3 checked):
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input value="Submit" type="submit" onclick="
var count = 0;
for(var i = 0; i < document.getElementsByTagName('input').length - 1; i++)
{
if(document.getElementsByTagName('input')[i].checked)
{
count += 1;
}
}
if(count >= 1 && count < 3)
{
alert('First Option');
}else
{
if(count == 3)
{
alert('Second Option');
}
}" />
</body>
</html>
The following should get you on the right path:
function Validate() {
var checkboxes = processCheckboxes();
if (checkboxes.all.length == checkboxes.checked.length) {
alert("All are checked");
} else if (checkboxes.checked.length > 0) {
alert("Some checked");
} else {
alert("None checked");
}
return false;
}
function processCheckboxes() {
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var checked = [].filter.call( checkboxes, function( el ) {
return el.checked
});
return { all: checkboxes, checked: checked };
}
You can then process the checked boxes in whatever manner you like before submitting.
See a working example here: http://jsfiddle.net/jkeyes/Zcu7d/

How to disable input attribute after 10 clicks?

I am trying to remove the style or the background of a textbox to reveal the content after 10 clicks. How can I do that on Javascript?
here is my html:
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000">
and here is my JS:
function check() {
var tries++;
if (tries == 10){
document.getElementById('firstN').disabled= true;
}
}
The problem is that tries is a local variable (local to the check function). Every time check is called, a new variable named tries is created and initialized to 0.
Try this instead:
var tries = 0;
function check() {
tries++;
if (tries == 10) {
document.getElementById('firstN').style.background = '#ffffff';
}
}
(I'm assuming that you already have some code to call check when the element is clicked. If not, you need to add a click handler to your element.)
You are instantiating a var "tries" everytime you go into this function. Move the variable up a level to where it will increment:
var btn = document.getElementById("btnclick");
btn.onclick = check;
var tries = 0;
function check() {
tries++;
if (tries == 10){
var ele = document.getElementById("firstN");
ele.value= "DISABLED";
ele.disabled = true;
}
}​
EDIT:
Working JSFiddle
store it in a cookie:
<script type="text/javascript">var clicks = 0;</script>
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" value="Click" onclick="clicks++">
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
Here you go. Remove the alert lines when you see that it works.
<html>
<head>
<title>Test</title>
<script>
function check(){
var getClicks = parseInt(document.getElementById('firstN').getAttribute('clicks')); //Get Old value
document.getElementById('firstN').setAttribute("clicks", 1 + getClicks); //Add 1
if (getClicks === 10){ //Check
alert('Locked');
document.getElementById('firstN').disabled= true;
} else {
alert(getClicks); //Remove else statement when you see it works.
}
}
</script>
</head>
<body>
<form action="#">
Input Box: <input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" onclick="check();" clicks="0">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>

Categories