how to make working Captcha post comment form? - javascript

how to make function, when Captcha are correct sumbit by user, than "Post Comment Button" accept the click and post comment..
when captcha are incorrect sumbit by user, than "Post Comment Button" not accept click and says "please fill correct captcha"..
This Is Comment form
<p class="form-submit"><input name="submit" type="submit"
id="submit" class="submit" value="Post Comment">
</p>
This Is Working Captcha Javascript Code
var code;
function createCaptcha() {
//clear the contents of captcha div first
document.getElementById('captcha').innerHTML = "";
var charsArray =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#!#$%^&*";
var lengthOtp = 6;
var captcha = [];
for (var i = 0; i < lengthOtp; i++) {
//below code will not allow Repetition of Characters
var index = Math.floor(Math.random() * charsArray.length + 1); //get the next character from the array
if (captcha.indexOf(charsArray[index]) == -1)
captcha.push(charsArray[index]);
else i--;
}
var canv = document.createElement("canvas");
canv.id = "captcha";
canv.width = 100;
canv.height = 50;
var ctx = canv.getContext("2d");
ctx.font = "25px Georgia";
ctx.strokeText(captcha.join(""), 0, 30);
//storing captcha so that can validate you can save it somewhere else according to your specific requirements
code = captcha.join("");
document.getElementById("captcha").appendChild(canv); // adds the canvas to the body element
}
function validateCaptcha() {
event.preventDefault();
debugger
if (document.getElementById("cpatchaTextBox").value == code) {
alert("Valid Captcha")
}else{
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
input[type=text] {
padding: 12px 20px;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button{
background-color: #4CAF50;
border: none;
color: white;
padding: 12px 30px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
border-radius: 36px;
}
canvas{
/*prevent interaction with the canvas*/
pointer-events:none;
}
<body onload="createCaptcha()">
<form onsubmit="validateCaptcha()">
<div id="captcha">
</div>
<input type="text" placeholder="Captcha" id="cpatchaTextBox"/>
<button type="submit">Submit</button>
</form>
</body>
<p class="form-submit"><input name="submit" type="submit" id="submit" class="submit" value="Post Comment"> <input type="hidden" name="comment_post_ID" value="11666" id="comment_post_ID">
<input type="hidden" name="comment_parent" id="comment_parent" value="0">
</p>

Well your question has answer inside it
function validateCaptcha() {
if (document.getElementById("cpatchaTextBox").value == code) {
alert("Valid Captcha")
// Here add whatever you want to do if captcha is correct
}
else {
alert("Invalid Captcha. try Again");
createCaptcha();
// And if captcha is incorrect than here it will show and alert on top and then it will make captcha once again
}
}
Just see this code and read the Comments!

Related

How to set specific text input be not required to fill in

First of all i'm a newbie of programming . I want to create a mini project using multiform. I use example from https://www.w3schools.com/howto/howto_js_form_steps.asp but i wonder how to set specific text input be not required to fill in for proceed the process of submit the data. Sorry for asking.
This is the code from W3S but the validation code is changed.
If you look in the code you will find commented fields with many !!! this is the validator
EDIT:
Currently the field for "Last name" i added an attribute data="noverify" Currently, any field that has this attribute will not be required.
In this example: First name is required. A Last name is NOT required!
Add this attribute data="noverify" for all fields you want NOT to be required!
This check y[i].getAttribute('data') !== "noverify" is made below in the code to skip the fields with data="noverify"
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<style>
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
</style>
<body>
<form id="regForm" action="/action_page.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." oninput="this.className = ''" name="fname"></p>
<p><input data="noverify" placeholder="Last name..." oninput="this.className = ''" name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." oninput="this.className = ''" name="email"></p>
<p><input placeholder="Phone..." oninput="this.className = ''" name="phone"></p>
</div>
<div class="tab">Birthday:
<p><input placeholder="dd" oninput="this.className = ''" name="dd"></p>
<p><input placeholder="mm" oninput="this.className = ''" name="nn"></p>
<p><input placeholder="yyyy" oninput="this.className = ''" name="yyyy"></p>
</div>
<div class="tab">Login Info:
<p><input placeholder="Username..." oninput="this.className = ''" name="uname"></p>
<p><input placeholder="Password..." oninput="this.className = ''" name="pword" type="password"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
if (y[i].getAttribute('data') !== "noverify") {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
}
// If the valid status is true, mark the step as finished and valid:
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script>
</body>
</html>
you can use value for set default text value
<div class="tab">Name:
<p><input placeholder="First name..." value="One" oninput="this.className = ''"></p>
<p><input placeholder="Last name..." value="Two" oninput="this.className = ''"></p>
</div>

Use JS to determine if all form fields are filled and correctly

*Edit: Fixed so that all inputs are now validated on one form. However, I can only add one variable to check if blank, as soon as I add more, none of the submit functions work. I have been trying multiple things.
function validateForm() {
var inputVelocity = document.getElementById("dzCalculator").inputVelocity.value;
var inputYellowPhase = document.getElementById("dzCalculator").inputYellowPhase.value;
var inputRedPhase = document.getElementById("dzCalculator").inputInterPhase.value;
var inputReactionTime = document.getElementById("dzCalculator").inputReactionTime.value;
if(inputVelocity === "" && inputYellowPhase === "" && inputRedPhase === "" && inputReactionTime === ""){
alert("Input all fields to calculate.");
return false;
}
}
I have checked the HTML matches - it does. But I found I could not use onsubmit="return validateForm" as this wouldn't work at all.
This is only 4 of the form values, there are seven all up. But when I can get the four working, I can get them all working.
How can I use JS to make sure that no input is left blank or empty? I already have made it so that it will only accept numbers and decimal points. So no one can add an incorrect field. But currently, they can leave a field blank which means my calculator generates a NaN response.
Also, how can I make sure one of my fields can not accept a number greater than 1 or less than 0. I tried min="0" max="1" in the input tag, but because I have removed spinners, this doesn't work.
So, in summary, I am looking to make sure when a button is clicked that all the form sections are filled in and that one of the fields doesn't accept a number greater that 1 or less than zero.
there are 2 options for this.
You can select all the inputs (inside the form tag) using querySelector and check the value of each input by looping through them.
use this trick selector to get all the invalid inputs
document.querySelectorAll('input:not([value]):not([value=""])');
replace input with more precise selector.
Can you please give more detail about how your form is in multiple places?
For input I think you need to use step attribute
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step
Reference: javascript_form_validation
Depends when would you like to validate form fields
For example: Form validation on submit
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<html>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Give name to your form using name attribute such as <form name="myForm" ..>
Then using document.forms["myForm"] you can have access to your form
There you can validate your input fields value. return true if validates
This works for me. You can use it, style it however you want or not. You do need JQuery. It has powerful selectors.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
body{
font-size: 12px;
}
.main-container{
display: flex; /* DO NOT CHANGE */
height: 100vh; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
}
.c-message{
display: flex; /* DO NOT CHANGE */
position: fixed; /* DO NOT CHANGE */
top: 0px; /* DO NOT CHANGE */
left: 0px; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
height: 100%; /* DO NOT CHANGE */
}
.c-msgbox{
padding: 30px;
text-align: center;
margin: auto; /* DO NOT CHANGE */
background-color: #e4e4e4;
border-radius: 4px;
border: 1px solid #adadad;
-webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
-moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);
}
.standerd-button2{
border: none;
font-family: arial,helvetica,clean,sans-serif;
font-size: 10px;
font-weight: 600;
color: white;
background: #1A709F;
padding: 3px;
text-align: center;
vertical-align: middle;
-webkit-border-radius: 3px;
width: max-content;
min-width: 50px;
margin: 2px;
}
.standerd-button2:hover{
background: crimson;
cursor: default;
}
.f-table {
display: table;
width: max-content;
padding: 5px;
border-spacing: 2px;
}
.f-tablerow {
display: table-row;
}
.f-tablecell{
display: table-cell;
}
.label-cell-r{
text-align: right;
}
.dd-required{
margin: auto;
color: red;
}
input, select{
border: 1px solid lightgrey;
}
</style>
<script type="text/javascript" src="JQuery.js"></script>
</head>
<body>
<div class="main-container">
<div>
<form id="f1" name="f1">
<div class="f-table">
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="firstname">First Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="firstname" name="firstname" type="text" data-er="First Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="lastname">Last Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="lastname" name="lastname" type="text" data-er="Last Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="company">Company</label>
</div>
<div class="f-tablecell input-cell">
<select id="company" name="company" data-er="Company Name">
<option value="0"> - Select Comapny - </option>
<option value="1">Company 1</option>
<option value="2">Company 2</option>
<option value="3">Company 3</option>
<option value="4">Company 4</option>
</select>
<span class='dd-required'>*</span>
</div>
</div>
</div>
<input id="b1" type="submit" value="Submit" />
</form>
</div>
<div>
<script type="text/javascript">
$.fn.CustomAlert = function (options, callback) {
var settings = $.extend({
message: null,
detail: null,
yesno: false,
okaytext: null,
yestext: null,
notext: null
}, options);
var frm = "";
detail = "<b>" + settings.detail + "</b>";
message = "<b>" + settings.message + "</b>";
if (settings.detail === null) {
detail = "";
};
frm = frm + message + "<div style='text-align: left; margin-top: 15px; margin-bottom: 15px;'>" + detail + "</div>";
if (settings.yesno === false) {
frm = frm + "<input id='ok' type='button' value='" + settings.okaytext + "' class='standerd-button2' />";
} else {
frm = frm + "<div><input id='yes' type='button' value='" + settings.yestext + "' name='yes' class='standerd-button2' />" +
"<input id='no' type='button' value='" + settings.notext + "' name='no' class='standerd-button2' /></div>";
};
var frmesg = "<div id='cmessage' name='cmessage' class='c-message'>" +
"<div class='c-msgbox'>" +
"<form>" + frm + "</form>" +
"</div>" +
"</div>";
$(".main-container").append(frmesg);
if (!settings.yesno) {
$("#cmessage #ok").click(function () {
$("#cmessage").remove();
callback(false);
});
} else {
$("#cmessage #yes").click(function () {
$("#cmessage").remove();
callback(true);
});
$("#cmessage #no").click(function () {
$("#cmessage").remove();
callback(false);
});
};
};
$.fn.JsFormCheck = function () {
var MessData = "";
this.find('select, input').each(function () {
if ($(this).attr("data-er")) {
m = $(this).attr("data-er");
switch ($(this).get(0).tagName) {
case "INPUT":
if ($(this).val().length === 0) {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
case "SELECT":
if ($(this).val() === "0") {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
};
};
});
if (MessData.length > 0) {
MessData = "<b>" + MessData + "</b>";
x = $().CustomAlert({message: "<b>Please fill in the following required fields to continue.</b>",
detail: MessData,
okaytext: "Close",
yesno: false});
return true;
} else {
return false;
};
};
$('#f1 #b1').click(function(event){
event.preventDefault();
Error = $("#f1").JsFormCheck();
if(Error === false){
null;
//Do Something
};
});
</script>
</body>

Need to add function to make sure at least 1 checkbox is selected before submitting multipage form?

I am working on a form with multiple pages. On one page I have check boxes that I would require at least one to be selected before submission. How can I do that with javascript/html5?
It is all one form that changes pages with javascript. How on the last page can I have the form check, if at least one checkbox has been selected?
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
<form id="regForm" action="/action_page.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." oninput="this.className = ''" name="fname"></p>
<p><input placeholder="Last name..." oninput="this.className = ''" name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." oninput="this.className = ''" name="email"></p>
<p><input placeholder="Phone..." oninput="this.className = ''" name="phone"></p>
</div>
<div class="tab">
<H3 id="subhead">AUDITORIUM ROOM SETUP & EQUIPMENT REQUESTS</H3>
<label><label id="asterisk">*</label>Room Setup (Select all that apply):</label><br><br>
<!-- <p><input placeholder="dd" oninput="this.className = ''" name="dd"></p> -->
<br>
<input id="element_3_1" name="Room-Setup" required type="checkbox" value="Auditorium-Seating-for-300" />
<label class="choice" id="labelinput" for="element_3_1">Auditorium Seating for 300</label>
<br>
<input id="element_3_2" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Auditorium-Seating-for-350" />
<label class="choice" id="labelinput" for="element_3_2">Auditorium Seating for 350 (recommended max for Performances</label>
<label class="choice" for="element_3_3">Auditorium Seating 400</label>
<input id="element_3_3" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Auditorium-Seating-400" />
<label class="choice" for="element_3_4">Round Tables and Chairs</label>
<input id="element_3_4" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Round-Tables-and-Chairs" />
<label class="choice" for="element_3_5">Other (Please note that we cannot change the auditorium setup during your event*)</label>
<input id="element_3_5" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Other" />
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
Put a second classname in <div class="tab theFirstTabWithCheckboxes">
This code get that element and counts cheched inputs to a global variable
var checkboxes = document.querySelectorAll("tab.theFirstTabWithCheckboxes input");
var i = checkboxes.length;
window.count_nr_of_checked_boxes = 0;
while (i--) { //count down to 0
if (checkboxes[i].checked) window.count_nr_of_checked_boxes++;
}
With querySelectorAll() you select in the same way as you select in CSS. Note how the dot operator is an and operator and the space operator means "input is inside ..." (it is evaluated from right to left).
Put the following line in the function validateForm()
if (count_nr_of_checked_boxes < 1) valid = false
You dont need to have window. on global variables

Javascript needed for form reset button

I have a form with a text area as well as javascript counter that counts how many characters you type into the text area. I need a button that resets both whats typed into the text area AND the counter.
This is my form code:
<script type="text/javascript">
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len -
el.value.length;
return true;
}
</script>
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2" maxLength="60" onkeyup="change(this);"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" value="reset title" />
</form>
The javascript below resets the text entered into the textarea but it does not reset the counter within the span "left_char_cnt"
<script>
function myFunction() {
document.getElementById("title").reset();
}
</script>
What javascript is needed to reset both?
You cannot "reset" the text / HTML of an element if you haven't saved it somehow. reset() only works for form inputs.
So what you have to do is rewrite the HTML content of your element.
<script>
function myFunction() {
document.getElementById("title").reset();
document.getElementById("left_char_cnt").innerHTML = '<b>0</b>';
}
</script>
your script to count words in text is not working but, i made a script to clear textarea & count
function myfun(){
document.getElementById('txtarea').value=' ';
document.getElementById('count').innerHTML='0';
}
<form id="title">
<textarea id="txtarea" style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2"></textarea>You've typed <span id="left_char_cnt"><b id=count>123</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b >lots</b></span> more
<input class="btn btn-primary" type="button" onclick="myfun()" value="reset title" />
</form>
<script type="text/javascript">
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len -
el.value.length;
return true;
}
</script>
The simplest way is to reuse the code you already have, and allow the change event handler to set the values correctly. That way, if you ever change the behavior of that function then the reset will also change to match it.
I also modified your code slightly to make it update as the text is changing, rather than when you leave the textarea.
Try this...
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len - el.value.length;
return true;
}
var textarea = document.querySelector("#title textarea");
textarea.addEventListener("keyup", function() { change(this); });
document.querySelector("#reset-button").addEventListener("click", function() {
textarea.value = "";
change(textarea);
});
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" id="reset-button" value="reset title" />
</form>
var t = document.getElementsByTagName('textarea')[0];
var a = document.getElementById('left_char_cnt');
var b = document.getElementById('left_chars_left')
t.addEventListener('keyup',function(){
var value = t.value.length;
var maxval = 60;
a.innerHTML = value
b.innerHTML = (maxval- value)
if(value == 60){ a.maxLength = maxval}
})
function resetVal(){
t.value = null;
a.innerHTML = '<b>0</b>'
b.innerHTML = '<b>lots</b>'
}
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2" maxlength="60"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" onclick='resetVal()' value="reset title"/>
</form>
Use this function, by replacing your 'myFunction()'
<script>
function myFunction() {
document.getElementById("title").reset(); // reset your form
document.getElementById("left_char_cnt").innerHTML = '<b>0</b>'; //reset your span counter
}
</script>

How to disable Form Onsubmit function JSP

I have two radio buttons, (Yes and No) when the user choses Yes, a set of text boxes will appear and is required to have at least one entry in order to submit. If the user chose "No" he/she can submit with no entries or whatsoever. I have everything working except for the "No" part.
The validation function works inside the form, is there anyway to disable it when the chosen button is "No"?
<script type="text/javascript">
function checkEvent() {
console.log("infunc");
if(document.getElementById('events_yes').checked){
document.getElementById('if_events_yes').style.display = "block";
}
else{
document.getElementById('if_events_yes').style.display = "none";
document.getElementById('myForm').removeAttribute("onsubmit","");
}
}
</script>
<form action="ResponseDB" method="post" id="myForm">
<input name="tipid" value="<% out.println(tipid);%>" type = "hidden">
Any events to report?<br>
<input type="radio" name="events" onclick="checkEvent()" id="events_yes" value="no">Yes<br>
<input type="radio" name="events" onclick="checkEvent()" id="events_no" value="yes" checked>No<br>
<div id="if_events_yes" style="display:none">
<br><br>
Firewall:<br>
<textarea rows="5" cols="80" name="firewall"></textarea><br>
IDS/IPS:<br>
<textarea rows="5" cols="80" name="ids"></textarea><br>
Web Content Filtering/Proxy:<br>
<textarea rows="5" cols="80" name="proxy"></textarea><br>
Deep packet inspection:<br>
<textarea rows="5" cols="80" name="dpi"></textarea><br>
Network malware protection devices (FireEye, Damballa, etc.):<br>
<textarea rows="5" cols="80" name="net_malware"></textarea><br>
Anti-virus software:<br>
<textarea rows="5" cols="80" name="av" id="av"></textarea><br>
Forensics Tools:<br>
<textarea rows="5" cols="80" name="forensics"></textarea><br>
Tripwire:<br>
<textarea rows="5" cols="80" name="tripwire"></textarea><br>
Memory Dumps:<br>
<textarea rows="5" cols="80" name="memdumps"></textarea><br>
Email logs:<br>
<textarea rows="5" cols="80" name="email_logs"></textarea><br>
</div>
<input type="submit" value="Submit">
</form>
<script>
onsubmit=function() {
var t = document.getElementsByTagName("textarea"),
l = 0;
for(var i = 0; i < t.length; i++){
l = l + t[i].value.trim();
}
if (l < 1) {
alert("Please have at least one entry");
return false;
}
}
</script>
This is the portion I'm working on. Is there anyway I can disable the onsubmit function when the user choses No?
You should be able to use this example from w3schools. Their example sends to an asp page, but that doesn't matter.
I have copied the part you need here, but for more details on how or why it works visit the link above.
JavaScript Part
a JavaScript function like this but checking the state of your radio buttons:
function validateForm() {
//here just get the value(s) from your radio(s)
var x = document.forms["myForm"]["fname"].value;
//check the value
if (x == null || x == "") {
alert("Name must be filled out");
//this prevents the submit to your server
return false;
}
}
Form Part
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
It is working thanks to Kevin2 from webdeveloper.com forums....
<%#page import="com.sun.xml.internal.txw2.Document"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="db.ResponseTracker"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MASC Response Form</title>
<style>
/* this selector could be div#nav instead of nav depending on which tag you wrapped the ul in */
#nav {
width: 100%;
float: left;
margin: 0 0 1em 0;
padding: 0;
background-color: #f2f2f2;
border-bottom: 1px solid #ccc; }
#nav ul {
list-style: none;
width: 800px;
margin: 0 auto;
padding: 0; }
#nav li {
float: left; }
#nav li a {
display: block;
padding: 8px 15px;
text-decoration: none;
font-weight: bold;
color: #069;
border-right: 1px solid #ccc; }
#nav li:first-child a {
border-left: 1px solid #ccc; }
#nav li a:hover {
color: #c00;
background-color: #fff; }
#tipid, fieldset {
display: none;
}
label {
display: block;
}
fieldset {
border: 0;
width: 50%;
}
textarea {
width: 100%;
height: 5em;
}
.active {
position: fixed;
left: 54%;
bottom: 2em;
}
</style>
<script src="nav.jsp"></script>
</head>
<body>
<div id="nav">
<ul>
<li>My Data</li>
<li>Logout</li>
</ul>
</div>
<% ResponseTracker tracker = new ResponseTracker() ;
int tipid = 0;
if(request.getParameter("tipid") != null)
{
tipid = Integer.parseInt(request.getParameter("tipid"));
}
if (tipid == 0){ response.sendRedirect("/MASC/index.jsp");}
%>
<h1> Tip report for <% out.print(tracker.getDateStringByTipId(tipid));
tracker.finalize();%></h1>
<%if(request.getParameter("failed") != null)
{
%> <br><font color=\"red\"> Login failed</font> <%
}
%>
<form action="ResponseDB" method="post">
<input name="tipid" id="tipid" value="<% out.println(tipid);%>">
Any events to report?
<label><input type="radio" name="events" onclick="checkEvent(this.value,if_events_yes,submit)" id="events_yes" value="yes">Yes</label>
<label><input type="radio" name="events" onclick="checkEvent(this.value,if_events_yes,submit)" id="events_no" value="no" checked>No</label>
<fieldset id="if_events_yes">
<label>Firewall:<br>
<textarea name="firewall"></textarea></label>
<label>IDS/IPS:<br>
<textarea name="ids"></textarea></label>
<label>Web Content Filtering/Proxy:<br>
<textarea name="proxy"></textarea></label>
<label>Deep packet inspection:<br>
<textarea name="dpi"></textarea></label>
<label>Network malware protection devices (FireEye, Damballa, etc.):<br>
<textarea name="net_malware"></textarea></label>
<label>Anti-virus software:<br>
<textarea name="av"></textarea></label>
<label>Forensics Tools:<br>
<textarea name="forensics"></textarea></label>
<label>Tripwire:<br>
<textarea name="tripwire"></textarea></label>
<label>Memory Dumps:<br>
<textarea name="memdumps"></textarea></label>
<label>Email logs:<br>
<textarea name="email_logs"></textarea></label>
</fieldset>
<input type="submit" id="submit" value="Submit">
</form>
<script>
function checkEvent(el,y,s) {
console.log("infunc");
if (el == 'yes') {
y.style.display = "block";
s.className = "active";
}
else {
y.style.display = "none";
s.className = "";
}
}
onsubmit=function() {
if (document.getElementById('events_yes').checked == true) {
var t = document.getElementsByTagName("textarea"),
l = 0;
for(var i = 0; i < t.length; i++){
l = l + t[i].value.trim();
}
if (l < 1) {
alert("Please re-enter");
return false;
}
}
}
</script>
</body>
</html>

Categories