I have a very typical example of jQuery validation form but it doesn't seem to work.
Here is my code:
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and 13 or larger.</title>
<link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
</head>
<body>
<h3>Contact Form</h3>
<form method="POST" class="form-horizontal" id="contact-form" action="">
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" name="name" id="name" placeholder="Your name" size="50">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" name="email" id="email" placeholder="Your email address" size="50">
</div>
</div>
<div class="control-group">
<label class="control-label" for="message">Message</label>
<div class="controls">
<textarea name="message" id="message" rows="8" cols="52" class="span5" placeholder="The message you want to send to us."></textarea>
</div>
</div>
<div class="control-group">
<?php
$var1 = rand(1,20);
$var2 = rand(1,20);
$sum = $var1 + $var2;
?>
<label class="control-label" for="captcha">Please enter the result of <?php echo $var1.' + '.$var2.' ='; ?>
</label>
<input type="text" id="captcha" name="captcha"><br/>
</div>
<br/>
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button type="submit" name="contact-submit" class="btn btn-success">Submit Message</button>
<button type="reset" class="btn">Cancel</button>
</div>
</form>
</body>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$("#contact-form").validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
captcha: {
required: true,
min: <?php echo $sum; ?>,
max: <?php echo $sum; ?>
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
});
jQuery.extend(jQuery.validator.messages, {
min: jQuery.validator.format("Wrong answer."),
max: jQuery.validator.format("Wrong answer.")
});
});
});
</script>
The only one thing needs to pay attention is my simple captcha. I use 2 php variables and its sum to check whether a spammer try to contact.
When I click on Submit button, the browser just refresh and nothing else happen, no error was generated. However, clicking Cancel button allow me to reset the form.
I have already searched for existing question relating to why jQuery validation did not work but can not figure out my case. Please help me to solve it. Any help is appreciated. Thank you in advance.
Based on suggestion from #Juhana, I worked around with my code and found another way to make my code work. I just replaced:
jQuery.extend(jQuery.validator.messages, {
min: jQuery.validator.format("Wrong answer."),
max: jQuery.validator.format("Wrong answer.")
by
messages: {
captcha: {
min: "Wrong answer",
max: "Wrong answer"
}
}
Thank you for your help.
You're breaking it because you've placed jQuery.extend() inside of the .validate() method; and you've improperly included a closing parenthesis and semicolon where there can only be a comma.
$("#contact-form").validate({
// options...
....,
success: function (element) {
....
}); // <- ');' is not valid here. Options must be separated by commas
jQuery.extend(jQuery.validator.messages, { // <- this is not a valid option!
min: jQuery.validator.format("Wrong answer."),
max: jQuery.validator.format("Wrong answer.")
});
});
Only the options provided by the developer can go inside of the .validate() method.
$("#contact-form").validate({
// options...
....,
success: function (element) {
....
}, // <- options must be separated by commas
messages: { // <- valid option
captcha: {
min: "Wrong answer",
max: "Wrong answer"
}
}
});
Related
I want to use the jquery plugin for validating my form with letters only in name section. such that when a user enters special characters or numbers it gives an error. Also i want to check the form validation as the users types the information i.e. realtime validation before submitting the form.
//jquery validation
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='book']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
fname: {
required: true,
lettersonly: true
},
lname:{
required: true,
lettersonly: true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
// Specify validation error messages
messages: {
fname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
lname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
<script src="design/bootstrap-3.3.7-dist/js/jquery.validate.js"></script>
<script src="design/bootstrap-3.3.7-dist/js/additional-methods.js"></script>
<form name="book" id="book" action="" method="post">
<div class="row form-group">
<div class="col-md-6 ">
<label class="" for="fname">First Name</label>
<input type="text" name="fname" id="fname" class="form-control" placeholder="First Name">
</div>
<div class="col-md-6">
<label class="" for="lname">Last Name</label>
<input type="text" name="lname" id="lname" class="form-control" placeholder="Last Name">
</div>
</div>
<div class="row form-group">
<div class="col-md-6 ">
<label class="" for="date">Date</label>
<input type="text" id="date" class="form-control datepicker px-2" placeholder="Date of visit">
</div>
<div class="col-md-6">
<label class="" for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="" for="treatment">Service You Want</label>
<select name="treatment" id="treatment" class="form-control">
<option value="">Hair Cut</option>
<option value="">Hair Coloring</option>
<option value="">Perms and Curls</option>
<option value="">Hair Conditioning</option>
<option value="">Manicure</option>
<option value="">Pedicure</option>
<option value="">Nails Extension</option>
<option value="">Nail Design</option>
<option value="">Waxing Eyebrows</option>
<option value="">Waxing Hands/Legs</option>
<option value="">Full Face Waxing</option>
<option value="">Full Body/Body Parts Wax</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="" for="note">Notes</label>
<textarea name="note" id="note" cols="30" rows="5" class="form-control" placeholder="Write your notes or questions here..."></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<center><input type="submit" value="Book Now" class="btn btn-primary btn-lg"></center>
</div>
</div>
</form>
I want to use the jquery plugin for validating my form with letters only in name section. such that when a user enters special characters or numbers it gives an error
var RegEx = /^[a-zA-Z\s]*$/;
if (RegEx.test($('#input').val())) {
}
else {
$('#input').val("");
}
});````
You have to wrap all the input elements in <form></form> and use jquery Validate plugin. Refer this link: http://jqueryvalidation.org/validate/ for detailed explanation
How about doing something like this?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<form id="form">
<label for="name">Name: </label>
<input type="text" name="name">
<div id="error"></div>
</form>
<script>
;(function($){
$.fn.extend({
donetyping: function(callback,timeout){
timeout = timeout || 1e3; // 1 second default timeout
var timeoutReference,
doneTyping = function(el){
if (!timeoutReference) return;
timeoutReference = null;
callback.call(el);
};
return this.each(function(i,el){
var $el = $(el);
// Chrome Fix (Use keyup over keypress to detect backspace)
// thank you #palerdot
$el.is(':input') && $el.on('keyup keypress paste',function(e){
// This catches the backspace button in chrome, but also prevents
// the event from triggering too preemptively. Without this line,
// using tab/shift+tab will make the focused element fire the callback.
if (e.type=='keyup' && e.keyCode!=8) return;
// Check if timeout has been set. If it has, "reset" the clock and
// start over again.
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function(){
// if we made it here, our timeout has elapsed. Fire the
// callback
doneTyping(el);
}, timeout);
}).on('blur',function(){
// If we can, fire the event since we're leaving the field
doneTyping(el);
});
});
}
});
})(jQuery);
function validate(value) {
var regex = /\d/g;
if (regex.test(value)) {
$('#error').text('Only text allowed!');
} else {
$('#error').empty();
}
}
$('input[name=name]').donetyping(function(e){
validate($(this).val());
});
</script>
</body>
</html>
Credits to this https://stackoverflow.com/a/14042239/9379378
//jquery validation booking page
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='book']").validate({
//on key up validation
onkeyup: function(element) {
$(element).valid();
},
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
fname: {
required: true,
lettersonly: true
},
lname:{
required: true,
lettersonly: true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
fname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
lname: {
required:"Please enter your lastname",
lettersonly:"Letters allowed only"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
This question already exists:
jQuery show/hide form with jQuery validate plugin working on last shown div only
Closed 4 years ago.
I am trying to validate my form that is a jQuery show/hide form. jQuery validate plugin only validates my last input on the last div (input type file). I can currently upload an image and submit the form successfully with the remaining inputs empty.
Below is the third div and when i click post ad with no inputs filled in, "This field is required" is shown.
Below is the first div with no validation messages
Below is the second div with no validation messages
Here is my form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Zootopia</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
</head>
<body>
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title" required>
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
Here is my JavaScript:
$(document).ready(function(){
$("#ad_section2").click(function(){
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
$("#ad_form").validate({
rules:{
ad_title:{
required: true
},
description:{
required: true
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title"
},
description: {
required: "please enter a description"
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
})
Here is my CSS:
#ad_form_section2,
#ad_form_section3{
display: none;
}
You need to add a condition before you show/hide next fields
if ( $('field-id').valid() ) {
// Code
}
For example:
$("#ad_section2").click(function(){
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
Also, don't forget to set character encoding to avoid characters range error, Add the following code just below <head> tag:
<meta charset="UTF-8">
Form Example:
$(document).ready(function(){
$("#ad_form").validate({
rules:{
ad_title:{
required: true,
minlength: 3, // set minimum title length
},
description:{
required: true,
minlength: 10,
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title",
minlength: "Your title must be more than 3 characters!",
},
description: {
required: "please enter a description",
minlength: "Your description must be at least 10 characters long",
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
$("#ad_section2").click(function(){
// Check if valid before show/hide
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
// Check if valid before show/hide
if ($('#location_ad').valid()) {
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
}
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
});
#ad_form_section2,
#ad_form_section3 {
display: none;
}
label.error {
color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<div class="container">
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title">
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
</div>
More examples from documentation
By default the plugin is going to ignore any/all fields that are hidden. You have to set to the ignore option to "nothing".
$("#ad_form").validate({
ignore: [], // ignore nothing, validate everything
rules:{
ad_title:{ ....
If you're expecting validation when you show/hide sections of the form, that's not how it works. You're going to have to programmatically trigger validation on the relevant fields as you click back and forth. Use the .valid() method for this.
However, multi-step validation can quickly get tedious so you may have to re-think your entire approach. I personally like to enclose each section within its own set of <form></form> tags so I can control validation on each step separately.
Here's one example:
https://stackoverflow.com/a/20481497/594235
I have one subscription form with ajax. The problem is that success and error messages are always on the page. Why they are on the page and how to hide them until form is submitted?
This is my js function
$(document).ready(function(){
(function($) {
"use strict";
// validate subscribeForm form
$(function() {
$('#subscribeForm').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
}
},
messages: {
name: {
required: "Please enter your name?",
minlength: "Your name must consist of at least 4 characters"
},
email: {
required: "Please enter your email address"
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"subscribe.php",
success: function() {
$('#subscribeForm :input').attr('disabled', 'disabled');
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#sub_success').fadeIn();
});
},
error: function() {
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$('#sub_error').fadeIn();
});
}
})
}
})
})
})(jQuery)
})
And this is the form
<div class="footer-newsletter row footer-widget right-box">
<h3 class="footer-title">newsletter sign up</h3>
<form class="form-inline newsletter-form" id="subscribeForm" method="post" action="">
<input type="text" id="name" name="name" class="form-control" placeholder="Name">
<input type="email" id="email" name="email" class="form-control" placeholder="Email">
<button type="submit" class="btn btn-primary" name="sub_submit">Submit</button>
</form>
<div id="sub_success">You subscribe succesfully!</div>
<div id="sub_error">Opps! There is something wrong. Please try again</div>
</div>
So sub_success and sub_error are always on the page..
Change this following things in your code:-
<div id="sub_success" style="display:none">You subscribe succesfully!</div>
<div id="sub_error" style="display:none">Opps! There is something wrong. Please try again</div>
use this type alert it will gone in 3sec
$('#success_message').fadeIn(1000).html("<div class='alert alert-danger' role='alert' style='font-size: 15px;'>Soory some there is some error,please enter again data...</div>").fadeOut(3000);
Just add .hide on document.ready for both elements as below:
$(document).ready(function(){
$('.sub_success,.sub_error').hide();
});
You could just write a css
#sub_success, #sub_error {display:none}
then with jquery you can just show and hide by using
$("#sub_success").show();
$("#sub_error").hide();
I am using bootstrap3 form with jquery/javascript to validate input. This was taken from here
Here is part of my form:
<form id="contact-form" action="#" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="sr-only" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge form-control" name="name" id="name" placeholder="Your Name">
</div>
</div>
<div class="form-group">
<label class="sr-only" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge form-control" name="email" id="email" placeholder="Email">
Here is the javascript:
<script>
$(document).ready(function(){
jQuery.validator.setDefaults({
errorClass: "help-block"
});
$('#contact-form').validate({
rules: {
name: {
minlength: 3,
regex: "/^[A-Za-z\']*$/",
required: true
},
email: {
required: true,
email: true
},
subject: {
minlength: 2,
required: true
},
message: {
minlength: 2,
maxlength: 400,
required: true
}
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
}); // end document.ready
</script>
The required field and number of digits work wonderfully well. I also intend to add further validation, for example, accept alphabets in name field. I have tried using regex but does not seem to be working.
how to use regex (or multiple) validation in this type of javascript validation ?
how to give appropriate error message when a field has multiple validations (only alphabets and more than 3 characters) ?
I am very new to web development, so these might appear noob questions. Just getting hands on html now. Please guide in right direction.
For email you should add something like this:
$.validator.addMethod("email", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
}, "Invalid email address");
then rules for email should be:
email: "required email",
How can I have 2 inputs instead of just one in Bootstrap's Bootbox?
I need to receive 2 values in a modal dialog.
Actually, there is a simpler way which doesn't require you to modify bootbox code.
The string you pass at the bootbox creation doesn't have to be only text: it can also be html code. That means you can include pretty much everything in the box.
To put a custom form in a bootbox, you can then create it as follow :
bootbox.confirm("<form id='infos' action=''>\
First name:<input type='text' name='first_name' /><br/>\
Last name:<input type='text' name='last_name' />\
</form>", function(result) {
if(result)
$('#infos').submit();
});
I just made function for that, check it out - here
Usage example
bootbox.form({
title: 'User details',
fields: {
name: {
label: 'Name',
value: 'John Connor',
type: 'text'
},
email: {
label: 'E-mail',
type: 'email',
value: 'johnconnor#skynet.com'
},
type: {
label: 'Type',
type: 'select',
options: [
{value: 1, text: 'Human'},
{value: 2, text: 'Robot'}
]
},
alive: {
label: 'Is alive',
type: 'checkbox',
value: true
},
loves: {
label: 'Loves',
type: 'checkbox',
value: ['bike','mom','vg'],
options: [
{value: 'bike', text: 'Motorbike'},
{value: 'mom', text: 'His mom'},
{value: 'vg', text: 'Video games'},
{value: 'kill', text: 'Killing people'}
]
},
passwd: {
label: 'Password',
type: 'password'
},
desc: {
label: 'Description',
type: 'textarea'
}
},
callback: function (values) {
console.log(values)
}
})
For me, this is the cleanest way to do it :
var form = $('<form><input name="usernameInput"/></form>');
bootbox.alert(form,function(){
var username = form.find('input[name=usernameInput]').val();
console.log(username);
});
Create hidden div with form in HTML and inject this html to bootbox message. Snippet below.
var buttonClick = function() {
var bootboxHtml = $('#js-exampleDiv').html().replace('js-exampleForm', 'js-bootboxForm');
bootbox.confirm(bootboxHtml, function(result) {
console.log($('#ex1', '.js-bootboxForm').val());
console.log($('#ex2', '.js-bootboxForm').val());
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
<div id="js-exampleDiv" hidden>
<form class="js-exampleForm">
<div class="col-sm-12">
<input placeholder="Example placeholder 1" id="ex1" />
</div>
<div class="col-sm-12">
<input placeholder="Example placeholder 2" id="ex2" />
</div>
</form>
</div>
<button onclick="buttonClick();">
Open bootbox confirm dialog.
</button>
You have to write your own function which will load dialog function from bootbox.
The easiest way is to copy prompt function from source: https://raw.github.com/makeusabrew/bootbox/v3.2.0/bootbox.js
and change this part for adding new input (or whatever you need)
// let's keep a reference to the form object for later
var form = $("<form></form>");
form.append("<input autocomplete=off type=text value='" + defaultVal + "' />");
and this part for getting result:
var confirmCallback = function() {
if (typeof cb === 'function') {
return cb(form.find("input[type=text]").val());
}
};
Here is a basic example for what you need (using knockout)
<button data-bind="click: select">Button</button>
<script type="text/html" id="add-template">
<div style="display:none">
<input data-bind='value: name' placeholder="Name">
</div>
</script>
var viewModel = function () {
var self = this;
self.name = ko.observable();
self.select = function () {
var messageTemplate = $($("#add-template").html());
ko.applyBindings(self, messageTemplate.get(0));
messageTemplate.show();
bootbox.confirm({
title: "Add new",
message: messageTemplate,
callback: function (value) {
// do something
}
});
}
}
ko.applyBindings(new viewModel());
Just add as many fields and bind them in the view model
http://jsfiddle.net/6vb7e224/2/
haradwaith Has the best solution for posting form data from a bootbox. Because it works, it's simple and because he demonstrates how to Actually Submit the Form. His solution:
bootbox.confirm("<form id='infos' action=''>\
First name:<input type='text' name='first_name' /><br/>\
Last name:<input type='text' name='last_name' />\
</form>", function(result) {
if(result)
$('#infos').submit();
});
Moving the <form> tag outside of the bootbox object allows the use of PHP when posting to self and to include hidden inputs without all the clutter.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="infos">
<input type=hidden form="infos" name="created" value="<?php echo date("Y-m-d H:i:s"); ?>" />
</form>
Now you can check for $_POST['created']
<?php
if(isset($_POST['created'])){
echo "Timestamp: ".$_POST['created']; // great things happen here
}
?>
You can create the form anywhere in the body tag, it won't display because the inputs are hidden.
Hope that helps!
I know this question is pretty old now, but this is the way I've done it. I think this way is great for larger forms as putting all of the HTML in JavaScript can get ugly pretty quick.
This example uses Bootstrap but the idea is the same. Create a hidden form in HTML and then select it using JavaScript or JQuery.
HTML:
<div id="hiddenForm" class="hidden">
<form id="myForm" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="FirstName" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="LastName" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">City</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="City" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">State</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="State" />
</div>
</div>
</form>
</div>
JavaScript Version:
var form = document.getElementById("hiddenForm").innerHTML;
bootbox.confirm({
message: form,
callback: function (result) {
// do something
}
});
JQuery Version:
var form = $("#hiddenForm").html();
bootbox.confirm({
message: form,
callback: function (result) {
// do something
}
});
Note:
When you try to serialize the form for posting, you'll have to make sure you are actually targeting the right form. $("#myForm").serialize() will most likely not work as it will grab the actual HTML form that you built earlier. So instead, you should do something like $(".bootbox-body #myForm").serialize() to get the current form's values.