I was trying to send a form data to php code some how when I have condition of if the button was submit do the following code it doesn't work :
$("button#send").click(function() {
var error = '';
var send = $("#send").val() = true;
if ($('#username').val().length == 0) { error += 'user name<br />'; }
if ($('#password').val().length == 0) { error += 'password<br />'; }
if ($('#repassword').val().length == 0) { error += 'repassword<br />'; }
if ($('#password').val() != $('#repassword').val()) { error += 'pass match<br />'; }
var phonenum = $('#phonenum').val() + $('#select').val();
if (phonenum.length == 0) { error += 'phone num <br />'; } else if ($.isNumeric(phonenum) == false || phonenum.length != 10) { error += 'phoneworng<br />'; }
if (error != '') {
$('#result').html(error);
} else {
$.ajax({
url: $("#form_reg").attr('action'),
data: $("#form_reg input").serializeArray(),
type: 'POST',
success: function(result) {
$("#result").html(result);
},
error: function(error) {
alert(error);
}
});
}
$("#form_reg").submit(function(e) {
e.preventdefault;
return false;
});
});
here the html code
<form id="form_reg" action="AddUser.php" method="post">
<div class="head_div"> <span> reg </span> </div>
<div id="main_reg">
<div class="login_line">
<label for="username">username</label>
<input type="text" name="username" id="username" placeholder="username" />
</div>
<div class="login_line">
<label for="password"> passs </label>
<input type="password" name="password" id="password" placeholder="pass" />
</div>
<div class="login_line">
<label for="repassword"> repass </label>
<input type="password" name="repassword" id="repassword" placeholder="repass" />
</div>
<div class="login_line">
<label for="email"> email </label>
<input type="email" name="email" id="email" placeholder="email" />
</div>
<div class="login_line">
<label for="phonenum"> phone num</label>
</div>
<div class="login_line">
<input type="text" id="phonenum" name="phonenum" placeholder="phone num" />
<select id="select">
<option value="050"> 050</option>
<option value="054"> 054</option>
<option value="052"> 052</option>
<option value="053"> 053</option>
<option value="058"> 058</option>
</select>
</div>
</div>
<div class="login_line">
<div id="result"> </div>
</div>
<div class="send_line">
<button type="submit" name="send" id="send"> reg</button>
</div>
</form>
here the php
include_once 'login_db.php';
$error_msg="";
if(isset($_POST['send']))
{
And the rest there include the echo somehow without the if isset($_POST['send'])
the code is echo the result
Related
So I got a form that gets the student basic information for temporary admission, so I have a function that when register/submit button is clicked it checks if the Or number is already exist in database when it does it displays error message and the inputted data stays in their own fields.
the function works but when a user inputted a name for example "james joseph" and or number exist in database it will retain the name "james" only.
is there a way that it retains both?
Here's my code for the form
<form class="form-group" method="post" action="index.php">
<div class="row"><!--Top row-->
<div class="col-lg-5"><p><h3>Register an Enrollee</h3></p></div>
<div class="col-lg-3"></div>
<div class="col-lg-4">
</div>
</div>
<br>
<br>
<div class="row">
<div class="col-lg-4">
<label>Academic Year </label>
<?php
if (isset($_GET['academic'])) {
$academic=$_GET['academic'];
echo '<input type="text" name="academic" class="form-control" required value='.$academic.'>';
# code...
}
else
{
echo '<input type="text" name="academic" class="form-control" required>';
}
?>
</div>
<div class="col-lg-4">
<label for="year_level">Year Level</label>
<?php
if (isset($_GET['year'])) {
$year=$_GET['year'];
echo '<input type="text" name="year" class="form-control" required value='.$year.'>';
# code...
}
else
{
echo '<input type="text" name="year" class="form-control" required>';
}
?>
</div>
<div class="col-lg-4">
<label>OR Number</label>
<?php
if (isset($_GET['or'])) {
$or=$_GET['or'];
echo '<input type="text" name="or" class="form-control" required value='.$or.'>';
# code...
}
else
{
echo '<input type="text" name="or" class="form-control" required>';
}
?>
</div>
</div>
<br>
<div class="row">
<div class="col-lg-4">
<label>First Name</label>
<?php
if (isset($_GET['firstname'])) {
$firstname=$_GET['firstname'];
echo '<input type="text" name="firstname" class="form-control" required value='.$firstname.'>';
# code...
}
else
{
echo '<input type="firstname" name="firstname" class="form-control" required>';
}
?>
</div>
<div class="col-lg-4">
<label>Last Name</label>
<?php
if (isset($_GET['lastname'])) {
$lastname=$_GET['lastname'];
echo '<input type="text" name="lastname" class="form-control" required value='.$lastname.'>';
# code...
}
else
{
echo '<input type="text" name="lastname" class="form-control" required>';
}
?>
</div>
<div class="col-lg-4">
<label>Middle Initial</label>
<?php
if (isset($_GET['middle'])) {
$middle=$_GET['middle'];
echo '<input type="text" name="middle" class="form-control" required value='.$middle.'>';
# code...
}
else
{
echo '<input type="text" name="middle" class="form-control" required>';
}
?>
</div>
</div><!--End of Second row-->
<br>
<button class="btn btn-primary btn-block" type="submit" name="register">Register</button>
</form>
Here is the php code that checks and gets the inputted data from the form
if (isset($_POST['register'])) {
# code...
$year_level=$_POST['year'];
$academic_year=$_POST['academic'];
$or_number=$_POST['or'];
$stud_fname=$_POST['firstname'];
$stud_lname=$_POST['lastname'];
$stud_mi=$_POST['middle'];
$or_check_query="SELECT * FROM tbl_user WHERE or_number=$or_number";
$result=mysqli_query($conn,$or_check_query);
$or=mysqli_fetch_assoc($result);
if($or['or_number']===$or_number) {
header("Location: index.php?signup=failed&academic=$academic_year&year=$year_level&or=$or_number&firstname=$stud_fname&lastname=$stud_lname&middle=$stud_mi");
# code...
}
else {
$sql= "INSERT INTO tbl_user(or_number,academic,year,firstname,lastname,middle)
VALUES ('$or_number','$academic_year','$year_level','$stud_fname','$stud_lname','$stud_mi')";
mysqli_query($conn,$sql);
header("Location: index.php?signup=success");
}
}
When I click on update, a page is only getting refreshed, values are not updated. I have 4 tables in database, namely -> stud,country_master_academic,master_state, master_city. In a console, values are not showing when I click on update button.
my update.php page
<div class="container" style="width:700px;height:1100px;margin-top:10%;box-shadow:4px 3px 3px 3px grey;margin-left:25%;background-color:#eaf2fa;padding:3%;">
<h4 style="font-weight:bold;"><span class="glyphicon glyphicon-edit"></span>Update Student</h4>
<div class="form-group">
<label for="photo"></label>
<?php
$img = "images/".trim($vrow["photo"]);
echo '<img src='.$img.' id="resultedPhoto" class="image" style="margin-left:75%;margin-top:2%;width:120px;height:120px;border:2px solid #bbbbbb;border-radius:10px;">';
?><br/>
<input type="file" name="upphoto" id="upphoto" style="margin-left:70%;" required />
</div>
<form class="form-horizontal" name="form1" id="form1" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-lock"></span><b> Student No: </b></label>
<input type="text" class="form-control" name="upno" id="upno" disabled value="<?php echo $vrow['stud_no'];?>" required />
</div>
<div class="form-group">
<label for="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label>
<input type="text" class="form-control" name="upname" id="upname" value="<?php echo $vrow['stud_name'];?>" required pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters"/>
</div>
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-phone"></span><b> Mobile No: </b></label>
<input type="text" class="form-control" value="<?php echo $vrow['mobile']; ?>" name="upmob_no" required id="upmob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits"/>
</div>
<div class="form-group">
<label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label>
<input type="date" required class="form-control" value="<?php echo $vrow['dob'];?>" name="updob" id="updob" />
</div>
<div class="form-group">
<label for="add"><span class="glyphicon glyphicon-map-marker"></span><b> Address: </b></label>
<textarea rows="4" cols="33" class="form-control" name="upadd" id="upadd" required><?php echo $vrow['address'];?></textarea>
</div>
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="genderMale" value="M"<?php echo ($vrow['gender']=='M')?'checked':' ' ?> required="required">Male
<input type="radio" name="gender" id="genderFemale" value="F"<?php echo ($vrow['gender']=='F')?'checked':' ' ?> required="required">Female
</div>
<div class="form-group">
<label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label>
<select required name="upcountry" id="upcountry" class="form-control">
<option value="">Select</option>
<?php
$country="SELECT * from country_master_academic";
$res= $conn->query($country);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["country_name"]==$vcountry or $vrow['country'] == $row["country_code"] )
{
echo '<option value='.$row["country_code"].' selected>'.$row["country_name"].'</option>';
}
else
{
echo '<option value='.$row["country_code"].'>'.$row["country_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="state"><span class="glyphicon glyphicon-map-marker"></span><b> State: </b></label>
<select required name="upstate" id="upstate" class="form-control">
<option value="">Select</option>
<?php
$state="SELECT * from master_state";
$res= $conn->query($state);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["state_name"]==$vstate or $vrow['state'] == $row["state_code"] )
{
echo '<option value='.$row["state_code"].' selected>'.$row["state_name"].'</option>';
}
else
{
echo '<option value='.$row["state_code"].'>'.$row["state_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="city"><span class="glyphicon glyphicon-map-marker"></span><b> City: </b></label>
<select required name="upcity" id="upcity" class="form-control">
<option value="">Select</option>
<?php
$city="SELECT * from master_city";
$res= $conn->query($city);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["city_name"]==$vcity or $vrow['city'] == $row["city_code"] )
{
echo '<option value='.$row["city_code"].' selected>'.$row["city_name"].'</option>';
}
else
{
echo '<option value='.$row["city_code"].'>'.$row["city_name"].'</option>';
}
}
}
?>
</select>
</div>
<br/>
<div class="form-group">
<button type="submit" name="update" id="update" style="font-weight:bold;" class="btn btn-primary">Update</button>
</div>
</form>
</div>
upresult.php page
<?php
include("connection.php");
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
$qry="update stud set stud_name='".$name."',mobile='".$mob."',dob='".$dob."',address='".$add."',gender='".$gen."',country='".$cn."',state='".$st."',city='".$ct."' where stud_no='".$no."'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
?>
jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:{formData:formData},
async:true,
success:function(data) {
alert(data);
},
cache:false,
contentType:false,
processData:false
});
});
});
Thank you in advance.
Don't use the same name
data:{stud_no:stud_no}, //here change the name of vbl or value
data:{
formData:formData, //here change the name of vbl or value
stud_no:stud_no, //here change the name of vbl or value
}
I have create form and i am trying to store the data using Ajax.but data is not inserted to the database.what can be the error.user_id will be auto increment. and also i want to validate sitename.it should restrict inserting same sitenames.
Here is my code
Controller
public function user_add()
{
$data_save = array(
"Mnumber" => $this->input->post("Mnumber"),
"email" => $this->input->post("email"),
"fname" => $this->input->post("fname"),
"address" => $this->input->post("address"),
"sitename" => $this->input->post("sitename"),
"title" => $this->input->post("title"),
"descr" => $this->input->post("descr")
);
if ($this->user_mod->AddUser($data_save)) {
echo "Successfully Saved";
} else {
echo "error";
}
}
}
Model
class user_mod extends CI_Model
{
public function AddUser($data_save)
{
if ($this->db->insert('users', $data_save)) {
return true;
} else {
return false;
}
}
}
View
<script>
function save_user_new() {
var user_id = $('#user_id').val();
var Mnumber = $('#Mnumber').val();
var email = $('#email').val();
var fname = $('#fname').val();
var address = $('#address').val();
var sitename = $('#sitename').val();
var title = $('#title').val();
var descr = $('#descr').val();
if (sitename != "" && Mnumber != "") {
$.ajax({
type: "post",
async: false,
url: "<?php echo site_url('form_con/user_add'); ?>",
data: { "user_id": user_id,
"Mnumber": Mnumber,
"email": email,
"fname": fname,
"address": address,
"sitename": sitename,
"title": title,
"descr": descr,
},
dataType: "html",
success: function (data) {
if (data == 'error') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Something wrong.");
} else if (data == 'have') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : This Employee is already exists.");
} else {
$('#error_msg1').hide();
$('#success_msg').show();
$('#success_msg').html("Entitled leave successfully saved.");
$('#load_leave').html(data);
}
}
});
} else {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Please enter Employee Details.");
}
}
</script>
<form action="#">
<div class="form-body">
<div class="form-group">
<label class="control-label">Your First Name</label>
<input type="text" class="form-control" id="fname" name="fname" placeholder="Enter text">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label class="control-label">Your Mobile Number</label>
<input type="text" class="form-control" id="Mnumber" name="Mnumber" placeholder="Enter text">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Your Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter text">
</div>
<div class="form-group">
<label class="control-label">Your Site Name</label>
<input type="text" class="form-control" id="sitename" name="sitename" placeholder="Enter text">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Title of Your Web site</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Enter text">
</div>
<div class="form-group">
<label class="control-label">Description of Your Web Site</label>
<input type="text" class="form-control" id="descr" name="descr" placeholder="Enter text">
</div>
</div>
<div class="form-actions right">
<button type="submit" class="btn green" onclick="save_user_new()">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</form>
I've been building a site recently for a friend and I've gotten stuck on this one form. A button links to url in which this form is on and then once you fill out all the information and click submit, instead of returning you back to home.php it just removes the form from view and all you see is a blank new.php and it doesn't submit the information.
<?php
function renderForm($user, $rank, $position, $error)
{
?>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<center>
<form action="" method="post">
<div class="form-group">
<label for="username">Username*</label>
<input id="username" class="form-control" type="text" name="user" placeholder="Username" value="<?php echo $user; ?>" />
</div>
<div class="form-group">
<label for="rank">Rank</label>
<select class="form-control" name="rank">
<option value="1">Pending Rank</option>
<option value="2">PVT</option>
</select>
</div>
<div class="form-group">
<label for="position">Position</label>
<input id="position" class="form-control" type="text" name="position" placeholder="MOG/GG" value="<?php echo $position; ?>" />
</div>
<div class="form-group">
<label for="Date">Date*</label>
<input id="Date" class="form-control" type="text" name="date" placeholder="<?php echo date('d M y'); ?>" value="<?php echo $date; ?>" />
</div>
<div class="form-group">
<label for="Tag">Tag*</label>
<input id="Tag" class="form-control" type="text" name="tag" placeholder="[]" value="<?php echo $tag; ?>" />
</div>
<div class="form-group">
<label for="adt">ADT</label>
<input id="adt" class="form-control" type="text" name="adt" placeholder="{TEST}" value="<?php echo $adt; ?>" />
</div>
<div class="form-group">
<label for="exp">EXP</label>
<input id="exp" class="form-control" type="text" name="exp" placeholder="420" value="<?php echo $exp; ?>" />
</div>
<div class="form-group">
<label for="reg">Regiment</label>
<input id="reg" class="form-control" type="text" name="reg" placeholder="[P]" value="<?php echo $reg; ?>" />
</div>
<div class="form-group">
<label for="Notes">Notes</label>
<input id="Notes" class="form-control" type="text" name="notes" placeholder="Notes" value="<?php echo $notes; ?>" />
</div>
<button type="submit" name="submit" class="btn btn-default" value="Submit">Submit</button>
</form>
<script>
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
</script>
<?php
}
include('config/db.php');
if (isset($_POST['submit']))
{
$user = mysql_real_escape_string(htmlspecialchars($_POST['user']));
$rank = mysql_real_escape_string(htmlspecialchars($_POST['rank']));
$position = mysql_real_escape_string(htmlspecialchars($_POST['position']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$tag = mysql_real_escape_string(htmlspecialchars($_POST['tag']));
$adt = mysql_real_escape_string(htmlspecialchars($_POST['adt']));
$exp = mysql_real_escape_string(htmlspecialchars($_POST['exp']));
$reg = mysql_real_escape_string(htmlspecialchars($_POST['reg']));
$notes = mysql_real_escape_string(htmlspecialchars($_POST['notes']));
$datej = mysql_real_escape_string(htmlspecialchars($_POST['date']));
if ($user == '' || $rank == '' || $date == '' || $tag == '')
{
$error = '<center>ERROR: Please fill in all required fields!</center>';
#renderForm($user, $rank, $position, $error);
}
else
{
mysql_query("INSERT per SET user='$user', rank='$rank', position='$position', date='$date', tag='$tag', adt='$adt', exp='$exp', reg='$reg', notes='$notes', datej='$datej'", $db1)
or die(mysql_error());
include('logsadd.php');
write_mysql_log('has added member <font color="black"><b>'. $user .'</b></font>.', $db);
header("Location: home.php");
}
}
else
header("home.php");
{
#renderForm('','','');
}?>
Your else looks like this
else
header("home.php");
{
#renderForm('','','');
it should be
else
{
// header should be inside the else part
header("Location:home.php");
#renderForm('','','');
I have the following form that needs to feed into the database but I would like it to be validated before it can be saved into the database :
<form name="add_walkin_patient_form" class="add_walkin_patient_form" id="add_walkin_patient_form" autocomplete="off" >
<div class="form-line">
<div class="control-group">
<label class="control-label">
Patient Name
</label>
<div class="controls">
<input type="text" name="patientname" id="patientname" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Patient Phone Number
</label>
<div class="controls">
<input type="text" name="patient_phone" id="patient_phone" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Department
</label>
<div class="controls">
<select name="department" required="" class="department" id="department">
<option value="">Please select : </option>
<option value="Pharmacy">Pharmacy</option>
<option value="Laboratory">Laboratory</option>
<option value="Nurse">Nurse</option>
</select>
</div>
</div>
</div>
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
</form>
And the submit is done by a jquery script using the following script :
<script type="text/javascript">
$(document).ready(function () {
//delegated submit handlers for the forms inside the table
$('#add_walkin_patient_button').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url() ?>index.php/reception/add_walkin', $('#add_walkin_patient_form').serialize(), function () {
//success do something
// $.notify("New Patient Added Succesfully", "success",{ position:"left" });
$(".add_walkin_patient_form").notify(
"New Walkin Patient Added Successfully",
"success",
{position: "center"}
);
setInterval(function () {
var url = "<?php echo base_url() ?>index.php/reception/";
$(location).attr('href', url);
}, 3000);
}).fail(function () {
//error do something
$(".add_walkin_patient_form").notify(
"There was an error please try again later or contact the system support desk for assistance",
"error",
{position: "center"}
);
})
})
});
</script>
How can I put form validation to check if input is empty before submitting it into the script?
I am using javascript to do the validations.
Following is the form code:
<form action="upload.php" method="post" onSubmit="return validateForm()">
<input type="text" id="username">
<input type="text" password="password">
<input type="submit" value='Login' name='login'>
</form>
To perform validation write a javascript function:
<script>
function checkform(){
var uname= document.getElementById("username").value.trim().toUpperCase();
if(uname=== '' || uname=== null) {
alert("Username is blank");
document.getElementById("username").backgroundColor = "#ff6666";
return false;
}else document.getElementById("username").backgroundColor = "white";
var pass= document.getElementById("password").value.trim().toUpperCase();
if(pass=== '' || pass=== null) {
alert("Password is blank");
document.getElementById("password").backgroundColor = "#ff6666";
return false;
}else document.getElementById("password").backgroundColor = "white";
return true;
}
</script>
You are using,
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
Here, submit button is used for submitting a form and will never trigger click event. Because, submit will be triggered first thus causing the click event skip.
$('#add_walkin_patient_button').on('click', function (e) {
This would have worked if you have used normal button instead of submit button
<input type="button">Submit</button>
Now to the problem. There are two solution for it ,
If you use click event, then you should manually trigger submit on correct validation case,
<input type="button" id="add_walkin_patient_button">Submit</button>
//JS :
$("#add_walkin_patient_button").click(function() {
if(valid){
$("#form-id").submit();
}
Another option is to use submit event;which is triggered just after you click submit button. Here you need to either allow form submit or halt it based on your validation criteria,
$("#form-id").submit(function(){
if(invalid){
//Suppress form submit
return false;
}else{
return true;
}
});
P.S
And i would recommend you to use jQuery Validate as suggested by #sherin-mathew
make a javascript validation method (say, validateForm(), with bool return type). add [onsubmit="return validateForm()"] attribute to your form and you are done.
You need to prevent default action.
$('#add_walkin_patient_form').on('submit', function(e) {
e.preventDefault();
//Validate form and submit
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<style>
#first{
display: none;
}
</style>
<div class="container"><br>
<div class="col-lg-6 m-auto d-block">
<form action="" method="" onsubmit="return validation()" class="bg-light">
<div class="form-group">
<label for="">Title</label>
<span class="text-danger">*</span>
<!-- <input class="form-control" type="text" > -->
<select name="title" id="title" class="form-control" >
<option value=""class="form-control" >Select</option>
<option value="Mr" class="form-control">Mr</option>
<option value="Mrs" class="form-control">Mrs</option>
</select>
<span id="tit" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<label for="firstName">FirstName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="First name" id="firstName" >
<span id="first" class="text-danger font-weight-bold"> </span>
</div>
<div class="col">
<label for="lastName">LastName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Last name" id="lastName">
<span id="last" class="text-danger font-weight-bold"> </span>
</div>
</div>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Email" id="email">
<span id="fillemail" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="contact">Your Contact</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Contact Number" id="contact">
<span id="con" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="password">Your Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="password">
<span id="pass" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="conPassword">Confirm Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="conPassword">
<span id="conPass" class="text-danger font-weight-bold"> </span>
</div>
<div class="checkbox">
<label><input type="checkbox"> I accept Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve Email Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve SMS Terms and Conditions</label>
</div>
<input type="submit" name="submit" value="SignUp" id="signUp" class="btn btn-success" autocomplete="off">
</form><br><br>
</div>
</div>
<script type="text/javascript">
function validation(){
var title = document.getElementById('title').value;
var firstName = document.getElementById('firstName').value;
var email=document.getElementById('email').value;
var contact=document.getElementById('contact').value;
var password=document.getElementById('password').value;
var conPassword=document.getElementById('conPassword').value;
var signBut=document.getElementById('signUp');
console.log(firstName);
if(title == ""){
document.getElementById("tit").innerHTML =" Please select the title feild first field";
return false;
}
// if(firstName == "" & firstName.length<=3){
// document.getElementById("first").innerHTML =" Please Enter First Name";
// return false;
// document.getElementById("signUp").addEventListener("click", function(event){
// event.preventDefault()
// });
// }
signBut.addEventListener('click',function(e){
if(firstName=="" & firstName<3)
{
document.getElementById("first").innerHTML="Please Enter proper Name";
e.preventDefault();
}
},false);
if(lastName == ""){
document.getElementById("last").innerHTML =" Please Enter Last Name";
return false;
}
else if(email ==""){
document.getElementById("fillemail").innerHTML="Please Enter Email";
}
else if(contact ==""){
document.getElementById("con").innerHTML="Please Enter Your Contact";
}
else if(password ==""){
document.getElementById("pass").innerHTML="Please Enter Your Password";
}
else if(conPassword ==""){
document.getElementById("conPass").innerHTML="Please Confirm Password";
}
}
</script>
</body>
</html>
I think you should use type button
and then eventClick function of jquery