empty multiple select field prevent form submission - javascript

I have multiple select field among other fields on my form and submitting the data to the database using ajax. The data is submitting successfully but the problem is, when the multiple select field is empty, noting works: both the js and php code does not execute. Even thought I have the multiple select on the form but I plan not to make mandatory. Please help
$(function() {
$('#form1').on('click', function(e) {
e.preventDefault(); // do not allow the default form action
/* var realvalues = new Array();//storing the selected values inside an array
$('#s2_multi_value:selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
}); */
var form = $(this)[0].form;
var data = $(form).serialize();
$.ajax({
method: "POST",
url: "orgprocess1.php",
data: data
})
.done(function(data) { // capture the return from process.php
var obj = $.parseJSON(data);
var orgvalid = obj.valid2;
var buty = obj.$bty;
var orgmessage = obj.msg_orgcode;
var btypemessage = obj.msg_business;
if (orgvalid == 1) { // place results on the page
$('input[name="org_Code"]').removeClass('textBoxError');
$('#result2').html('<div class="valid"></div>');
} else {
$('input[name="org_Code"]').addClass('textBoxError');
$('#result2').html('<div class="error">' + orgmessage + '</div>');
}
if (buty == 1) { // place results on the page
$('select[name="btype"]').removeClass('textBoxError');
$('#result3').html('<div class="valid"></div>');
} else {
$('input[name="btype"]').addClass('textBoxError');
$('#select3').html('<div class="error">' + btypemessage + '</div>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-4">
<p>Email Address</p>
<input type="text" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="col-sm-4">
<p>Address</p>
<input type="text" class="form-control" id="addre" name="addre" placeholder="Physical Assress">
</div>
<div class="col-sm-4">
<p>Business Type</p>
<select id="s2_multi_value" name="btype[]" class="form-control" multiple="multiple">
<option value="">select one</option>
<option value="Goods">Goods</option>
<option value="Consultancy">Consultancy</option>
</select>
<input type="submit" value="submit" name="submit">
</div>

Try the following snippet it submits form weather you select any value or not.
$(document).ready(function() {
$(document).on('submit', function(e) {
e.preventDefault(); // do not allow the default form action
console.log("form submitting and sending ajax call");
/* var realvalues = new Array();//storing the selected values inside an array
$('#s2_multi_value:selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
}); */
var form = $(this)[0].form;
var data = $(form).serialize();
$.ajax({
method: "POST",
url: "orgprocess1.php",
data: data
}).error(function(){
console.log('error for ajax')
})
.done(function(data) { // capture the return from process.php
var obj = $.parseJSON(data);
var orgvalid = obj.valid2;
var buty = obj.$bty;
var orgmessage = obj.msg_orgcode;
var btypemessage = obj.msg_business;
console.log("into ajax done function",data);
if (orgvalid == 1) { // place results on the page
$('input[name="org_Code"]').removeClass('textBoxError');
$('#result2').html('<div class="valid"></div>');
} else {
$('input[name="org_Code"]').addClass('textBoxError');
$('#result2').html('<div class="error">' + orgmessage + '</div>');
}
if (buty == 1) { // place results on the page
$('select[name="btype"]').removeClass('textBoxError');
$('#result3').html('<div class="valid"></div>');
} else {
$('input[name="btype"]').addClass('textBoxError');
$('#select3').html('<div class="error">' + btypemessage + '</div>');
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="my-form" action="http://google.com">
<div class="form-group">
<div class="col-sm-4">
<p>Email Address</p>
<input type="text" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="col-sm-4">
<p>Address</p>
<input type="text" class="form-control" id="addre" name="addre" placeholder="Physical Assress">
</div>
<div class="col-sm-4">
<p>Business Type</p>
<select id="s2_multi_value" name="btype[]" class="form-control" multiple="multiple">
<option value="">select one</option>
<option value="Goods">Goods</option>
<option value="Consultancy">Consultancy</option>
</select>
<input type="submit" value="submit" name="submit">
</div>
</form>

Related

Problem with required warning message and submit form

I'm implemented the code taken from here to check if radio button is checked and if not, see a warning message.
My code works, but I have a button for submit with ajax (jQuery(function($)) that go ahead also if radio input is not checked.
Some idea to avoid to run function jQuery if function validateForm() is validated?
Here my code:
document.getElementById("filter").onsubmit = validateForm;
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('button').text('Filtering...'); // changing the button label
},
success: function(data) {
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis1(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis2(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br>
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action">
</div>
</form>
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
console.log(validateConsumo());
$(document).on("submit", "form#filter", function(e) {
e.preventDefault();
// Check for validations.
if (!validateConsumo()) {
console.log("Failed validation");
return;
}
console.log("Successful validation");
// Rest of the code here.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br />
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button type="submit" id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action" />
</div>
</form>
Remove document.getElementById("filter").onsubmit = validateForm;
and then update jQuery code like this:
$("#filter").on("submit", function (e) {
e.preventDefault();
// Check for validations.
if (!validateForm()) {
return;
}
// Rest of the code here.
});

JS: prevent reseting of form fields after adding new form

I have below code where I add new form after clicking button. If I put some values into the fields everything is reseted. I would like to prevent that.
I tried e.preventDefault() and return false but it's not working as I would like to.
Additionally after clicking 'add button' I am taking data from json file.
Please see my code here. Any help will be appreciated.
// add new product to the list
const newLocal = document.querySelector('.add-product-button');
const addNewProduct = newLocal;
const listProduct = document.querySelector('.products-list');
const changeVisibility = document.getElementById('change-visibility');
let productCounter = 1;
addNewProduct.addEventListener('click', e => {
e.preventDefault();
productCounter++;
generateTemplate();
changeVisibility.style.display = 'block';
});
const generateTemplate = (e) => {
const html = `
<li>
<div class="first-product-indicator">
<div class="first-product-border-line"></div>
<div class="product-number">${productCounter}</div>
</div>
<form action="" method="get" class="form-product">
<select name="product-type" id="product-type" class="" required>
<option value="" disabled selected hidden>Typ Produktu</option>
<option value="produkt" >PRODUKT GOTOWY</option>
<option value="materiały" >MATERIAŁY POMOCNICZE</option>
<option value="surowce" >SUROWCE</option>
</select>
<div class="product-container">
<select name="product" id="product" class="option-field product-list" required>
<option value="" disabled selected hidden>Produkt</option>
</select>
<i class="fas fa-plus-circle add-product"></i>
</div>
<div class="form-price">
<input type="number" id="quantity" name="quantity" placeholder="Ilość">
<input type="number" id="netto" name="netto" placeholder="Netto">
<input type="number" id="brutto" name="brutto" placeholder="Brutto">
</div>
<div class="form-total-price">
<input type="number" id="netto-total" name="netto-total" placeholder="Wartość netto">
<input type="number" id="brutto-total" name="brutto-total" placeholder="Wartość brutto">
</div>
</form>
</li>
`;
listProduct.innerHTML += html;
// populate product select field with values from json file (finished_good.json)
let newProductElement = document.querySelector('.products-list').lastElementChild;
let dropdownProductAdd = newProductElement.querySelector('.product-list');
dropdownProductAdd.length = 0;
let defaultOptionProductAdd = document.createElement('option');
defaultOptionProductAdd.text = 'Produkt';
dropdownProductAdd.add(defaultOptionProductAdd);
dropdownProductAdd.removeIndex = 0;
const urlProductAdd = 'finished_good.json';
const requestProductAdd = new XMLHttpRequest();
requestProductAdd.open('GET', urlProductAdd, true);
requestProductAdd.onload = function() {
if (requestProductAdd.status === 200) {
const dataProductAdd = JSON.parse(requestProductAdd.responseText);
let optionProductAdd;
for (let i = 0; i < dataProductAdd.length; i++) {
optionProductAdd = document.createElement('option');
optionProductAdd.text = dataProductAdd[i].name;
dropdownProductAdd.add(optionProductAdd);
}
} else {
// Reached the server, but it returned an error
}
}
requestProductAdd.onerror = function() {
console.error('An error occurred fetching the JSON from ' + urlProductAdd);
};
requestProductAdd.send();
e.preventDefault();
};

How am i supposed to use onsubmit event in django template?

i am creating a website using django, i have added a little js for validation, but it's not working. whenever i run the code it says
TypeError: document.getElementById(...) is null
html snippet
<form onsubmit=" return validate_bus()" action="confirm_bus/{{busname}}" method="post">
{% csrf_token %}
<div id="left">
<label>Departure date</label>
<input type="date" autocomplete="off" name="date" id="departuredate"> <br><br>
<label>Username</label>
<input type="text" name="username" id="BusUsername" autocomplete="off">
</div>
<div id="right">
<label>Number of seats</label><br>
<select autocomplete="off" name="seats" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<br>
</select><br><br>
<label> password</label>
<input type="password" autocomplete="off" name="password" id="password">
</div>
<label id="error_message">{{error_message}}</label><br>
<button type="submit">Confirm booking</button>
</form>
and this is my js snippet
function validate_bus()
{
var date = document.getElementById("departuredate").value;
var username = document.getElementById("BusUsername").value;
var seats = document.getElementById("seats").value;
var password = document.getElementById("password").value;
var date_regx = /^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/
var username_regx = /^[a-zA-Z0-9_$.#]+$/
var password_regx = /^(?=.*\d).{4,12}$/
var seats_regx = /[1-6]{1}/
var valid = true
console.log(date, username, seats, password);
if (! date_regx.test(date))
{
valid = false;
}
if (! username_regx.test(username))
{
valid = false;
}
if (! seats_regx.test(seats))
{
valid = false;
}
if(! password_regx.test(password))
{
valid = false;
}
if (!valid)
{
var error = document.getElementById("error_message").innerHTML = "invalid input";
}
console.log(valid)
return valid;
};
Hi there in your var seats = document.getElementById("seats").value; calls an id that's doesn't exist.
Just add the id to your select element and it should fix your error.
ex:
<select autocomplete="off" id="seats" name="seats" >

How to post data to server and capture response

I'm new to web development and stucked at sending data to server. I have registration form and i want to send this data to server. I can send data from form tag using action and method attribute but it will return response in next page. So i read somewhere i have to use ajax to send data. I tried but i cannot send and capture data using script.
This is my reponse
{"success":true}
Html code
<div class="form">
<div class="formdetail">
<h3>Individual Registration</h3>
<label for="fname"> Name</label><br>
<input type="text" size="40" id="name" name="name" placeholder="Enter your name.." required><br><br>
<label for="phonenumber">Mobile Number</label>
<br/>
<input id="mobileno" size="40" name="mobileno" type="tel" size="20" maxlength="13" placeholder="Enter your mobile number..." type="number" required><br><br>
<label for="email">Email-Id</label><br>
<input type="text" size="40" id="email" name="email" placeholder="Enter your email-id..." required><br><br>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" name="dob" onclick="mydate();" hidden />
<input type="button" Value="Date of Birth" onclick="mydate();" />
<script>
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("dob").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("dob").value=dt+"/"+mn+"/"+yy
document.getElementById("dob").hidden=false;
document.getElementById("dt").hidden=true;
}
</script>
<br><br>
<label for="address">Address</label><br>
<input type="text" id="address" size="40" name="address" placeholder="Enter your address..." required><br><br>
<label for="country">Country</label><br>
<input type="text" id="country" size="40" name="country" placeholder="Enter your country name....." required><br><br>
<label for="State">State</label><br>
<input type="text" id="state" size="40" name="state" placeholder="Enter your state name....." required><br><br>
<label for="city">City</label><br>
<input type="text" id="city" size="40" name="city" placeholder="Enter your city name....." required><br><br>
<input type="hidden" name="category" value="Individual">
<input type="submit" value="Submit" id="someInput" onclick="ajax_post()"><br>
<p class="small">Institute Registraion</p>
</div>
</div>
</form>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "https://smilestechno.000webhostapp.com/Register.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200) {
var resp = console.log(response);
if (resp == "true") {
}
}
hr.send("name="+ name + "&mobileno=" + mobileno + "&email=" + email + "&dob=" + dob + "&address=" + address + "&city=" + city + "&state=" + state + "&country=" + country );
document.getElementById("status").innerhtml = "processing";
}
you can not send variable in this format.
var vars = name+mobileno+email+dob+address+city+state+country;
Params must have a format like:
hr.send("fname=Henry&lname=Ford");
Code you need:
hr.send("name=" + name + "&monbileno=" + mobileno + ... );
You can use jquery to use ajax in a simple way.
Reference:
xmlhttprequest https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
jquery ajax https://www.w3schools.com/jquery/jquery_ref_ajax.asp
Use jquery, it makes it easier. This is how it should be using just the fname and email as an example with jquery ajax:
<form name="myForm" id="myForm" action="myActionUrl" method="POST">
<input type="text" name="fname" id="fname">
<input type="email" name="email" id="email">
<input type="submit" value="Submit">
</form>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$("#myForm").on("submit", function(event){
event.preventDefault(); //this prevents the form to use default submit
$.ajax({
method: "POST",
url: $(this).attr("action"), //this will use the form's action attribute
data: {fname: $("#fname").val(), email: $("#email").val()},
success: function(responseData){
//do something here with responseData
}
});
});
</script>
Please replace the "myActionUrl" part with the url/file that processes your data.
The file can be some basic php file which stores the data into some database and returns or echoes something back so that you can use it within the "responseData" on the ajax success function.
Hope this helps!
Please call function like this
onclick="ajax_post()"
not
onclick="ajax_post"
You used getElementById but selected a name attribute
have to use
getElementById('fname').value;
not
getElementById('name').value;
hey i would recommend using jquery to accomplish this task.
this isthe client script
script type="text/javascript" src='jquery.js'></script>
<!-- download the lates version -->
<script type="text/javascript">
ajax_post(){
var url = "https://smilestechno.000webhostapp.com/Register.php";
var name = $("#name").val();
var mobileno = $("#mobileno").val();
var email = $("#email").val();
var dob = $("#dob").val();
var address = $("#address").val();
var city = $("#city").val();
var state = $("#state").val();
var country = $("#country").val();
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'json',
'url':url,
'data':{name:name,mobileno:mobileno,email:email,dob:dob,address:address,city:city,state:state,country},
'success': function (data) {
tmp = data;
}
});
return tmp; // you can access server response from this tmp variable
}
Server side
<?php
//get items as post inputs
print_r($_POST[]);
echo $_POST['name'];
?>

onsubmit validateForm funxtion is not working

here for validation i used onsubmit event.
but any how its not working.
i just want check that textbox filed is empty or not.
<!DOCTYPE html>
<html>
<head>
<title>temple3</title>
<link rel="stylesheet" type="text/css" href="temple3css.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div id="popup-content" class='container'>
<div id="container1">
<form id="form" class="form" onsubmit="return validateForm()">
<h1>Feedbak Form</h1>
<div class="content">
<div class="intro"></div>
<div id="section0" >
<div class="field roption">
<input type="radio" name="view" value="public" checked="checked"> <span>Public</span>
<input type="radio" name="view" value="private" ><span>Private</span>
</div>
<div class="field category">
<label for>Category:</label>
<select class="dropDownCate" autofocus>
<option value="bug">Bug</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="field message">
<label for="Comments">Comments:</label>
<textarea id="comments" name="Comments" placeholder='Your Feedback Here!' autofocus></textarea>
</div>
<div class="field">
<label for="Email">Email</label>
<input type="email" id="email" name="Email" placeholder="example#stevens.edu(optional)" autofocus>
</div>
<div class="field"><input type="submit" id="submit-feedback-button" autofocus></div>
</div>
</div>
</form>
</div>
</div>
<div id="popup-overlay-bg"> </div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function validateForm(){
var texbox=document.getElementById("comments").value;
if(texbox == "") {
document.getElementById("comments").focus();
// document.getElementById("comments").style.border = "1px solid #ff0000";
return false;
}
}
$(document).ready(function(){
$("#feedback-button").click(function(){
openfeedbackform();
});
$("#popup-overlay-bg").click(function(){
closefeedbackform();
});
$("#submit-feedback-button").click(function(){
// closefeedbackform();
});
$(window).resize(function(){
updatefeedbackform();
});
$("#submit-feedback-button").click(function(){
var category=$(".dropDownCate").val();
var roption=$('input:radio[name=view]:checked').val();
var message=$("#comments").val();
var email=$("#email").val();
$.ajax({
type: "POST",
url: "feedback.php",
data: "category="+category+ "&roption="+roption+ "&message="+message+ "&email="+email,
success:function(result)
{
if(result=="true"){
$("#form").hide();
$("#container1").html("<h3>Thank you for your feedback We will get back to you ASAP</h3> ");
}
else{
$("#form").hide();
$("#container1").html("<h3> database error </h3>");
}
}
});
return false;
});
});
function openfeedbackform(){
$("#popup-content").find('input:text').val('');
$("#popup-content").fadeIn();
$("#popup-overlay-bg").fadeIn();
updatefeedbackform();
}
function updatefeedbackform(){
$popup=$("#popup-content");
var top = "50px";
var left = ($(window).width() - $popup.outerWidth()) / 2;
$popup.css({
'top' : top,
'left' : left
});
}
function closefeedbackform(){
$("#popup-content").fadeOut();
$("#popup-overlay-bg").fadeOut();
}
</script>
</body>
</html>
earlier i used same this for form validation. but i don't why its not working here. i tried to debug but function has not been call.
The problem is you are doing ajax submit in the button click event, not in the form submit.
The click handler is triggered before the submit event handler, so the validation does not have any effect.
The solution will be to use the form submit event handler for both validation and the ajax call as given below, and then there is no need to have the inline event handler like onsubmit="return validateForm()"
$("#form").submit(function () {
if (validateForm() === false) {
return false;
}
var category = $(".dropDownCate").val();
var roption = $('input:radio[name=view]:checked').val();
var message = $("#comments").val();
var email = $("#email").val();
$.ajax({
type: "POST",
url: "feedback.php",
data: "category=" + category + "&roption=" + roption + "&message=" + message + "&email=" + email,
success: function (result) {
if (result == "true") {
$("#form").hide();
$("#container1").html("<h3>Thank you for your feedback We will get back to you ASAP</h3> ");
} else {
$("#form").hide();
$("#container1").html("<h3> database error </h3>");
}
}
});
return false;
});

Categories