using check box selected append textarea and update textarea value using jQuery - php

I have problem in updating value of textarea.
when this checkbox is checked , it will show textarea. Now the problem is i am not able to add and save some more text in the textarea.
For example, as of now the textarea shows CBC value, but if i change it to CBC NEW, then it should be update to CBC NEW.
('#contactform :checkbox.one_c').change(function() {
var $this = $(this);
if ($this.is(':checked')) {
var newInput = $('<textarea id="addme" class="doctor1 value" ><div id="c-content"></div></textarea>');
$('#contactform').append(newInput);
$("textarea").text("CBC");
$('#contactform :checkbox.one_c').attr("checked", "checked");
} else {
$('#contactform').find('#addme').remove();
$('#contactform :checkbox.one_c').removeAttr('checked');
}
});
<form class="textboxes1" method="post" id="tb2_1964">
<div id="contactform">
<div class="row">
<div class="col-md-3 col-sm-4 col-xs-12 remove_all">
<input type="checkbox" class="checkbox-inline one_c" checked="checked">
<label>CBC </label>
</div>
</div>
<textarea id="addme" class="doctor1 value">CBC</textarea>
<div id="c-content"></div>
</div> <button class="patient_add2 no_print">Save</button>
</form>

problem in your JS code. Try this hope this is helpful for you
$('.one_c').change(function() {
var $this = $(this);
if ($this.is(':checked')) {
var newInput = $('<textarea id="addme" class="doctor1 value" ><div id="c-content"></div></textarea>');
$('#contactform').append(newInput);
$("textarea").text("CBC");
$('#contactform :checkbox.one_c').attr("checked", "checked");
} else {
$('#contactform').find('#addme').remove();
$('#contactform :checkbox.one_c').removeAttr('checked');
}
});
$('.patient_add2').click(function(){
alert($("textarea").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form class="textboxes1" method="post" id="tb2_1964">
<div id="contactform">
<div class="row">
<div class="col-md-3 col-sm-4 col-xs-12 remove_all">
<input type="checkbox" class="checkbox-inline one_c" checked="checked">
<label>CBC </label>
</div>
</div>
<textarea id="addme" class="doctor1 value">CBC</textarea>
<div id="c-content"></div>
</div> <button class="patient_add2 no_print">Save</button>
</form>

Related

Form Validation with Jquery with if statements

I'm about to release my personal website but stucked with contact form validation. I want visitors to properly enter every field. While I'm doing this, I can go for both sides (either javascript or php validation). But the page is static HTML, only requests for mail.php for sending it. (Using PHPMAILER).
What I want is basically users to get notified in each field, then if they enter everything properly, I want them to submit the form and show the success message, without redirecting them. So here is my code and I appreciate for your help.
<form name="form1" id="contact-form" method="post" role="form">
<div class="col-md-8 col-pb-sm animate-box">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="name" required="required" class="form-control" placeholder="Your Name">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="email" required="required" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" name="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" required="required" name="message" id="" cols="30" rows="7" placeholder="Message"></textarea>
</div>
</div>
<div class="col-md-12">
<div class="col-md-3 form-group">
<input type="submit" name="submit" value="Send Message" class="btn btn-primary" formaction="mail.php" onsubmit="return ValidateLoginForm();">
</div>
<div class="col-md-7 col-md-offset-1 form-align" id="form_response"></div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<footer>
<div id="footer">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<p>
Copyright © 2020 Umut Pirinci.
</p>
</div>
</div>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- animateAnything -->
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/409445/animateAnything.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Owl Carousel -->
<script src="js/owl.carousel.min.js"></script>
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<!-- Main JS (Do not remove) -->
<script src="js/main.js"></script>
<script>
$(function() {
$('a[href*=\\#]:not([href=\\#])').on('click', function() {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
});
});
</script>
<script>
$(function () {
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "mail.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
</script>
<script>
function ValidateLoginForm() {
var name = document.form1.name;
var message = document.form1.message;
var email = document.form1.email;
if (name.value == "") {
alert("Your name wasn't recognised.");
name.focus();
return false;
}
if (message.value == "") {
alert("Please enter your message.");
message.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address.");
email.focus();
return false;
}
else {
return true;
}
}
</script>
<script>
function form_sub() {
$('#form_response').html('Your form has been successfully sent!').fadeIn(1500).delay(5000).fadeOut(1500);
}
</script>
</body>
</html>
There are some things you need to do:
1- input with type submit you need to remove the onsubmit attribute as this attribute must be added on FORM tag only.
2- try to combine submission functions with only one.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form name="form1" id="contact-form" method="post" role="form">
<div class="col-md-8 col-pb-sm animate-box">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="name" required="required" class="form-control" placeholder="Your Name">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="email" required="required" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" name="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" required="required" name="message" id="" cols="30" rows="7" placeholder="Message"></textarea>
</div>
</div>
<div class="col-md-12">
<div class="col-md-3 form-group">
<input type="submit" name="submit" value="Send Message" class="btn btn-primary" formaction="mail.php">
</div>
<div class="col-md-7 col-md-offset-1 form-align" id="form_response"></div>
</div>
</div>
</div>
</form>
<script>
$('#contact-form').on('submit', function (e) {
ValidateLoginForm();
e.preventDefault();
return false;
})
function ValidateLoginForm() {
var name = document.form1.name;
var message = document.form1.message;
var email = document.form1.email;
if (name.value == "") {
alert("Your name wasn't recognised.");
name.focus();
return false;
}
if (message.value == "") {
alert("Please enter your message.");
message.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address.");
email.focus();
return false;
} else {
var url = "mail.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
}
}
</script>

Insert multiple values in row php

I can`t find a solution for this formular, so i am asking you guys how i can solve this: (1)I have this formular:
<form id="formRetur" action="" method="POST" novalidate="novalidate">
<div id="mail-status" style="color: black;text-align: center;"></div>
<h3><strong>
Detalii client
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nume_prenume" id="nume_prenume" placeholder="Nume Prenume">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_tlf" id="nr_tlf" placeholder="Numar telefon">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="adresa_email" id="adresa_email" placeholder="Adresa email">
</div>
</div>
</div>
<h3><strong>
Detalii comanda
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_comanda" id="nr_comanda" placeholder="Numar comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="data_comanda" id="data_comanda" placeholder="Data comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_factura" id="nr_factura" placeholder="Numar factura">
</div>
</div>
</div>
<h3><strong>
Detalii produse
</strong></h3>
<div class="row">
<i class="fa fa-plus" aria-hidden="true" style="position: absolute;z-index:999;"></i>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="den_prod" id="den_prod" placeholder="Denumire produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="culoare_prod" id="culoare_prod" placeholder="Culoare produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="cantitate" id="cantitate" placeholder="Cantitate">
</div>
</div>
</div>
<div class="maimulte">
</div>
<h3><strong>
Motiv retur
</strong></h3>
<div class="row">
<div class="col-md-12">
<textarea name="motiv" id="motiv" class="form-control" cols="30" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-12" style="margin-top:10px;margin-bottom:10px;"><div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div> </div>
<div class="col-md-12">
<button type="submit" id="send-message" class="btn btn-default">Trimite </button>
</div>
<div id="loader-icon" style="display:none;"><img src="images/loader.gif"></div>
</div>
</form>
I use ajax to insert data in DB, but i have an option where you can add more products when user press + adding +1 row with 3 fields name,color, qty and i want to insert also these in db, here is my ajax:
<script>
$(document).ready(function (e){
$("#formRetur").on('submit',(function(e){
e.preventDefault();
$("#mail-status").hide();
$('#send-message').hide();
$('#loader-icon').show();
$.ajax({
url: "valid_retur.php",
type: "POST",
dataType:'json',
data: {
"nume_prenume":$('input[name="nume_prenume"]').val(),
"nr_tlf":$('input[name="nr_tlf"]').val(),
"adresa_email":$('input[name="adresa_email"]').val(),
"nr_comanda":$('input[name="nr_comanda"]').val(),
"data_comanda":$('input[name="data_comanda"]').val(),
"nr_factura":$('input[name="nr_factura"]').val(),
"den_prod":$('input[name="den_prod"]').val(),
"culoare_prod":$('input[name="culoare_prod"]').val(),
"cantitate":$('input[name="cantitate"]').val(),
"motiv":$('textarea[name="motiv"]').val(),
"g-recaptcha-response":$('textarea[id="g-recaptcha-response"]').val()},
success: function(response){
// $( '#frmContact' ).each(function(){
// this.reset();
// });
$("#mail-status").show();
$('#loader-icon').hide();
if(response.type == "error") {
$('#send-message').show();
$("#mail-status").attr("class","alert alert-danger");
} else if(response.type == "message"){
// grecaptcha.reset();
$('#send-message').show();
$("#mail-status").attr("class","alert alert-success");
}
$("#mail-status").html(response.text);
},
error: function(){}
});
}));
});
</script>
Here is my db:enter image description here
And there is my php file who insert in db with values from ajax:
<?php
if($_POST)
{
include('config.php');
$nume_prenume = filter_var($_POST["nume_prenume"], FILTER_SANITIZE_STRING);
$nr_tlf = filter_var($_POST["nr_tlf"], FILTER_SANITIZE_STRING);
$adresa_email = filter_var($_POST["adresa_email"], FILTER_SANITIZE_STRING);
$nr_comanda = filter_var($_POST["nr_comanda"], FILTER_SANITIZE_STRING);
$data_comanda = filter_var($_POST["data_comanda"], FILTER_SANITIZE_STRING);
$nr_factura = filter_var($_POST["nr_factura"], FILTER_SANITIZE_STRING);
$den_prod = filter_var($_POST["den_prod"], FILTER_SANITIZE_STRING);
$culoare_prod = filter_var($_POST["culoare_prod"], FILTER_SANITIZE_STRING);
$cantitate = filter_var($_POST["cantitate"], FILTER_SANITIZE_STRING);
$motiv = filter_var($_POST["motiv"], FILTER_SANITIZE_STRING);
if(empty($nume_prenume)) {
$empty[] = "<b>nume_prenume</b>";
}
if(empty($nr_tlf)) {
$empty[] = "<b>nr_tlf</b>";
}
if(empty($adresa_email)) {
$empty[] = "<b>adresa_email</b>";
}
if(empty($nr_comanda)) {
$empty[] = "<b>nr_comanda</b>";
}
if(empty($data_comanda)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($den_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($culoare_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(!empty($empty)) {
$output = json_encode(array('type'=>'error', 'text' => implode(", ",$empty) . ' obligatoriu!'));
die($output);
}
// if(!filter_var($email2, FILTER_VALIDATE_EMAIL)){ //email validation
// $output = json_encode(array('type'=>'error', 'text' => '<b>'.$email2.'</b> is an invalid Email, please correct it.'));
// die($output);
// }
//reCAPTCHA validation
if (isset($_POST['g-recaptcha-response'])) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$output = json_encode(array('type'=>'error', 'text' => '<b>Captcha</b> Validation Required!'));
die($output);
}
}
// bag in db
$sql0 = "INSERT INTO retur (nume_prenume, nr_tlf, email, nr_comanda, data_comanda, nr_factura, den_prod, culoare_prod, cantitate_prod, motiv_retur)
VALUES ('$nume_prenume', '$nr_tlf', '$adresa_email', '$nr_comanda', '$data_comanda', '$nr_factura', '$den_prod', '$culoare_prod', '$cantitate', '$motiv')";
mysqli_query($conn, $sql0);
}
So basically this is a formular for returns products and if he have more products to return i added that jquery to add more fields and i want to be inserted in databased then i will fetch data and display it in my CMS.
1.You don't have to write that much code in ajax. You can easily use serialize():
Reduce you ajax code with below code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#your_form_id");
$("#Your_submit_id").click(function(){
$.ajax({
type:"POST",
url:"URL",
data:form.serialize(),
success: function(response){
console.log(response);
}
});
});
});
</script>
2.To add multiple product:
-You have to create every input field as array for product info like:
<input type="text" name="prod_name[]">
This array statement store you every product info index wise. If you
used normal variable then it will post only you last product
details.
In Php code you have to take the count of posted
product title & use for loop to get the every product information.
for($i=0;$i<count($prod_name);$i++)
{
//Insert/fetch All Values like : $prod_name[$i]
}
-When you click on add, just create clone of the prev available div.

Text is appending multiple times due to incorrect Ajax data parameter. What is the correct parameter?

I'm fairly new to Ajax. I am getting the correct values from the PHP url in my Ajax function. The problem is that my data parameter is causing it to duplicate values.
Here is what is displaying on the actual webpage:
Here is the console.log output:
[2000, 335.1032163829112]
[2000, 335.1032163829112]
[2000, 335.1032163829112]
[2000, 335.1032163829112]
[2000, 335.1032163829112]
The form has 5 input fields, so I'm assuming since the Ajax function says $('form').serialize(), it's returning the requested values as many times are there are input fields.
What is the correct data parameter to send what I need? I only need 2 values that are calculated in my php script.
Here is the initial form, then the hidden div and Ajax call:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Volume Calculator</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="container page-heading">
<h2>Volume Calculator</h2>
</div>
<!--<form class="form-horizontal" method="post" action="result.php">-->
<form id="form" class="form-horizontal" method="post" action="">
<div class="form-container">
<p class="calculate-heading">Calculate Volume of a Rectangle</p>
</div>
<div class="container form-container">
<div class="row">
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<label for="width" class="col-sm-3 col-form-label">Width: </label>
<div class="col-sm-9">
<input type="number" class="form-control pull-left" id="width" name="width" required>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<label for="length" class="col-sm-3 col-form-label">Length: </label>
<div class="col-sm-9">
<input type="number" class="form-control pull-left" id="length" name="length" required>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<label for="height" class="col-sm-3 col-form-label">Height: </label>
<div class="col-sm-9">
<input type="number" class="form-control pull-left" id="height" name="height" required>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 bs-linebreak">
<!-- NOTHING. JUST A LINE BREAK -->
</div>
</div>
<div class="form-container">
<p class="calculate-heading">Calculate Volume of a Cone</p>
</div>
<div class="container form-container">
<div class="row">
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<label for="radius" class="col-sm-3 col-form-label">Radius: </label>
<div class="col-sm-9">
<input type="number" class="form-control pull-left" id="radius" name="radius" required>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<label for="cone_height" class="col-sm-3 col-form-label">Height: </label>
<div class="col-sm-9">
<input type="number" class="form-control pull-left" id="cone_height" name="cone_height"
required>
</div>
</div>
</div>
</div>
</div>
<div class="container form-container">
<div class="row">
<!--<button type="submit" id="submit-btn" class="btn btn-primary">Calculate</button>-->
<button type="button" id="submit-btn" class="btn btn-primary">Calculate</button>
</div>
</div>
</form>
Hidden div that appears and Ajax function:
<!-- NEW DIV THAT APPEARS ON FORM SUBMIT. HIDDEN BY DEFAULT VIA JQUERY -->
<div id="result-form" class="form-horizontal">
<div class="form-container">
<p class="calculate-heading">Summary of Calculations</p>
</div>
<div class="row">
<div class="col-md-12 bs-linebreak">
<!-- NOTHING. JUST A LINE BREAK -->
</div>
</div>
<div class="form-container">
<p class="calculate-heading calculate-heading-bold">Volume of Rectangle</p>
<p id="length-p" class="calculate-heading">Length: </p>
<p id="width-p" class="calculate-heading">Width: </p>
<p id="height-p" class="calculate-heading">Height: </p>
<br>
<p id=rec_volume-p" class="calculate-heading">The Volume of the Rectangle is <strong></strong></p>
</div>
<div class="form-container">
<p class="calculate-heading calculate-heading-bold">Volume of a Cone</p>
<p id="radius-p" class="calculate-heading">Radius: </p>
<p id="cone_height-p" class="calculate-heading">Height: </p>
<br>
<p id="cone_volume-p" class="calculate-heading">The Volume of the Cone is <strong></strong></p>
</div>
</div>
</body>
<script>
//HIDE THE DIV WHEN DOCUMENT IS LOADED
$(document).ready(function() {
$('#result-form').hide();
});
//GET RID OF DEFAULT HTML INVALID WARNING
$('input').on("invalid", function (e) {
e.preventDefault();
});
//HANDLE BUTTON SUBMIT
//LOOP THROUGH ALL INPUT ELEMENTS AND CHECK FOR INVALID FIELDS
$('#submit-btn').click(function () {
$('form input[type!=submit]').each(function () {
if ($(this).val() == '') {
alert("All fields are required");
return false;
}
else {
//AJAX CALL HERE
$.ajax({
type:'post',
url:'calculate.php',
data: $('form').serialize(), //<-- THIS IS THE PROBLEM, BUT I DON'T KNOW WHAT TO DO
success: function(output) {
var result = $.parseJSON(output);
console.log(result);
$('#result-form').show();
$('#length-p').append($('#length').val());
//REST OF THE VALUES UNDER THIS
}
});
}
});
});
</script>
The calculate.php script:
<?php
//Rectangle dims
$width = $_POST['width'];
$length = $_POST['length'];
$height = $_POST['height'];
//Cone dims
$radius = $_POST['radius'];
$cone_height = $_POST['cone_height'];
//Rectangle volume
$rec_volume = $width * $length * $height;
//Cone volume
$cone_volume = 1/3 * (M_PI * pow($radius, 2) * $cone_height);
echo json_encode(array($rec_volume, $cone_volume));
I would really like to do this asynchronously instead of going to a completely new page. It just seems redundant. What is the correct data parameter?
Thanks.
Your code loops over every variable in the form and issues an ajax call. Each ajax call returns and appends the results to the #length-p element.
The solution is to only call the ajax once, after you've verified all the elements are filled out. This should do it.
$('#submit-btn').click(function () {
// validate, failures issue alert and exist the call.
$('form input[type!=submit]').each(function () {
if ($(this).val() == '') {
alert("All fields are required");
return false;
}
});
// no failure, so issue the request.
//AJAX CALL HERE
$.ajax({
type:'post',
url:'calculate.php',
data: $('form').serialize(), //<-- THIS IS THE PROBLEM, BUT I DON'T KNOW WHAT TO DO
success: function(output) {
var result = $.parseJSON(output);
console.log(result);
$('#result-form').show();
$('#length-p').append($('#length').val());
//REST OF THE VALUES UNDER THIS
}
});
});

jQuery show hide select menus based on serialized hash

I am trying to get select menus show hide by using ajax and serialised hashes. I had this system working last night but I changed the #selector from a form to a div and suddenly its stopped running. I had to broaden the form for additional data on post and did not want to serialise all the data at once for this as it would be additional strain on the system.
The page somewhat works as expected. It shows the first select, allows me to select an option, I can see the AJAX posting but the hash value is empty which I believe is breaking the PHP above. I cant figure out why the hash is posting empty. I assume its not getting the value from the select but I cant work out why..
If possible can you please point out where I am going wrong?
<section id="add">
<div class="container">
<form method="post">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><strong>Step 1: Instance Select</strong></h3>
</div>
<div id="selector">
<div class="panel-body">
<div class="col-md-6">
<select class="form-control box1" name="box1"></select>
<input name="box1hash" class="box1hash" type="hidden" />
</div>
<div class="col-md-6">
<select class="form-control box2" name="box2"></select>
<input name="box2hash" class="box2hash" type="hidden" />
</div>
<div class="col-md-6">
<select class="form-control box3" name="box3"></select>
<input name="box3hash" class="box3hash" type="hidden" />
</div>
<div class="col-md-6">
<select class="form-control box4" name="box4"></select>
<input name="box4hash" class="box4hash" type="hidden" />
</div>
<div class="col-md-6">
<select class="form-control box5" name="box5"></select>
<input name="box5hash" class="box5hash" type="hidden" />
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><strong>Step 2: Event Details</strong></h3>
</div>
<div class="panel-body">
<input name="event_name" type="text" class="form-control" />
</div>
</div>
<input type="submit"/>
</form>
</div>
$(document).on('change', '#selector', function(e) {
ajax_post(this);
});
ajax_post();
})(jQuery);
function show_hide_select(select){
if ($(select).find('option').length < 1) {
$(select).hide();
} else {
$(select).show();
}
}
function ajax_post(element=null) {
var frm = $('#selector');
if (element != null) {
// Reset selections
var found=false;
frm.find('select').each(function(e){
if (found==true) {
$(this).hide().find('option:selected').prop("selected", false)
}
if (element==this) found=true;
});
}
$.ajax({
url: '?ajax=1',
type: "POST",
data: frm.serialize(),
dataType: 'json',
success: function (data) {
if (data.box1hash != frm.find('.box1hash').val()) {
frm.find('.box1').html(data.box1?data.box1:'');
frm.find('.box1hash').val(data.box1hash);
show_hide_select(frm.find('.box1'));
}
if (data.box2hash != frm.find('.box2hash').val()) {
frm.find('.box2').html(data.box2?data.box2:'');
frm.find('.box2hash').val(data.box2hash);
show_hide_select(frm.find('.box2'));
}
if (data.box3hash != frm.find('.box3hash').val()) {
frm.find('.box3').html(data.box3?data.box3:'');
frm.find('.box3hash').val(data.box3hash);
show_hide_select(frm.find('.box3'));
}
if (data.box4hash != frm.find('.box4hash').val()) {
frm.find('.box4').html(data.box4?data.box4:'');
frm.find('.box4hash').val(data.box4hash);
show_hide_select(frm.find('.box4'));
}
if (data.box5hash != frm.find('.box5hash').val()) {
frm.find('.box5').html(data.box5?data.box5:'');
frm.find('.box5hash').val(data.box5hash);
show_hide_select(frm.find('.box5'));
}
}
});
}
</script>
Contrary to my earlier comments, a form tag cannot be nested within another form tag. jquery serialize() only works on forms, so unfortunately it's not possible to focus it on a div component of the form. Instead however you can serialize the whole form as a string, and then extract the subsection of that string for reduced ajax posting. Snippet below with inline comments...
$('form').on({
'change':function(e){
e.preventDefault();
var dats = $(this).serialize(); // serialize the whole form into a string
var pico = dats.indexOf('&event_name='); // get the index of the end point of the desired data
var newDats = dats.slice(0 , pico); // get the edited section for ajax submission
$('#results').text(dats+' '+newDats);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="add">
<div class="container">
<form method="post" id='bob'>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><strong>Step 1: Instance Select</strong></h3>
</div>
<div id="selector">
<div class="panel-body">
<div class="col-md-6">
<select class="form-control box1" name="box1">
<option>a</option>
<option>b</option>
<option>c</option>
</select>
<input name="box1hash" class="box1hash" type="hidden" />
</div>
<div class="col-md-6">
<select class="form-control box2" name="box2"></select>
<input name="box2hash" class="box2hash" type="hidden" />
</div>
<div class="col-md-6">
<select class="form-control box3" name="box3"></select>
<input name="box3hash" class="box3hash" type="hidden" />
</div>
<div class="col-md-6">
<select class="form-control box4" name="box4"></select>
<input name="box4hash" class="box4hash" type="hidden" />
</div>
<div class="col-md-6">
<select class="form-control box5" name="box5"></select>
<input name="box5hash" class="box5hash" type="hidden" />
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><strong>Step 2: Event Details</strong></h3>
</div>
<div class="panel-body">
<input name="event_name" type="text" class="form-control" />
</div>
</div>
<input type="submit"/>
</form>
</div>
<p><tt id="results"></tt></p>

Form validation before Submit

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

Categories