How to use Bootstrap tooltip on input elements?

2019-01-31 07:33发布

问题:

I'm not 100% sure this is at all possible, because input doesn't have a rel attribute (the example on the Bootstrap website shows only 1 example with rel="tooltip"), but I think it should work.

This is my HTML:

<input id="password" type="password" /> 

And this is how I try to trigger it:

$(document).ready(function () {

    $('input[id=password]').tooltip({'trigger':'focus'});
});

And I also tried this:

$('#password').tooltip({'trigger':'focus'});

And none of them seem to work. I eventually want to trigger it manually, but this is the first step. Does anybody know a solution for this? Is it possible at all? Thanks.

回答1:

Try to specify "title" parameter to tooltip. Like:

$('#password').tooltip({'trigger':'focus', 'title': 'Password tooltip'});

Btw, that's nothing wrong with input element having "rel" attribute.



回答2:

In case anyone wants to know more generic tooltip option for the all the text boxes

$(document).ready(function() {
  $('input[rel="txtTooltip"]').tooltip();
});
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" rel="txtTooltip" title="**Your Title**" data-toggle="tooltip" data-placement="bottom">



回答3:

This may be useful for those having multiple input fields, so you don't end up calling several tooltip(),

Just do this, this is based on ID of input field, you could have it to work as class too;

$('input').each(function (i, e) {
    var label;
    switch ($(e).attr('id')) {
        case 'input-one':
            label = 'This is input #1';
            break;
        case 'input-two':
            label = 'This is input #2';
            break;
    }
    $(e).tooltip({ 'trigger': 'focus', 'title': label });
});

Hope it helps :)



回答4:

Boostrap 3 and 4

Based on @Senthil's response, and using bootstrap 3.x or 4.x and JQuery, this will set tooltips for all input elements as long as the title property is set without the need of the rel attribute.

HTML:

<input class="form-control" id="inputTestID" name="inputTest" placeholder="Test" type="text" data-placement="bottom" title="Tooltip Text">

Javascript:

$(document).ready(function(){
  $('input').tooltip();
});

CSS:

.tooltip-inner {
  background-color: #fff; 
  color: #000;
  border: 1px solid #000;
}
  • Bootstrap 3 Fiddle.
  • Bootstrap 4 Fiddle.