Multiple inputs in a Bootbox - javascript

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.

Related

how to trigger same name class only on current input text box in jquery plugin?

hello i am creating ajax search plugin.I have created some dynamically div. suppose I have two input box field and the div which is dynamically generated have same name . So I want to project only that div in which user enter the value on text box not other, but it fetch result on both div whether I type on first or second input box.
HTML
<div class="row" style="padding:10px">
<div class="col-md-6">
<input type="text" class="form-control" name="" value="" id="searchText1">
</div>
<div class="col-md-6">
<input type="text" class="form-control" name="" value="" id="searchText2">
</div>
</div>
js file
$(document).ready(function(){
$('#searchText1').typefast({
hint:true,
autocomplete:true,
});
$('#searchText2').typefast({
hint:true,
autocomplete:true,
});
jquery plugin file
var timeOut = null;
var $current;
var $info;
var input;
var hint;
var comment;
(function( $ ) {
$.fn.typefast = function(a){
$(this).one('keydown',function(){
input=$(this);
$('body').bodyAppend($(this));
$(this).css({
'position': 'relative',
'top': '-34px',
'background': 'transparent',
'padding-left': '11px',
'font-size': '16px'
})
$('<div>').attr({
name: 'comment',
class: 'comment'
}).insertAfter($(this));
comment=$(this);
})
$(this).on('keydown',function (e) {
var _this = $(this);
clearTimeout(timeOut);
timeOut = setTimeout(function() {
var m = _this.val();
api.searchResult(m,e);
// console.log(ui.input);
console.log(m);
},500);
})
$.fn.bodyAppend=function(m) {
$(window).ready(function() {
$('<input>').attr({
type: 'text',
name: 'input1',
class: 'form-control',
id:'result',
placeholder: 'working'
}).insertBefore(m);
hint=$('#result')
single=$('.single')
})
}
};
}( jQuery ));
My Question is that irrespective of number of input text field on page. My comment should point only the current input box in which I am on working. It should not update the other comment field
class single is the field in which ajax request result displayed.
What is the best way of doing this??
For this case you can set one common class to all input field and apply typefast function on focus event to that class.
For Example,
HTML code
<div class="col-md-6">
<input type="text" class="form-control searchtext" name="" value="" >
</div>
<div class="col-md-6">
<input type="text" class="form-control searchtext" name="" value="" >
</div>
Javascript Code,
$(document).ready(function () {
$(document).on("focus", ".searchtext", function () {
$($(this)).typefast({
hint: true,
autocomplete: true,
});
});
});

jQuery validation did not work?

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"
}
}
});

how to validate element is angular js?

I make a view from json object. I am able to make take now I need to valid element on keyup event and blur event. So I googled it and find this tutorial
http://scotch.io/tutorials/javascript/angularjs-form-validation
I try to implement this in my demo, but when I used this:
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine"
class="help-block">`Your name is required.</p>
This break my view can you please tell me how to validate thing in angular if there is no form?
Here is my plunker: http://plnkr.co/edit/we1QHuDuCOOR4tDAk6yv?p=preview
<script>
function Controller($scope) {
$scope.outputs = {};
$scope.inputs = [{
type: "email",
name: "email",
required:true
}, {
type: "text",
name: "name",
}, {
type: "number",
name: "phonenumber",
}, {
type: "checkbox",
name: "whant to check",
},
{
type: "url",
name: "server Url",
}];
}
</script>
A solution is to use ng-form like
<div ng-switch="input.type" ng-form="myfrm">
<div ng-switch-when="text">
<input type="text" ng-model="outputs[input.name]"/>
</div>
<div ng-switch-when="email">
<input type="email" ng-model="outputs[input.name]" name="input" ng-required="input.required">
<span ng-if="myfrm.input.$invalid">Please enter a valid email</span>
</div>
<div ng-switch-when="number">
<input type="number" ng-model="outputs[input.name]"/>
</div>
<div ng-switch-when="url">
<input type="number" ng-model="outputs[input.name]"/>
</div>
<div ng-switch-when="checkbox">
<input type="checkbox" ng-model="outputs[input.name]" ng-checked="outputs[input.name]" value="outputs[input.name]"/>
</div>
</div>
Demo: Plunker

I can't reach dynamic inputs with javascript

I want to change Cloudera Hue project code but I have some problems.
Knockout data-bind is created some html codes with foreach , when I want to reach input in this html, my code does not work correct. My app.mako file code :
.....
<div data-bind="foreach: submissionVariables" style="margin-bottom: 20px">
<div class="row-fluid">
<span data-bind="text: name" class="span3"></span>
<input type="text" data-bind="value: value,attr: { id: 'dtpicker' + name }" class="span9" />
<button class="btn fileChooserBtn" data-bind="click: $root.showTimePicker">time</button>
</div>
</div>
<input type="text" value="2014/03/15 05:06" id="datetimepickerz"/>
....
<script src="/static/js/jquery.datetimepicker.js"></script>
<script type="text/javascript">
$('#dtpickerfolder').datetimepicker()
.datetimepicker({value:'2015/04/15 05:03',step:10});
$('#dtpickereverything').datetimepicker()
.datetimepicker({value:'2015/04/15 05:03',step:10});
$('#datetimepickerz').datetimepicker()
.datetimepicker({value:'2015/04/15 05:03',step:10});
</script>
Output:
<input id="dtpickerfolder" class="span9" type="text" data-bind="value: value,attr: { id: 'dtpicker' + name }"></input>
<input id="dtpickereverything" class="span9" type="text" data-bind="value: value,attr: { id: 'dtpicker' + name }"></input>
<input id="datetimepickerz" type="text" value="2014/03/15 05:06"></input>
datetimepickerz input works correct but my dynamic inputs that ids starts with dtpicker are not working.
Can anyone help me ?
I solve this with :
self.runOrShowSubmissionModal = function runOrShowSubmissionModal() {
var script = self.currentScript();
if (! $.isEmptyObject(script.getParameters())) {
self.submissionVariables.removeAll();
$.each(script.getParameters(), function (key, value) {
self.submissionVariables.push({'name': key, 'value': value});
// CALL TO JQUERY
$("#dtpicker"+key).datetimepicker({value:"2015/04/15 05:03",step:10});
});
$("#runScriptBtn").button("reset");
$("#runScriptBtn").attr("data-loading-text", $("#runScriptBtn").text() + " ...");
$("#submitModal").modal({
keyboard: true,
show: true
});
} else {
self.runScript();
}
};
I sent my jquery in knockout function.

get form data by click and chart with the data in highchart

I want to load form data and send it to the sever then chart with the returned data. It works fine if the form's input field have default data and I comment
//$("button").click(function(){
I get no chart all if the default text fields are empty. I tried different ways but still I wont get it load from the form by clicking a button. I am stuck for 2 days now. Please, help. Thanks in advance. Here is the code
<script type="text/javascript">
var chart = null;
var dataString = [];
$(document).ready(function() {
$("button").click(function() {
$(function() {
var city1 = $("#city1").val();
var city2 = $("#city2").val();
dataString = {
city1: city1,
city2: city2
};
requestData();
});
});
function requestData() {
$.ajax({
url: 'array.php',
type: 'POST',
data: dataString,
success: function(point) {
var chartSeriesData = [];
var chartCategory = [];
$.each(point, function(i, item) {
var series_name = item.name;
var series_data = item.data2;
var cagory = series_name;
var series = {
name: series_name,
data: item.data2
};
chartSeriesData.push(series);
chartCategory.push(series_name);
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'column',
},
title: {
text: 'Real time data from database'
},
xAxis: {
categories: chartCategory
},
yAxis: {
minPadding: 0.1,
maxPadding: 0.1,
title: {
text: 'Value',
margin: 40
}
},
series: chartSeriesData
});
},
cache: false
});
}
});​
</script>
Here is the body section
<body>
<div id="container" style="min-width: 200px; height: 400px; margin: 0 auto"></div>
<div id="city_form">
<form name="contact" action="" method="post">
<label for="city1" id="city1_label">First city</label>
<input type="text" name="city1" id="city1" size="30" value="Amsterdam" />
<label for="city2" id="email_label">Second city</label>
<input type="text" name="city2" id="city2" size="30" value="London" />
<button>Click me</button>
</form>
</div>
</body>
</html>
You are doing a bunch of things incorrectly here, one as pointed out by wirey, other you have to prevent the form submission on click of the button. Eh? When you click the submit button, its default action is to submit the form and take you to the action page. You do have an added eventListener attached, which makes this ajax call and then plots the chart, but the button will still perform its default action, viz. take you to the action page, which in you case is the same page, so you don't even realize that such a thing happened, you may have noticed a flicker or page reload?
jQuery allows preventing this default action by calling the preventDefault() method on your event object, which gets passed to you event listener as the 1st argument. You can read more about it here http://api.jquery.com/event.preventDefault/
Try this and let us know if it helped.
HTML
<div id="city_form">
<form name="contact" action="" method="post">
<label for="city1" id="city1_label">First city</label>
<input type="text" name="city1" id="city1" size="30" value="Amsterdam" />
<label for="city2" id="email_label">Second city</label>
<input type="text" name="city2" id="city2" size="30" value="London" />
<button id="btnGet">Click me</button>
</form>
</div>
JS
$("#btnGet").click(function(evt) {
evt.preventDefault();
var city1 = $("#city1").val();
var city2 = $("#city2").val();
var dataString = {
city1: city1,
city2: city2
};
requestData(dataString);
});
jsFiddle # http://jsfiddle.net/jugal/V5zt9/6/

Categories