I have file .js in this link: C:\xampp\htdocs\ab-group\assets\js\default.js
I've made a form and I wanna validate it. I also already linked the js file in HTML head but it doesn't work.
I use a same way in calling css file and it succeeded, but why I can't call js file?
here my view code:
<head>
<title>Welcome to AB Group</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href="<?php echo base_url('assets/css/default.css')?>"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="<?php echo base_url(). "assets/js/default.js" ?>"></script>
</head>
<body>
<div class="form-style-3">
<form id="form_sendEmail" name="form_sendEmail" method="post" onsubmit="validate();">
<fieldset><legend>Personal</legend>
<label for="field1"><span>Name <span class="required">*</span></span><input type="text" class="input-field" name="name" id="name" value="" /></label>
<label for="field2"><span>Email <span class="required">*</span></span><input type="email" class="input-field" name="email" id="email" value="" /></label>
<label for="field3"><span>Phone <span class="required">*</span></span><input type="text" class="input-field" name="phone" id="phone" value="" /></label>
<label for="field4"><span>Subject</span><select name="field4" class="select-field">
<option value="Information">Information</option>
<option value="Complain">Complain</option>
<option value="Other">Other</option>
</select></label>
<label for="field5"><span>Shipment Code <span class="optional"></span></span><input type="text" class="input-field" name="field5" value="" /></label>
</fieldset>
<fieldset><legend>Message</legend>
<label for="field6"><span>Message <span class="required">*</span></span><textarea name="message" id="message" class="textarea-field"></textarea></label>
<label><span> </span><input type="submit" onclick="validate()" id="sendEmail" value="Send Email" /></label>
<span class="required">* Indicates Required Field</span>
</fieldset>
</form>
</div>
</body>
and here my js file:
$(document).submit(function () {
function validate()
{
var emailID = document.form_sendEmail.Email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if( document.form_sendEmail.Name.value == "" )
{
alert( "Please provide your name!" );
document.form_sendEmail.Name.focus() ;
return false;
}
if( document.form_sendEmail.Email.value == "" )
{
alert( "Please provide your Email!" );
document.form_sendEmail.Email.focus() ;
return false;
}else if(atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.form_sendEmail.EMail.focus() ;
return false;
}
if( document.form_sendEmail.Phone.value == "" )
{
alert( "Please provide your phone number!" );
document.form_sendEmail.Phone.focus() ;
return false;
}
if( document.form_sendEmail.Message.value == "" )
{
alert( "Please write your message!" );
document.form_sendEmail.Message.focus() ;
return false;
}else{
return( true );
}
}
});
I hope js file could validate the form is empty or not and validate email as well. Please help to find a mistake in my code. Thank you very much.
Problem might be at linking js file. So try this.
<script src="<?php echo base_url(); ?> assets/js/default.js"></script>
I change $(document).submit(function ()... to become $(document).ready(function()... and then (somehow) it works.
Related
Here I'm trying to execute the following code but it throws the above error in console log in website page, I am unable to identify the error .
I have coded this webpage in such a way that it should show an error like "enter the user name" and "enter the password" whenever the input boxes are left empty but instead of this it is showing an uncaught type error. Kindly help me to find the solution.
my github code link is:https://github.com/harish-123445/login-form-using-html-css-javascript
function vfun(){
var uname=document.forms["myform"]["uname"].value;
var pword=document.forms["myform"]["pword"].value;
if(uname==null || uname=="" ){
document.getElementById("errorBox").innerHTML =
"enter the user name";
return false;
}
if(pword==null || pword==""){
document.getElementById("errorBox").innerHTML =
"enter the password";
return false;
}
if (uname != '' && pword != '' ){
alert("Login successfully");
}
}
<!DOCTYPE html>
<html >
<head>
<title>sign in form</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="js.js"></script>
<body>
<div class="box">
<img src="user.png" class="user">
<h1 >LOGIN HERE</h1>
<form class="myform" onsubmit= "return vfun()">
<p>USERNAME </p>
<input type="text" name="uname" placeholder="enter username" >
<p>PASSWORD </p>
<input type="password" name="pword" placeholder="enter password">
<div id="errorBox"></div>
<input type="submit" name="" value="login">
<br><br>
<a href="register.html" >Register for new user</a>
</form>
</div>
</body>
</head>
</html>
I have edited your code. I have called your username and password using getElementById and your two error boxes with different id names and now it is working fine.
function vfun(){
var uname=document.getElementById("name").value;
var psword=document.getElementById("passw").value;
if(uname==null || uname=="" ){
document.getElementById("errorBox2").innerHTML =
"enter the user name";
return false;
}
if(psword==null || psword==""){
document.getElementById("errorBox").innerHTML =
"enter the password";
return false;
}
if (uname != '' && pword != '' ){
alert("Login successfully");
}
}
<!DOCTYPE html>
<html >
<head>
<title>sign in form</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="js.js"></script>
<body>
<div class="box">
<img src="user.png" class="user">
<h1 >LOGIN HERE</h1>
<form class="myform" onsubmit= "return vfun()">
<p>USERNAME </p>
<input type="text" name="uname" id="name"
placeholder="enter username" >
<div id="errorBox2"></div>
<p>PASSWORD </p>
<input type="password" name="pword" id="passw"
placeholder="enter password">
<div id="errorBox"></div>
<input type="submit" name="" value="login">
<br><br>
<a href="register.html" >Register for new user</a>
</form>
</div>
</body>
</head>
</html>
This is my first ever try on Ajax, what this code is doing is that when a user types a username, ajax should get triggered and tell the user whether the username is available of not. But ajax file is not doing what it is suppose to do in other words the function is not getting triggered. any idea why?
I have taken this example from a book.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<!-- Bootstrap Core CSS -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="bootstrap/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- Ajax -->
<script src="ajax.js" type="text/javascript" language="javascript"></script>
<!-- Ajax -->
<script src="checkusername.js" type="text/javascript" language="javascript"></script>
</head>
<body>
<div class="form-group">
<form action="checkusername.php">
<fieldset>
<legend>Registration Form</legend>
<p>
Username: <br> <input name="username" onchange="check_username(this.form.username.value)" type="text" class="form-control" placeholder="Username" maxlength="20" style="width:200px; display: inline;">
<span id="username_label"></span>
</p>
<p>
Password: <input type="password" class="form-control" placeholder="Password" maxlength="20" style="width:200px;">
</p>
<p>
Confirm Password: <input type="text" class="form-control" placeholder="Confirm Password" maxlength="20" style="width:200px;">
</p>
<p>
First Name: <input type="text" class="form-control" placeholder="First Name" maxlength="20" style="width:200px;">
</p>
<p>
Last Name: <input type="text" class="form-control" placeholder="Last Name" maxlength="20" style="width:200px;">
</p>
<p>
Email: <input type="email" class="form-control" placeholder="Email" maxlength="20" style="width:200px;">
</p>
<button type="submit" name="submit" class="btn" >Register</button>
</fieldset>
</form>
</div>
</body>
</html>
ajax.js
var ajax = false;
if( window.XMLHttpRequest ){
ajax = new XMLHttpRequest();
} else {
// code for IE6, IE5
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
if ( !ajax ) {
alert('functionality is not avaible');
}
checkusername.js
function check_username( username ){
if( ajax ){
ajax.onreadystatechange = handle_check;
ajax.open( 'GET', 'checkusername.php?username=' + encodeURIComponent(username), true);
ajax.send(null);
}
else{
document.getElementById( 'username_label' ).innerHTML = 'The availablity of this username will be check upon form submission';
}
}
function handle_check(){
if ( ajax.readyState == 4 && ajax.status == 200 ) {
document.getElementById( 'username_label' ).innerHTML = ajax.responseText;
}
}
checkusername.PHP
<?php
if (isset($_GET['username'])) {
$dbc = #mysqli_connect('localhost','root','','testdb') OR die ( 'Cannot connect.' );
$que = sprintf("SELECT ID FROM maintable WHERE name='%s'", mysqli_real_escape_string( $dbc, trim( $_GET['username'] ) ));
$runque = mysqli_query( $dbc, $que );
if (mysqli_num_rows( $runque ) == 1) {
echo "The Username is unavaiable!";
}
else{
echo "The Username is avaiable!";
}
mysqli_close( $dbc );
}
else{
echo "Please Enter username";
}
?>
I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}
This is my first time with javascript. I'm making a basic login page where there is a control for the email input. I would like to put an error message of some kind when someone gives an email address with illegal symbol. Here my code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var result = email.search("/[^(a-z | A-Z | 0-9 | #)]/");
if(result !== -1)
{
emailObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
</html>
I have a function I use to validate email addresses, it uses regex. I would suggest jQuery just to show/hide the error message.
function validEmail(val){
if(val.length < 6 || val.length > 255) return false;
return new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/).test(val);
}
$(function(){
$("#email").on("change", function(){
var email = $("#email").val();
if(!validEmail(email)){
$("#emailError").show();
} else {
$("#emailError").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- Some Inputs here -->
<span id='emailError' style='display: none;'>Please enter a valid email address</span><br>
<input type='email' id='email' name='email' placeholder='Email Address' />
<!-- More Inputs here -->
<button type='submit'>Submit</button>
</form>
you're trying to append something to an input element (email input, in this case). I'd suggest to append it to your main div, which in this case I have identified as "YOUR_ID".
Also, I suggest you a more efficint way to check a valid email.
follow the below example
<body>
<div id="YOUR_ID">
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var divObject = document.getElementById("YOUR_ID");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var check = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var result = check.test(email);
if(result !== -1)
{
divObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
After my form is submitted, I'd like to reset my form to display the original blank values. Here's the code:
PHP Form
<form action="index.php" method="post" id="contact_form" >
<div id="topic_error" class="error"><img src="images/error.png" /> What category should this be filed in?</div>
<div>
<select name="topic" id="topic">
<option value="">Please select a topic...</option>
<option value=" Computer Repair ">Computer Repair</option>
<option value=" Website Design ">Website Design</option>
<option value=" Say Hi ">Just Want to Say Hi</option>
</select>
</div>
<h4>NAME:</h4><div id="name_error" class="error"><img src="iamges/error.png" /> Please enter your name</div>
<div><input class="contact_name" type="text" name="name" id="name" placeholder="Enter Name" /></div>
<H4>EMAIL:</H4><div id="email_error" class="error"><img src="images/error.png" /> Please enter your email</div>
<div><input class="contact_email" type="text" name="email" id="email" placeholder="you#mail.com" /></div>
<h4>SUBJECT:</h4><div id="subject_error" class="error"><img src="images/error.png" /> Please enter a subject</div>
<div><input class="contact_subject" type="text" name="subject" id="subject" placeholder="How did you become so awesome?" /></div>
<h4>MESSAGE:</h4><div id="message_error" class="error"><img src="images/error.png" /> Please give us a few more details</div>
<div><textarea class="contact_message" name="message" id="message" placeholder="Give us some details"></textarea></div>
<div id="mail_success" class="success"><img src="images/success.png" /> Thank you. The mailman is on his way.</div>
<div id="mail_fail" class="error"><img src="images/error.png" /> Sorry, we don't know what happened. Please try again later.</div>
<div id="cf_submit_p">
<input class="submit" type="submit" id="send_message" value="">
</div>
</form>
The contact.js file
$(document).ready(function(){
$('#send_message').click(function(e){
e.preventDefault();
var error = false;
var topic = $('#topic').val();
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
if(topic.length == 0){
var error = true;
$('#topic_error').fadeIn(500);
} else {
$('#topic_error').fadeOut(500);
}
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
} else {
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
} else {
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
} else {
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
} else {
$('#message_error').fadeOut(500);
} if(error == false){
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
$.post("send_email.php", $("#contact_form").serialize(),function(result){
if(result == 'sent'){
$('#cf_submit_p').remove();
$('#mail_success').fadeIn(500);
} else {
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Send Message');
}
});
}
});
});
I don't think the send_email.php file is needed, but I can put that up here if need be. I would assume (I know what happens when you assume) that this can be done with some sort of trigger in the javascript. I did try to add the line form.trigger('reset'); after the $('#mail_success').fadeIn(500); line but that did not work
It would be $("#contact_form").trigger("reset"), and $("#contact_form")[0].reset() should also work.
$('#contact_form').trigger('reset') should work.