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.
});
My form contain about 10 input text boxes ,The problem is when I press the enter key from a input text box it's directly going to submit button by skipping the text boxes between them.I added my snippet below.it's working fine when using mouse
function getElement(elm){
var elem = document.getElementById(elm);
return elem;
}
function sendData(){
getElement('submit-button').addEventListener("click",function(){
getElement("success-txt").removeClass('display-none');
if(getElement('pbarcode')){
var pbarcode = $('#pbarcode').val();
var pname = $('#pname').val();
var pprice = $('#pprice').val();
var poprice = $('#poprice').val();
$.ajax({
url:'getdata.php',
method:"post",
data:{pbarcode:pbarcode,pname:pname,pprice:pprice,poprice:poprice},
cache: false,
onSuccess: function(response){
alert('success');
},
onFailure: function(response){
alert('failure');
}
});
}
else{
alert("error");
}
});
}
function showWarnMessage(){
getElement("submit-button").addEventListener("click",function(){
alert("you enteres submitt button");
var data1 = $('#pbarcode').val();
var data2 = $('#pname').val();
var data3 = $('#pprice').val();
var l3 = data3.length;
var l1 = data1.length;
var l2 = data2.length;
var flag = 0;
if(l1 < 1){
flag = 1;
}
if(l2 < 1){
flag = 1;
}
if(l3 < 1){
flag = 1;
}
alert(flag);
if (flag == '0'){
alert(flag + "go");
sendData();
}
});
}
showWarnMessage();
ul,li {
list-style : none;
padding :0px;
margin : 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="create-user" method="post">
<ul id="create-new-user-page">
<li>
<span>Product Barcode</span>
<input type="number" id="pbarcode" name="barcode" class="form-data" required>
</li>
<li>
<span>Product Name</span>
<input type="text" class="form-data" name="pname" id="pname" required>
</li>
<li>
<span>Product Price</span>
<input type="number" class="form-data" name="pprice" id="pprice" required>
</li>
<li>
<input type="submit" id="submit-button" Value="Submit" name="submit_data">
</li>
</ul>
</form>
What I have been tried so far is using
event.preventDefault();
on 'enter' click on text box ,I added the codes below
function preventDefault(elem){
getElement('elem').addEventListener('keypress',function(){
if (event.keyCode == 13) {
event.preventDefault();
alert('calling ')
}
});
}
preventDefault('pname');
preventDefault('pprice');
preventDefault('pname');
preventDefault('pbarcode');
but which also returns the same result.I would like to have a form which works fine with the enter key.(ie,when I press 'enter' key from one input text box which should move in to the next text box ,instead moving directly in to the form submit button)
you can change the button type submit to button.
<input type="button" id="submit-button" Value="Submit" name="submit_data">
My form submitting input field fine without appended input field. When I append input field by clicking add button and input value there and submit my form my appended data not posting.
I tried to print comments after post submit.
function edit($id,$redirect=false){
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$data = array( $save['comments'][] = json_encode($this->input->post('comments')) );
print_r($data);
//echo $save['comments'] = json_encode($this->input->post('comments'));
exit();
}
}
My output
Array ( [0] => ["test"] )
But it just displaying 1st comment not from next that I added using javascript.
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').on('click', function(e) {
e.preventDefault();
$(scntDiv).append('<p><input type="text" name="comments[]" class="form-control col-md-10"/><i class="fa fa-minus" aria-hidden="true"></i>remove</p>');
i++;
});
$(document).on("click", '#remScnt', function(e) {
e.preventDefault();
if( i > 2 ) {
$(this).closest('p').remove();
i--;
}
// return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action="<?php echo site_url('admin/observation/edit/'.$id.'/'.$redirect)?>" enctype="multipart/form-data" id="edit_form">
<h2>Add Another Input Box</h2>
<div id="p_scents">
<p>
<label for="p_scnts"><input type="text" id="p_scnt" size="20" name="comments[]" value="" placeholder="Input Value" /></label>
</p>
</div>
<button type="submit" class="btn btn-primary update">Update</button>
</form>
I have a simple login form with checbox remember me. What i want to achieve is when user checked checbox than create cookies else start session but it still start session even I checked checkbox. Can anyone help ?
This is my html:
<form action="PHP/login.php" method="post" class="loginForm">
<div class="form_vkope">
<input type="text" name="prihlNick" placeholder="Nick" class="prihlNick" />
<img src="Obrazky/ios7-person.png" alt="Ikonka postavy">
</div>
<div class="form_vkope">
<input type="password" name="prihlHeslo" placeholder="Heslo" class="prihlHeslo" />
<img src="Obrazky/locked.png" alt="Ikonka zámok">
</div>
<div class="obal_submitov">
<input type="checkbox" name="zapametat" class="zamapetat" /><label for="zapametat"><span></span>Remember me</label>
<input type="submit" name="prihlasit" value="Login" class="prihlasit" />
</div>
</form>
part of my PHP:
$zapametat = $_POST['zapametat']; //checkbox
if ($dbNick == $Snick AND $dbHeslo == $Sheslo) {
if ($ban != 1) {
if (isset($zapametat)) {
setcookie('id',$dbId,time()+86400, '/');
setcookie('nick',$dbNick,time()+86400, '/');
echo "cookie";
}else{
$_SESSION['id'] = $dbId;
$_SESSION['nick'] = $dbNick;
echo "session";
}
}else{
echo "Tvoj účet bol zablokovaný";
}
}else{
echo "Heslo alebo meno sa nezhoduje";
}
}
And my jQuery:
$('.prihlasit').click(function() {
var prihlNick = $('.prihlNick').val();
var prihlHeslo = $('.prihlHeslo').val();
var prihlasit = $('.loginForm .prihlasit');
var checbox = $('.zapametat'); //checkbox
var data = 'prihlNick='+prihlNick+'&prihlHeslo='+prihlHeslo+'&zapametat='+checbox+'&prihlasit='+prihlasit;
if (prihlNick == '' || prihlHeslo == '') {
$('.loginForm :input').addClass('inputError');
}else{
$('.loginForm :input').removeClass('inputError');
$.ajax({
url: 'PHP/login.php',
type: 'POST',
data: data ,
})
.done(function(data) {
$('.vypis_chyba').html(data);
console.log(data);
})
}
});
I would suggest using this:
jQuery
var checbox = $('.zapametat').prop('checked'); //checkbox (jQuery 1.6+)
PHP
if((isset($zapametat))&&($zapametat==true)){
I have used this jquery validation plugin for the following form.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var obj = document.getElementById("list").cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>
<form id="commentForm" method="get" action="">
<p id="parent">
<input id="list" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
You need to re-parse the form after adding dynamic content in order to validate the content
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
Modified version
jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.
$(document).find('#add_patient_form').validate({
ignore: [],
rules:{
'email[]':
{
required:true,
},
},
messages:{
'email[]':
{
'required':'Required'
},
},
});
In regards to #RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
In case you have a form you can add a class name as such:
<form id="my-form">
<input class="js-input" type="text" name="samplename" />
<input class="js-input" type="text" name="samplename" />
<input class="submit" type="submit" value="Submit" />
</form>
you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:
$(document).ready(function() {
$.validator.addClassRules('js-input', {
required: true,
});
//validate the form
$('#my-form').validate();
});
$('#form-btn').click(function () {
//set global rules & messages array to use in validator
var rules = {};
var messages = {};
//get input, select, textarea of form
$('#formId').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
rules[name] = {};
messages[name] = {};
rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
if (name === "email") {
rules[name].email = true;
//messages[name].email = "Please provide valid email";
}
else if(name==='url'){
rules[name].required = false; // url filed is not required
//add other rules & messages
}
});
//submit form and use above created global rules & messages array
$('#formId').submit(function (e) {
e.preventDefault();
}).validate({
rules: rules,
messages: messages,
submitHandler: function (form) {
console.log("validation success");
}
});
});
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>