I have many textarea,I want to check input length.
if not longer than 10 words, can't submit.
It will alert,but still submit.
function checkinput(){
$('.TextArea').each(function() {
var textl = $(this).val().length;
if ( textl < 10 && (EndTime.getTime()-Time != 0)) {
window.alert ( "answer need large 10 word!" );
return false;
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="answer.php" id="form" onsubmit="return checkinput();">
function checkinput() {
//create an event listener for click on your submit button
$('#submit').click(function(e) {
// define a variable to hold textareas
let $Textarea = $('.TextArea');
// run a loop on each textarea
$Textarea.each(function(i, v) {
// variable for each instance of textarea being triggered using keyword this
let input = $(this).val();
// split the value at each word using a blank space
let words = input.split(' ');
// check the length of the split array and see if there is 10 values present
if (words.length < 10) {
window.alert("Textarea " + i + " - answer need large 10 word!");
// preventDefault() keeps the form from submitting and refreshing the DOM
e.preventDefault();
return false;
}
});
});
}
checkinput();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="answer.php" id="form">
<textarea class='TextArea'></textarea>
<textarea class='TextArea'></textarea>
<textarea class='TextArea'></textarea>
<textarea class='TextArea'></textarea>
<button id='submit'>Submit</button>
</form>
Add event.preventDefault() for cases when the function is returning false;
function checkinput(event){
$('.TextArea').each(function() {
var textl = $(this).val().length;
if ( textl < 10 && (EndTime.getTime()-Time != 0)) {
event.preventDefault();
window.alert ( "answer need large 10 word!" );
return false;
}
});
return true;
}
Related
The following code is used to avoid duplicates input fields in HTML form
$(document).ready(function() {
$(".classesName").submit(function(e) {
e.preventDefault();
var frm = document.querySelector('form.classesName');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var classArr = [];
console.log("HI"); // To show that ajax is called again and again
var inputs = frm.querySelectorAll('input[type=text]');
inputs = Array.from(inputs); // So as to avoid UPPERCASE and lowercase i.e, HEL and hel
for (var i = 0; i < inputs.length; i++) {
inputs[i] = inputs[i].value.toUpperCase();
console.log(inputs[i]);
if (classArr.indexOf(inputs[i].value) != -1) {
alert("Duplicate Name Found");
return false;
} else
classArr.push(inputs[i].value);
}
frm.submit();
});
});
});
The problem is that when i enter HELLO and hello in the HTML form an alert message occurs saying the error, when i click ok and then edit to say HELLO and NEW.
#PROBLEM : the ajax call starts again, so now the alert message occurs twice when there is no duplicate values.
F12 BROWSER OUTPUT
HI
2HELLO
HI
HELLO
NEW
HI
HELLO
NEW
The problem is that you're creating multiple event listeners. $(".classesName").submit() creates a jQuery listener. When you call that it creates a regular JavaScript listener with frm.addEventListener(). The next time you submit, it runs both event listeners, and also adds another event listener.
You don't need to add the listener multiple times. Just use the jQuery listener.
Another problem is that you're replacing inputs[i] with its uppercase value, but then you're using inputs[i].value when searching classArr. Since inputs[i] is now a string, it doesn't have a .value property. Instead of replacing the array element, use a new variable.
$(document).ready(function() {
$(".classesName").submit(function(e) {
e.preventDefault();
var classArr = [];
console.log("HI"); // To show that ajax is called again and again
var inputs = $(this).find('input[type=text]');
for (var i = 0; i < inputs.length; i++) {
var val = inputs[i].value.toUpperCase();
console.log(val);
if (classArr.indexOf(val) != -1) {
alert("Duplicate Name Found");
return false;
} else
classArr.push(val);
}
this.submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="classesName">
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit">
</form>
How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.
When I submit a web form I call two functions, like this:
<form action="myaction" name="myform" method="post" onsubmit="return submithandler(this) && validate(this)">
The javascript:
function submithandler (form) {
// a function that replaces some diacritical marks to the correct form
return true;
};
function validate(form) {
// huge validation code
};
Works fine in all browsers, except Firefox; this browser does the submithandler(this) part, but ignores the validate(this). If I make the form tag like this (below), it does the validation but ignores submithandler(this).
<form action="myaction" name="myform" method="post" onsubmit="return validate(this) && submithandler(this)">
Any ideas please?
EDIT:
The Firefox problem must be within this script? Maybe var form = event.target; ? Please see here: Change characters on form submit
// The script replaces all instances of a letter (or whatever) inside all text fields in the form.
function submithandler (form) {
var form = event.target;
var i, l;
for (i = 0, l = form.elements.length; i < l; i += 1) {
if (form.elements[i].type === 'text') {
form.elements[i].value = form.elements[i].value.replace(/Ş/g, 'Ș');
form.elements[i].value = form.elements[i].value.replace(/ş/g, 'ș');
form.elements[i].value = form.elements[i].value.replace(/Ţ/g, 'Ț');
form.elements[i].value = form.elements[i].value.replace(/ţ/g, 'ț');
}
}
return true;
};
call the validate function inside the submithandler function:
function submithandler (form) {
// a function that replaces some diacritical marks to the correct form
if(isValid(form)){
return true;
} else{
return false;
}
};
function isValid(form) {
// huge validation code
//validation code: must return true if valid
if(valid){
return true;
} else {
return false;
}
};
I have form that I need to validate using JavaScript and I need to show all the messages at the same time. E.g if the first name and surename is missing for two messages to appear. I've got this working with the below code but the form is still being returned back to the server. P Lease see below:
function validateForm() {
var flag = true;
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "First name is required";
flag = false;
} else {
document.getElementById("fNameMessage").innerHTML = "";
}
var x = document.forms["myForm"]["surname_5"].value;
if (x == null || x == "") {
document.getElementById("sNameMessage").innerHTML = "Surename is required";
flag = false;
} else {
document.getElementById("sNameMessage").innerHTML = "";
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
flag = false;
} else {
document.getElementById("titleMessage").innerHTML = "";
}
return flag;
}
My form and event :
<form action=""method="post" accept-charset="UTF-8" name="myForm" onsubmit="return validateForm();">
My Button:
<input type="submit" class="button" name="submit" id="submit" value="Submit">
Your code:
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title")
... triggers an exception and you don't catch it:
Uncaught TypeError: Cannot read property 'options' of undefined
Thus JavaScript code stops running.
Since everyone seems to be providing jQuery answers and I didn't see anything in your orignal code that was jQuery-esque I'll assume you aren't using jQuery.
You should be using the event.preventDefault:
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit
document.getElementById("submit").addEventListener(
"click", validateForm, false
);
function validateForm(){
// We should not assume a valid form!
var formValid = false;
// All your validation code goes here
if(formValid){
document.forms["myform"].submit();
}
}
try something like
if(flag){
document.getElementById("submit").submit();
}
else{
$('#submit').click(function (e) {
e.preventDefault();
});
}
I want to see if it's possible to block the enter key and replace it with a space. I'm also using form validation to only allow letters, numbers and some other specific characters like the dollar sign,minus, and period and so on.
Here is that code, I would like to see if I can combine them into one and be able to check for the validation and replace the key press with a space all in one code/call.
<script type="text/javascript">
function ValidateForm(form)
{
var str
str=document.getElementById('limitedtextarea').value
str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
document.getElementById('limitedtextarea').value=str
//return true;
}
</script>
<FORM action="sms_SendMessage.asp" method=post onsubmit="javascript:return ValidateForm(this)" target=_blank>
Thanks for the help...
In javascript, the line-break character is represented by \n. You could replace them by spaces in your validation function like this :
function ValidateForm(form)
{
var str
str=document.getElementById('limitedtextarea').value
str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
str=str.replace(/\n/g, " ");
document.getElementById('limitedtextarea').value=str
//return true;
}
If you remove the onsubmit and do not have a submit button, typing enter will not submit it.
<body>
<form>
<textarea></textarea>
</form>
<script>
(function(){
var txt = document.getElementsByTagName('TEXTAREA')[0];
txt.onkeypress = function(ev){
ev = ev || window.event;
if ( ev.keyCode === 13 ){
if (window.event) {
window.event.returnValue = false;
}
if (ev && ev.preventDefault) {
ev.preventDefault();
}
txt.value += ' ';
}
};
})();
</script>
</body>