Minimal length in textarea validation - javascript

I have a problem with my script.
It is only partly working. If i enter less then 15 charachters the alert appears but then i click ok on the alert massage and the from gets send anyway. I am not sure waht i'm doing wrong. Here is my script:
function checktextarea() {
var minLength = 15;
var $textarea = $('#massage');
if($textarea.text().split(/\s+/).length < minLength) {
alert('You need to enter at least ' + minLength + ' words');
return false;
}
}
This is the html:
<form action="kontaktsi.php" name="myForm" id="myForm" method="post" class="contact_form" onsubmit="checktextarea()">
<span class="sporo">
<input type="text" id="fname" name="fname" class="contacttextform form-control" placeholder="Name" required>
</span>
<input type="email" id="email" name="email" class="contacttextform" placeholder="Your email" required><br><br>
<textarea name="message" id="message" cols="8" rows="8" class="contacttextarea" placeholder="text text text?" required></textarea>
<br>
<div class="send">
<input name="send" type="submit" class="contactformbutton" style="width:150px;" value="Send">
</div>
</form>

change your <form> tag into this:
<form action="kontaktsi.php" ... method="post" onsubmit="return checktextarea()">
You need to add return to the call, in order to pass the boolean value false to the submit event.
There's also a typo in your script: change $('#massage') into $('#message')
Finally, you need to use val() instead of text() to get the value of a <textarea>.
Here's the final script:
function checktextarea() {
var minLength = 15;
var textarea = $('#message');
if(textarea.val().replace(' ') < minLength) {
alert('You need to enter at least ' + minLength + ' words');
return false;
}
return true;
}

I am not 100% sure if it is the only way, but the last time I solved this problem I avoided the generic onsubmit mechanism; precisely because of the missing way of breaking in case of error.
Instead, one can bind a jQuery submit event and then use preventDefault() in case of error, as described here:
http://api.jquery.com/submit/
One can even submit directly with jQuery: Submit a form using jQuery
It is slightly more work, but you have much better control.

try this
function checktextarea() {
var minLength = 15;
var $textarea = $('#massage');
if($textarea.val().split(' ').length < minLength) {
alert('You need to enter at least ' + minLength + ' words');
return false;
}
}

Related

JavaScript: Stopping form from refreshing? [duplicate]

This question already has answers here:
Using JQuery - preventing form from submitting
(15 answers)
Closed 5 years ago.
I am trying to get my form to stop refreshing on submit and instead I would like to make an ajax call, I haven't done the ajax part yet but its still refreshing?
What have you tried?
I have took suggestions on the forum and added 'return false;' after the function is called onSubmit?
$('#message_form').submit(function() {
postMessage();
return false;
});
function postMessage() {
var isValid = true;
var username = document.forms["post_message_form"]["username"].value;
var message = document.forms["post_message_form"]["message"].value;
var errorMessage = "Something went wrong, try again!";
if (isEmpty(username) || isEmpty(message)) {
errorMessage = "You can't post with an empty name or message.";
isValid = false;
}
if (!isValid) {
alert(errorMessage);
}
else {
alert("Your message has been posted.");
}
return false;
}
function isEmpty(field) {
return field == null || field == "";
}
Form:
<form id="message_form" name="post_message_form" method="post">
<input type="text" class="form-control" placeholder="Whats your name?" name="username">
<textarea class="form-control" placeholder="Whats your message?" name="message"></textarea>
<input type="submit" class="btn btn-info" name="message_form" value="Submit Message">
</form>
Try this:
<form id="message_form" name="post_message_form" method="post" onsubmit="return postMessage();">
<input type="text" class="form-control" placeholder="Whats your name?" name="username">
<textarea class="form-control" placeholder="Whats your message?" name="message"></textarea>
<input type="submit" class="btn btn-info" name="message_form" value="Submit Message">
</form>
Try this code added onsubmit="return postMessage()
<form id="message_form" name="post_message_form" method="post" onsubmit="return postMessage()">
<input type="text" class="form-control" placeholder="Whats your name?" name="username">
<textarea class="form-control" placeholder="Whats your message?" name="message"></textarea>
<input type="submit" class="btn btn-info" name="message_form" value="Submit Message">
</form>
EDIT: Updated
There can be certain reasons regarding this kind of issue
postMessage is not accessible
There may be chances that this message is not globally declared
There may be other error in javascript code
Some some piece of code does not work due to error in other parts of javascript code
There may be chances that you have not loaded jquery core library file
If have not include jquery.min.js file your above code will not work (your case - See comments)
Since return false and event.preventDefault(); do the same work in this example you can use one of them
$('#message_form').submit(function(event) {
event.preventDefault();
postMessage();
// return false;
});
To debug the code and find the error you can open developer tools in browser by pressing f12 or select option inspect element by clicking right click on the page
use preventDefault instead return false;
$('#message_form').submit(function(event) {
console.log(123);
event.preventDefault();
});
https://codepen.io/animhotep/pen/bRBmxm?editors=1011
like in official maual ;) https://api.jquery.com/submit/

Validating input text field using Javascript

I guess I'm doing a trivial error somewhere but will be grateful if someone can spot it.
I am trying to validate a postcode in a form field once it has been typed in. Similar code works fine in PHP but I've spent hours and the JS does not seem to be executing whatever I do.
Here is part of the form (all within body tags):
<form name ="register" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
...
<script type="text/javascript" src="common.js">
</script>
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onchange="isValidPostcode(this.form)" required />
Here are versions of the javascript (stuffed with alerts just to print out something).
Version 1:
function isValidPostcode(form) {
alert("called");
var p = document.register.postcode.value;
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
Version 2 (is called without a parameter):
function isValidPostcode() {
alert("called");
var p = document.getElementById('postcode').value.replace(/\s/g,'');
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
I tried binding to other events but can't get a single alert out. Even exact reproduction of the examples is not working. Hope someone gives me an idea of what is wrong.
you should replace onchange with keyup and remove quotes from regex :)
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onkeyup="isValidPostcode(this.value)" required />
function isValidPostcode(value) {
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(value)) console.log("OK");
else console.log("This does not look a valid UK postcode...");
}
You should use the keyup event to do that and add the event using JS, not inline it.
postcodeRegEx is a regex, not a string, you need to remove quotes around it.
function isValidPostcode() {
var p = document.getElementById('postcode').value.replace(/\s/g, '');
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
document.getElementById("postcode").addEventListener("keyup", function() {
isValidPostcode();
});
<form name="register" method="post" action="" autocomplete="off">
<input id="postcode" type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' required />
</form>

enable/disable submit button based in input field (filled/not filled)

what I am missing in this code, If I just want the input submit button to enable/disable/enable.. as long as I fill or unfill the input text?
sorry I am doing my best to learn javascript...can anyone help me fix this code?
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value=""/>
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>
<script>
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;
function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
</script>
This is the fiddle: https://jsfiddle.net/1zfm6uck/
Am I missing declaring onLoad mode or something like this?
Thanks!
Actually - if it wasn't a jsfiddle example your code would work great:
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;
function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
input[type='submit']:disabled{
color:red;
}
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value="" required="required" />
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>
The problem was the jsfiddle put your javascript code inside a clousure, so the checkFormsValidity function is not available in the scope of your input.
I added a required="required" to your input to make sure it's a required field (which will affect the checkValidity() of your form).
function checkFormsValidity(){
needs to be change to:
checkFormsValidity = function(){
Personally I wouldn't check validity that way, but in terms of making your code work without error, that will do it.
Edit: Also add required="required" to the input.

How to disable submit button until all text fields are full and file is selected

I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.
The distilled version of the code I'm working with is here:
HTML
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
JS
$('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
$('.submit').prop('disabled', false);
}
});
})()
Thanks for your help
https://jsfiddle.net/xG2KS/482/
Try capture the event on those field and checking the empty values by using another function, see below code :
$(':input').on('change keyup', function () {
// call the function after
// both change and keyup event trigger
var k = checking();
// if value inc not 0
if (k) $('.submit').prop('disabled', true);
// if value inc is 0
else $('.submit').prop('disabled', false);
});
// this function check for empty values
function checking() {
var inc = 0;
// capture all input except submit button
$(':input:not(:submit)').each(function () {
if ($(this).val() == "") inc++;
});
return inc;
}
This is just an example, but the logic somehow like that.
Update :
Event Delegation. You might need read this
// document -> can be replaced with nearest parent/container
// which is already exist on the page,
// something that hold dynamic data(in your case form input)
$(document).on('change keyup',':input', function (){..});
DEMO
Please see this fiddle https://jsfiddle.net/xG2KS/482/
$('input').on('change',function(){
var empty = $('div').find("input").filter(function() {
return this.value === "";
});
if(empty.length>0) {
$('.submit').prop('disabled', true);
}
else{
$('.submit').prop('disabled', false);
}
});
[1]:
The trick is
don’t disable the submit button; otherwise the user can’t click on it and testing won’t work
only when processing, only return true if all tests are satisfied
Here is a modified version of the HTML:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file"><br>
<input type="text" name="name"><br>
<input type="text" name="email"><br>
<button name="submit" type="submit">Upload</button>
</form>
and some pure JavaScript:
window.onload=init;
function init() {
var form=document.getElementById('test');
form.onsubmit=testSubmit;
function testSubmit() {
if(!form['file'].value) return false;
if(!form['name'].value) return false;
if(!form['email'].value) return false;
}
}
Note that I have removed all traces of XHTML in the HTML. That’s not necessary, of course, but HTML5 does allow a simpler version of the above, without JavaScript. Simply use the required attribute:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file" required><br>
<input type="text" name="name" required><br>
<input type="text" name="email" required><br>
<button name="submit" type="submit">Upload</button>
</form>
This prevents form submission if a required field is empty and works for all modern (not IE8) browsers.
Listen for the input event on file and text input elements, count number of unfilled inputs and, set the submit button's disabled property based on that number. Check out the demo below.
$(':text,:file').on('input', function() {
//find number of unfilled inputs
var n = $(':text,:file').filter(function() {
return this.value.trim().length == 0;
}).length;
//set disabled property of submit based on number
$('#submit').prop('disabled', n != 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
For my approach, I'd rather use array to store if all the conditions are true. Then use every to make sure that all is true
$(function(){
function validateSubmit()
{
var result = [];
$('input[type=file], input[type=text]').each(function(){
if ($(this).val() == "")
result.push(false);
else
result.push(true);
});
return result;
}
$('input[type=file], input[type=text]').bind('change keyup', function(){
var res = validateSubmit().every(function(elem){
return elem == true;
});
if (res)
$('input[type=submit]').attr('disabled', false);
else
$('input[type=submit]').attr('disabled', true);
});
});
Fiddle

javascript function in html form

I have seen some other threads like this but they don't seem to help me in my problem. I am new to Javascript and I am struggling to understand which value in the email input has to be called in my javascript function to make it work.
<input type="email" name="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
The function I am using is this:
function check_v_mail('myEmail') {
fld_value = document.getElementById(field).value;
is_m_valid = 0;
if (fld_value.indexOf('#') >= 1) {
m_valid_dom = fld_value.substr(fld_value.indexOf('#')+1);
if (m_valid_dom.indexOf('#') == -1) {
if (m_valid_dom.indexOf('.') >= 1) {
m_valid_dom_e = m_valid_dom.substr(m_valid_dom.indexOf('.')+1);
if (m_valid_dom_e.length >= 1) {
is_m_valid = 1;
}
}
}
}
if (is_m_valid) {
update_css_class(field, 2);
m_valid_r = 1;
} else {
update_css_class(field, 1);
m_valid_r = 0;
}
return m_valid_r;
}
This function is saved as email_script.js and is called in my footer as follows:
<script src="includes/js/email_script.js"></script>
What am I doing wrong?
You need to call the check_v_mail function. Usually, this is done when the user clicks the button to submit the form.
<form name="myForm" onsubmit="return check_v_mail('myEmail')" method="post">
Email: <input type="email" name="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
<input type="submit" value="Submit">
</form>
You can add it in form's onsubmit
In addition to calling the function on form submit or field exit, you also need to add id attribute to your element because your function uses getElementById() to get the element but your input element doesn't have id attribute
<input type="email" name="myEmail" id ="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
To expand on a comment by Mani:
Right now the signature of your function check_v_mail is incorrect, it is written like a call to a function.
Signature in email_script.js could be:
function check_v_mail(emailFieldId) {
fld_value = document.getElementById(emailFieldId).value;
return m_valid_r;
}
Calling on the form could be:
<form onsubmit="return check_v_mail('myEmail');" method="post"></form>
A slight tweak is to have a validate function or class that handles the validation. This can be expanded to call multiple different validation methods and decreases the likelihood that the onsubmit will become complex with additional validations.
<form onsubmit="return validateForm();" method="post"></form>
function validateForm() {
var emailValid = check_v_mail('myEmail')
var firstNameValid = validateFirstName('firstNameInput');
return emailValid && firstNameValid;
}

Categories

Resources