Question

How can I have 2 inputs instead of just one in Bootstrap's Bootbox?

I need to receive 2 values in a modal dialog.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top