passing a simple variable in javascript (form) - javascript

I am an inexperienced web developer writing a registration form using JS for client-side validation and PHP for server-side. I am stuck trying to just test a variable and make sure that it is getting passed to JS. I heard that jsfiddle doesn't like forms, so I restructured my fiddle code to not include any form tags. The code does not do anything when I run it. Can someone help please? Also, should I install Apache to test the form locally or would Chrome be able to handle it? I know that I'll have to eventually to test PHP, but I'm just trying to get JS validation to work right now.
http://jsfiddle.net/5JT94/
HTML:
<p>Zip Code: <input type="text" name="zipbox"></p>
<p><input type="submit" name="submit" onClick="formValidation()" value="Submit" /></p>
JS:
function formValidation()
{
var zip=document.getElementById("zipbox");
function allnumeric(zip)
{
var numbers = /^[0-9]+$/;
if(zip.value.match(numbers))
{
alert("Everything OK");
}
else
{
alert("Numbers only please");
}
};
};

You weren't executing the function on the zip that you found.
var zip=document.getElementById("zipbox");
allnumeric(zip);
http://jsfiddle.net/5JT94/1/

And in case you don't want to add an id (can't see why):
Demo: JSFiddle
HTML
<form name="zipform">
<p>Zip Code: <input type="text" name="zipbox" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
JS
function formValidation() {
var zip=document.forms["zipform"].elements["zipbox"];
var numbers = /^[0-9]+$/;
if(zip.value.match(numbers)) {
alert("Everything OK");
} else {
alert("Numbers only please");
return false;
}
return true;
}
document.forms["zipform"].elements["submit"].onclick=formValidation;

One of the problems may relate to how jsfiddle works. I had to add "window.formValidation = formValidation" so that the formValidation function you defined in the onClick would be found. Second, you had an allnumeric function but it wasn't being called.
function formValidation()
{
var zip=document.getElementById("zipbox");
function allnumeric(zip)
{
var numbers = /^[0-9]+$/;
if(zip.value.match(numbers))
{
alert("Everything OK");
}
else
{
alert("Numbers only please");
}
};
allnumeric(zip);
};
window.formValidation = formValidation

your element does not have an id ? change like below
<input id="zipbox" type="text" name="zipbox">
then debug from there

Related

window.location.href does not work, it always returns an alert

I have been learning HTML/CSS/JS in my free time. I'm still a noobie and I have encountered this problem while practicing.
I want to create a form where you can type what are you searching for and sumbit button redriects you to google and If it's empty it shows an alert. But the redirect does not work, I always get an alert.
Can you guide me what Am I doing work ?
Sorry for my english, It isn't my native langue.
<form id="myform">
<input type="search" name="searchedValue">
<input type="submit" value="Szukaj">
</form>
<script>
$("document").ready(function() {
$("#myform").submit(function(e) {
var searchedValue = $("input[name='searchedValue']").attr("value");
if (searchedValue) {
window.location.href = "http://www.google.pl/#hl=plf&output=search&q="+searchedValue;
} else {
alert("empty string");
}
e.preventDefault();
});
});
</script>
var searchedValue = $("input[name='searchedValue']").val()
you should use val()
instead of attr(). Rest of the things are fine.
<form id="myform">
<input type="search" name="searchedValue">
<input type="submit" value="Szukaj" onclick="search(event)">
</form>
<script>
function search(event) {
// [0] gets the first textbox of current page with name.
var searchedValue = document.getElementsByName('searchedValue')[0].value;
if (searchedValue && event) {
event.preventDefault(); // cancels the event if it is cancelable
var specs = "height=auto,width=auto";
var searchUrl = "http://www.google.pl/#hl=plf&output=search&q=" + searchedValue;
window.open(searchUrl, "_blank", specs);
} else {
alert("empty string");
}
};
</script>
Useful links like window.open() and preventDefault(). I think it's better to practice with pure javascript and DOM manipulations when you are learning. Anyway, keep up the hard work. :)
Code is fine, i think your browser is blocking your redirect to
http://www.google.pl/#hl=plf&output=search&q="+searchedValue;
It may happen when you have https website and want to redirect to http.
Console will silently display error regarding insecure redirect.

Validate form's textarea - jQuery

I am trying to develope a plugin for an application that let the users invite their friends to use the application by just sending an email. Juts like Dropbox does to let the users invite friends and receive extra space.
I am trying to validate the only field I have in the form (textarea) with JQuery (I am new to JQuery) before submiting it and be handled by php.
This textarea will contain email addresses, separated by commas if more than one. Not even sure if textarea is the best to use for what I am trying to accomplish. Anyway here is my form code:
<form id="colleagues" action="email-sent.php" method="POST">
<input type="hidden" name="user" value="user" />
<textarea id="emails" name="emails" value="emails" placeholder="Example: john#mail.com, thiffany#mail.com, scott#mail.com..."></textarea>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
Here is what I tried in Jquery with no success:
//handle error
$(function() {
$("#error_message").hide();
var error_emails = false;
$("#emails").focusout(function() {
check_email();
});
function check_email() {
if(your_string.indexOf('#') != -1) {
$("#error_message").hide();
} else {
$("#error_message").html("Invalid email form.Example:john#mail.com, thiffany#mail.com, scott#mail.com...");
$("#error_message").show();
error_emails = true;
}
}
$("#colleagues").submit(function() {
error_message = false;
check_email();
if(error_message == false) {
return true;
} else {
return false;
}
});
I hope the question was clear enough, if you need more info please let me know.
Many thanks in advance for all your help and advises.
var array = str.split(/,\s*/);
array.every(function(){
if(!validateEmail(curr)){
// email is not valid!
return false;
}
})
// Code from the famous Email validation
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Few errors as I noted down:
The code snippet posted here has missing braces }); at the end.
Also, what is your_string variable in the function check_email.
Also, error_message is assigned false always so the submit method will return true always.
Fixing this issues should help you.
I would use, as I commented above, append() or prepend() and just add fields. As mentioned in another post, client side use jQuery validation, but you should for sure validate server-side using a loop and filter_var($email, FILTER_VALIDATE_EMAIL). Here is a really basic example of the prepend():
<form id="colleagues" action="" method="POST">
<input type="hidden" name="user" value="user" />
<input name="emails[]" id="starter" placeholder="Email address" />
<div id="addEmail">+</div>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
<script>
$(document).ready(function() {
$("#addEmail").click(function() {
$("#colleagues").prepend('<input name="emails[]" placeholder="Email address" />');
});
});
</script>
Hi please use below js code,
$('#emails').focusout(function(e) {
var email_list = $('#emails').val();
var email_list_array = new Array();
email_list_array = email_list.split(",");
var invalid_email_list=' ';
$.each(email_list_array, function( index, value ) {
if(!validEmail(value))
{
invalid_email_list=invalid_email_list+' '+value+',';
}
});
console.log(invalid_email_list+' is not correct format.');
alert(invalid_email_list+' is not correct format.');
})
function validEmail(v) {
var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return (v.match(r) == null) ? false : true;
}
If you need to check more REGEX just do it validEmail() function. I hope this will help to sort out.
thank you
Your code might look correct, but you are using bad technique. My advice is to use jquery validation plugin that would handle textarea validation.for you. Also notice. There might be many solutions for this problem, but you should stick with simple one. And the first problem i see stright away is: button tag doesnt have type attribute. You are changing #error_message html, not text. Etc...

How to correctly validate form with jQuery?

So I have this jQuery for my form:
frm.submit(function(event) {
validateForm();
if(validateForm()) {
$(this).submit();
} else {
event.preventDefault();
}
});
It does sort of work, but I get JS <error> (and it doesn't say anything else in the console about it), I think the reason is that the function has to go through the validation again? Kind of like a circular dependency.
Can you show me a better way to do the exact thing that I'm trying to achieve here please?
Validate and show errors if filled in the wrong way;
Submit the form if everything is ok
Something like this maybe?
HTML -
<input type="text" id="name" />
<input type="tel" id="phone" />
<button type="button" id="submit">Submit</button>
<div id="errors"></div>
JS -
const user = {}
$('#submit').click(function(){
// validating form
if(!$('#name').val()) {
$('#errors').text('invalid value in "name" field')
return;
}
if(!$('#phone').val()) {
$('#errors').text('invalid value in "phone" field')
return;
}
$('#errors').text('');
user.phone = $('#phone').val();
user.name = $('#name').val();
// form submission goes here
});
Logic -
Once a function returns, the execution of anything else after the return expression itself, is prevented.
If you don't return anything, the interpreter will continue to the next expression.
This gives you the option of manipulating elements and handle errors just before returning and stopping the function from continuing to run.
function validateForm(){
if (input.val().isok && select.val().ispresent){
form.submit();
}else{
show_errors();
}
}
why not that way?

onSubmit button won't load location

I switched from type=click to type=submit so that I can use the Enter key to login. The if/else statements for invalid username/password functions fine. But if I input the correct credentials it wont load the location(different HTML page.)
PS: I'm new to coding in general(only 3 weeks in) Try to explain it so a newbie would know.
Thanks in advance.
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
location="Random.html"
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
}
</script>
<form name=login onsubmit="check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
You need to use .href on location
location.href = "Random.html";
(Also, since you said you were new, be sure to keep your dev console (F12) open when writing JavaScript and testing - you'll catch a lot of errors very early on)
Two things:
1 - Proper way to simulate a clink on a link is to use change the href attribute of location, not location itself. The line below should work:
window.location.href = "Random.html";
2 - As you are redirecting to another page, you have to "suppress" (stop) the natural onsubmit event.
In other words, you have to return false on the onsubmit event, otherwise the redirection (to Random.html) won't have a chance to work because the submit event will kick in (and sedn the user to the action page of the form) before the redirection works.
So change <form name=login onsubmit="check_info()"> to:
<form name=login onsubmit="return check_info()">
And add a return false; to the end of check_info().
The full code should be as follows:
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
window.location.href = "Random.html"; // ------ CHANGED THIS LINE
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
return false; // ------------------------ ADDED THIS LINE
}
</script>
And the HTML (only the onsubmit changed):
<form name="login" onsubmit="return check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
JSFiddle demo here.
The new way of doing this - set a breakpoint at the line
if(username=="test") {
And step through it to find what the problem is.
The old school way of doing this (from back before we had Javascript debuggers) is to alert messages in each of those blocks, and figure out why you step into that block to begin with. It's a lot more cumbersome than the debugger, but sometimes you may need to resort to old school hacks.

JavaScript: Search string for expression and return error if not found

I have a form that should only allow e-mail addresses with a ".edu" domain, and I worked up some JavaScript to try to make that happen.
Form elements:
<input type="text" name="empEmail" id="empEmail" />
<input type="submit" name="submit" id="submit" value="submit" onClick = "error();" />
<span id="empEmailError"> </span>
JavaScript function:
//Check for non-university e-mail addresses
function error() {
var email = document.getElementById('empEmail').value;
var re = /\.edu$/;
if(!email.match(re))
{
document.getElementById('empEmailError').innerHTML = "University e-mail
address only.";
return false;
}
}
Here's the fiddle:
http://jsfiddle.net/4T5qV/
I can't get it to work. Not sure what it is I'm missing.
You have to use .test().
if(!re.test(email))
.test() returns whether the regex has matched or not.
Also, you have to use <wrap in head> option of fiddle
Demo
There was a problem where it wasnt finding the error function. It could be that it was putting the error function in a document.on('loaded') function or something like that in the jsFiddle.
So the solution is to add a function to the window, like so:
//Check for non-university e-mail addresses
window.validateEduAddress = function() {
var email = document.getElementById('empEmail').value;
var re = /\.edu$/;
if(!email.match(re)) {
document.getElementById('empEmailError').innerHTML = "University e-mail address only.";
return false;
} else {
console.log('woohoo');
}
}
Then in your html you need to tell the onclick to use that function like so:
<input type="submit" name="submit" value="submit" id="submit" onclick="validateEduAddress();" />
And just to make it easier, heres the updated jsFiddle
In general you should also try to avoid naming functions so generically, so instead of error or fail you should try to describe the event or functionality :)
As others have noted, the cause of this issue is that you have the onLoad option selected in jsfiddle, and the result is that your inline onclick handler cannot find your error function. This is partly the fault of using inline event handlers (putting the JavaScript directly in an attribute), which is not a recommended practice.
Another problem is that you have a line break right in the middle of one of your string values, and this is causing a syntax error and preventing the code from running at all.
You should use the "no wrap in <head>" option, and unobtrusive JavaScript.
Remove the onclick attribute from your element:
<input type="submit" name="submit" id="submit" value="submit" />
And use this:
function validate(e) {
var email = document.getElementById('empEmail').value,
re = /\.edu$/;
if (re.test(email)) {
document.getElementById('empEmailError').innerHTML =
"University e-mail address only.";
return false;
}
return true;
}
window.onload = function () {
var form = document.getElementById('submit').onclick = validate;
};
(I've used re.test() here as Amit suggests, because that does make more sense semantically in this case.)
http://jsfiddle.net/4T5qV/6/

Categories

Resources