How to refresh the form value using JQuery - javascript

I have a html form. I want to take the input value (a url), extract a number from the url using regex ( '/[0-9]{5,}/') , and then refresh the form value with the number extracted and appended to another url. If I can't find a number - I just want an error to appear in the form box. All using Jquery to avoid page reload.
This is the existing form
<form id = "submit" method="post">
<label for="link_website_url">Create a short url</label>
<input id="link_website_url" name="link" size="30" type="text" />
<input class="go" name="commit" type="submit" value="Go!" /></form>

$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
return false; //error, so cancel this submit
}
});
If you perform additional validation, cancel the submit even if an individual check passes, clear error messages per check that validates (e.g. $('#error_link_web_url').remove();) and submit after all checks pass:
var checkFailed = false;
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
$('#error_link_web_url').remove();
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
checkFailed = true;
}
/*Other checks...*/
if(checkFailed){
return false; //cancel submit
}
});

$('#submit').submit(function(){
var url = $('#link_website_url').value();
var val = <do your processing here>;
$('#link_website_url').value(val);
return false;
});

Related

JavaScript HTML validation function only works when the form elements are all filled

I'm making sign in form with submit. What I want to do is to alert when there is blank in the form. But the function only works when all of the form are filled. Here's the HTML and JS code. The result is the same using onsubmit inside of the HTML or addEventListener("submit" function name)
HTML : It's basically a form for sign in / ordering.
<form id="registration" method="POST" onsubmit="return validate();" action="phplink">
<p> <label for="custName">Name : </label>
<input type="text" id="cname" name="cname" required="required" /> </p>
</form>
JS :
function validate(event) {
event.preventDefault();
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}
The validation constrains, such as your required="required" are validated before your browser will trigger a submit event. If the validation fails (a value to a required field is not provided) it will not submit your form.
If you want to do the validation using JavaScript instead of the validation constraint attributes, you either need to remove the required="required" attribute (together with any other similar attributes) or you can add the novalidate attribute to your form to indicate that it should not perform this validation on submit.
If you use the latter, you can still use formElement.reportValidity() to see if all the elements satisfy their validation constraints.
If you add a required attribute to each field that shouldn’t be blank, it’ll prevent form submission with empty fields, like this...
<input type="text" name="username" required>
Hi you have several problem. on submit must pass event => onsubmit="return validate(event);" .
you must first defined result and thats your flag => var result = false .
if you want show alert then input dont need required attribute.
so this is your Fixed Code;
function validate(event) {
event.preventDefault();
var result = true;
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}

Jquery min and max show new page

I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)

Add suffix to form field

I have some (more than thousand) users that insist on logging in just with their names, but a system that insists on having the full e-mail address (name + #my-mail.com) provided. Which is a smart solution to add a suffix to a field without bothering the user?
The Form:
<form id="login_form" action="processing.php" method="post" class="form">
<fieldset>
<ul class="input_block">
<li>
<input type="text" name="email" id="email" value="" />
</li>
<li>
<input type="password" name="passwort" id="password" />
</li>
</ul>
</fieldset>
I played around with the key up function for the field, but it didn't help much.
<script>
$('#email').keyup(function(e){
if(this.value.length > 12){
this.value = this.value + '#my-mail.com';
if( this.value.indexOf('#my-mail.com') <= 0 ){
this.value = String.fromCharCode(e.which) + '#my-mail.com';
}
});
</script>
I consider a solution that manipulates the field just right before the submission much more "proper" (sadly I don't have access to the PHP file that is receiving the submission). So I tried as well with the submit function, this didn't work either.
<script>
$( "#login_form" ).submit(function( event ) {
("#email").value = ("#email").value + '#my-mail.com';
});
</script>
Anybody some advise on how to solve it using the submit function or another idea that seems to be better?
$('#email').change(function() {
var val = $(this).val();
if(val.indexOf('#my-mail.com') == -1)
$(this).val(val+'#my-mail.com');
});
http://jsfiddle.net/g4oLtfw7/
This will add the '#my-mail.com' suffix if it's not already part of the input value. If you want to allow other types of emails, but default to 'my-mail.com' otherwise, try this:
$('#email').change(function() {
var val = $(this).val();
if(val.indexOf('#') == -1)
$(this).val(val+'#my-mail.com');
});
Either:
$('#login_form').submit(function (e) {
var email = $('#email'),
user = email.val().split('#')[0],
domain = '#my-mail.com';
if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
email.val(user + domain);
}
});
or
$('#email').change(function (e) {
var email = $(this),
user = email.val().split('#')[0],
domain = '#my-mail.com';
if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
email.val(user + domain);
}
});
is how I would approach this (obligatory fiddle: http://jsfiddle.net/e84v7nat/).
This approach ensures that your user has a domain specified and that the domain is correct. If the username is case-sensitive, remove the calls to .toLowerCase.

How to add a validation error message next to a field using jQuery

Hi have a form with a few fields. Amongst them:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p> tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.
Use .after().
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p tag too, so you can remove them when the number is edited to be correct.
Try:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
Its best to use jqueryvalidation plugin.
But in some scenario may be you need to show validation message using custom code, then below may help.
Code
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});

Form validation is interrupted when one check is invalid in javascript

I've got a form which contains two textarea, each concerning a group of mails.
<form name="myform" action='entryupdate.php' method="post">
<textarea name="mailgroup1" rows="2" cols="50" onchange="checkFormValue();">
</textarea>
<textarea name="mailgroup2" rows="2" cols="50" onchange="checkFormValue();">
</textarea>
<input name="update" type="submit" value="Update description"/>
</form>
And I've got a function to check if an email is well formated, after our internal norms.
function checkmail(component){
var emailpattern = /^[A-z0-9\._-]+#[A-z0-9][A-z0-9-]*(\.[A-z0-9_-]+)*\.([A-z]{2,6})$/;
var mails = component.value.split(/[\n\r\t ]+/);
var valid = true;
for(var i=0; i<mails.length; i++){
valid = valid && emailpattern.test(mails[i]);
alert("Mail: "+mails[i]+" Valid: "+ emailpattern.test(mails[i]));
}
if(valid){
component.setAttribute('class', 'valid');
}else{
component.setAttribute('class', 'invalid');
}
return valid;
}
If a field has is class set to invalid, the following style is applied:
.invalid
{
background-color:#fffacd;
}
When a value is changed in one of the textarea, the following function is called, which check if any of the value is not correctly formated, and if it is the case, the submit button is disabled.
function checkFormValue(){
var validform = true;
validform = validform && checkmail(document.myform.mailgroup1) && checkmail(document.myform.mailgroup2);
document.hotfixomat.update.disabled = !validform;
}
The problem is, if the first check return false, then the second check is not made, and if it happens that the value is not correctly formatted, then the change is style is not done. (but the submit button is disabled). Why are the checks interrupted?
This reason for this is how you get your validform variable in the last bit. JavaScript works like many other languages and will not go any further in a boolean AND if it can't possibly be true:
var validform = true;
validform = validform && checkmail(document.myform.mailgroup1) && checkmail(document.myform.mailgroup2);
If the first checkmail() is false, then it doesn't have to perform the second one since there is no possible way that validform will be true. If you set var validform = false then it won't even do any of the checkmail functions.
An example: http://jsfiddle.net/jonathon/Ndw9K/
If you want to ensure that both are called then you can split it up and do something like this:
var validForm1 = checkmail(document.myform.mailgroup1),
validForm2 = checkmail(document.myform.mailgroup2),
validForm = validForm1 && validForm2;
Alternatively, you could change your method so that it goes through all the elements you want to validate and it changes a variable and returns that.
A basic example:
function checkmailElements(myarray){
var returnVal = true;
for(var i = 0; i< myarray.length; i++){
if( !checkmail(myarray[i]) ){
returnVal = false;
}
}
returnVal;
}

Categories

Resources