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;
}
Related
I am trying to run a form validation on an HTML form with pureJS.
Here is my code:
<form name="myForm" action="" onsubmit="alert('hello world');return validateForm(myForm);">
<label>
<input name="username" placeholder="Name" type="text" required>
</label>
<label>
<input name="email" placeholder="Email" type="email" required>
</label>
<input type="submit" value="Submit 1">
<button type="submit">Submit 2</button>
<button>Submit 3</button>
function validateForm(formName) {
const form = document.forms[formName];
for(let i = 0; i < form.elements.length; i++){
const element = form.elements[i];
// validation fails if element is required and blank
if(element.attributes["required"] && !element.value.length){
element.focus();
return false;
}
// validation fails if email is not valid
if(element.getAttribute('type') === "email" && !validateEmail(element.value)) {
element.focus();
return false;
}
};
return true;
}
function validateEmail(str) {
var regexp = /[a-z0-9!#$%&'*+/=?^_`{|}~.-]+#[a-z0-9-]+(\.[a-z0-9-]+)*/;
return regexp.test(str);
}
new link without typo: http://jsfiddle.net/mech8bon/
http://jsfiddle.net/4bjmh9as/
Expected: to call the alert then the function.
Result: nothing called at all.
Open the developer tools in your browser. Look at the console. Read the error message.
Uncaught TypeError: Cannot read property 'elements' of undefined
You are passing the variable myForm:
validateForm(myForm);
But then you are treating it as a string containing a property name:
const form = document.forms[formName];
String literals need quotes around them:
validateForm('myForm');
The solution thanks to Ric and Quentin in this fiddle:
http://jsfiddle.net/eg89b02j/2/
<form name="myForm" action="" onsubmit="return validateForm(this);" novalidate>
The first fix was adding novalidate attribute to the form tag.
The second fix was making the form more generic by sending the form itself instead of name.
I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})
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.
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;
}
}
I have a form that I am trying to pass a JavaScript variable into. The custom hidden field works, but nothing gets passed into it... is there something wrong with the onsubmit code?
Embedded form code:
<input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email" required>
<input type="hidden" name="REFERID" id="MERGE1" value="">
Here is the JS Code later in the page:
<script type="text/javascript">
function addref() {
var urlref = (document.url);
var refcode = urlref.substring(urlref.indexOf "ref" +4 != urlref.length);
document.mc-embedded-subscribe-form.MERGE1.value = refcode;
}
</script>
Try to use:
document.getElementById("MERGE1").value = refcode;