Setting a Bootstrap 3 modal title dynamically - javascript

I have the same modal dialog for three different buttons.
However, depending upon which button is clicked, I need to dynamically set the title of the modal dialog.
I thought this would be simple setting the title in the appropriate javascript function using jQuery. However, when debugging, I can see the title is set accordingly in the code, but after the modal is displayed, the modal title is blank.
How can I properly display the modal title accordingly?
Here is the pertinent part of the HTML:
<div class="modal fade" id="btnJournalVoucherEditGrid" tabindex="-1" role="dialog" aria-labelledby="btnJournalVoucherEditGrid-label" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="btnJournalVoucherEditGrid-label"></h4>
Here is the JS
function onEditJournalVoucher(gdId, rwID)
{
$('#btnJournalVoucherEditGrid-label').val("Edit Journal Voucher")

Well, you're trying to use .val() on an H4 tag. Should it not be:
$('#btnJournalVoucherEditGrid-label').text("Edit Journal Voucher");
or
$('#btnJournalVoucherEditGrid-label').html("Edit Journal Voucher");
.val() is the right mindset, but what it does in JQuery is why it won't work in this situation. Take an element that has a value="something" attribute, for example:
<input id="example" type="text" name="something" value="something"/>
Targeting this id using $("#example") and calling .val() can access or change the value="something" attribute. Now take a look at a <label> element:
<label id="example"> This is some text </label>
Notice the lack of a value="something" attribute? In this case, since "This is some text" is simply plain-text, using:
$("#example").text("Updated Text");
is the correct way to go about this. Hope that helps clear things up!

.val() is used for form elements (like inputs, checkboxes, etc.)
For divs/other elements (e.g. h4 in your situation) use either .text() or .html() depending on the situation you want to do.
In this case since this is just text change your line to:
$('#btnJournalVoucherEditGrid-label').text("Edit Journal Voucher");

It should be
function onEditJournalVoucher(gdId, rwID)
{
$('#btnJournalVoucherEditGrid-label').html("Edit Journal Voucher")

Try text() function instead of val():
$('#btnJournalVoucherEditGrid-label').text("Edit Journal Voucher")

I would set the title in the button:
<button id="edit-journal-voucher" data-title="Edit Journal Voucher" data-toggle="modal" data-target="#btnJournalVoucherEditGrid">Edit this Journal</button>
Then in the JS do something like:
$("#edit-journal-voucher").on("click", funtion(e){
e.preventDefault();
var title = $(this).data('title');
$("h4#btnJournalVoucherEditGrid-label").html(title);
});

Related

Jquery replaceWith(html) not replacing element; appending it to end instead

I have the following HTML. Its a form inside of a modal window:
<div class="modal fade" id="requestModal" tabindex="-1" role="dialog" aria-labelledby="requestModalLabel">
<div class="modal-dialog wide-modal" role="document">
<form novalidate>
<div class="modal-content">
....
</div>
</form>
</div>
</div>
Whenever the form is opened, I want to render a fresh version of the form, free of any old inputs or error messages. The following handler gets the data for hidden fields plus the form's HTML I can obtain the data for the form along with the raw HTML for the form via an Ajax request:
$(document).on('click', '#por-detail-tbl .dropdown-menu', e => {
// This route will get fresh form HTML also.
$.get(`/projects/${$(e.target).attr('project-id')}`, res => {
$('#requestModal').replaceWith(res.html)
...more code here to populate hidden fields...
})
})
I would expect the $('#requestModal') element to be replaced with whatever res.html is (in this case, a new version of the form). Instead, res.html is getting inserted as the last element in the document body. The old $('#requestModal') is still there.
Here is a snippet from res.html:
<div class="modal fade" id="requestModal" tabindex="-1" role="dialog" aria-labelledby="requestModalLabel">
<div class="modal-dialog wide-modal" role="document">
<form novalidate>
<div class="modal-content">
...
</div>
</form>
<div>
</div>
I'm able to use this technique successfully in other Ajax callbacks. Any ideas why this one is behaving strangely?
You actually want jQuery's .html() function here.
In your original code, the replaceWith() function replaces $('#requestModal'). But the element you replaced is the element that's been manipulated by Bootstrap to perform the modal behavior you expect.
So I think you really want to set the content of the div.modal-dialog element to just the form and its children. If you can pare down res.html to just the form and children, you can change $('#requestModal').replaceWith(res.html) to $('#requestModal').find('div.modal-dialog').html(res.html).

Getting data from text file via data-src using jQuery

I am trying to retrieve text from a .txt file using jQuery (I am also using Bootstrap). I am very new to web design but I am familiar somewhat with coding. I have the following button in my HTML:
<button type="button" class="btn btn-primary-outline-btn text-btn" data-toggle="modal" data-src="test.txt" data-target="#textModal"><img class="video_icon" src="assets/icons/parchment_icon.png" alt="text"</button>
As you can see, the target of the button is a modal which loads up text like so:
<!-- Text Modal -->
<div class="modal fade" id="textModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p id="outputText">File not found.</p>
</div>
</div>
</div>
</div>
My JS file looks like this (changed following one of the answers):
$(".text-btn").on("click", textFunction);
function textFunction() {
var el = document.getElementById('test');
console.log(el.getAttribute('data-src'));
jQuery.get(el.getAttribute('data-src'), function(data) {
$( '#outputText' ).html(data.replace('n',''));
});
}
Whilst the filepath outputs to the console correctly, I am unsure how to use jQuery to utilise this so that it will input the file contents into the modal-body. Additionally, my issue is now how to make the variable assigned through getElementById correctly correspond to the button pressed. Moreover, I am not sure how to use getAttribute or attr in jQuery to obtain the data source in javascript.
This is an issue as I will have multiple buttons with multiple file sources so I would like the jQuery to retrieve from each button's respective data source. Is there a way in which I can do this...?
You have to set the full file url in data-src then use:
$('.text-btn').on('click', function() {
$.get($(this).data('src'), function(data) {
$('#outputText').html(data);
});
});
For the case of multiple buttons, you can use an onclick event on each, which will fire textFunction. Then, inside the text function, you can retrieve the correct button's data-src using jQuery's data() function:
//assuming all your relevant buttons have class `text-btn`
//call textFunction on button click
$(".text-btn").on("click", textFunction);
function textFunction() {
//inside event handler, `this` points to the button that triggered the event
jQuery.get($(this).data('src'), function(data) {
alert(data);
$( '#outputText' ).html(data.replace('n',''));
});
}

How to change an href attribute through Javascript on a modal window

I've been searching and trying different ways to change an href attribute through Javascript. Few things have worked better than others.
The problem with this approach is that the variable on the href is not working. I guess there is a better way to include a variable within an html tag.
I'm really stuck on this so would appreciate any help.
Here is the code of the modal window:
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
<h1>¿Quieres seguir creando?</h1>
<a class="btn-ok" href=enlace target="_blank">OK</a>
</div>
</div>
And this the button that the user clicks on before the modal window is shown:
<script type="text/javascript">
var enlace;
</script>
<button onclick="enlace='https://cloqq.com/actividad/tu-aventura-interactiva';return false" id="" class="go-btn pink-bg">Empieza a crear
</button>
https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
You can use setAttribute to reassign the href, the way you're using javascript in html doesnt work like that.
const itemYouWantToUpdateHref = document.querySelector('.btn-ok')
function changeHref(link) {
itemYouWantToUpdateHref.setAttribute('href', link);
}
<a class="btn-ok" href="www.google.com" target="_blank">My link will change</a>
<button onclick="changeHref('www.youtube.com')">click to change href from google to youtube</button>
You can use your code itself with only some changes and without any script tag. look at code below:
<button onclick="window.enlace='https://cloqq.com/actividad/tu-aventura-interactiva'" class="go-btn pink-bg">Empieza a crear</button>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
<h1>¿Quieres seguir creando?</h1>
<a class="btn-ok" href="javascript:window.open(window.enlace||'defaultAddress', '_blank');">OK</a>
<!--
!! If you like to show an alert when the button is not clicked yet, try line below instead above line:
<a class="btn-ok" href="javascript:window.enlace?window.open(window.enlace, '_blank'):alert('Please click the Button first!');">OK</a>
-->
</div>
</div>
If you run above snippet and look at console, you can see all things is fine (but because Security problems this will not work with these URLs in current page and you should copy it in your project or an empty html file for seeing the result.)

Bootstrap $('#myModal').modal('show') is not working

I'm not sure why but all the modal functions are not working with me.
I checked the version and the load they are fine.
I keep getting this error message:
Uncaught TypeError: $(...).modal is not a function
for the hide I already found an alternative.
instead of:
$('#myModal').modal('hide');
I used this :
$('#myModal .close').click();
And it works perfectly.
The problem now is with the show
$('#myModal').modal("show");
I also tried both
$('#myModal').modal("toggle");
And:
$('#myModal').modal();
but unfortunately none of them is working.
Here html code -when the button is clicked I will do some verification and handle a json data from the web service if it succeed then I want show my modal- everything is working except the show.
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
if there's any alternative I would like to know it.
Most common reason for such problems are
1.If you have defined the jquery library more than once.
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
The bootstrap library gets applied to the first jquery library but when you reload the jquery library, the original bootstrap load is lost(Modal function is in bootstrap).
2.Please wrap your JavaScript code inside
$(document).ready(function(){});
3.Please check if the id of the modal is same
as the one you have defined for the component(Also check for duplication's of same id ).
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
Note: Remove fade class from the div and enjoy it should be worked
This can happen for a few reasons:
You forgot to include Jquery library in the document
You included the Jquery library more than once in the document
You forgot to include bootstrap.js library in the document
The versions of your Javascript and Bootstrap does not match. Refer bootstrap documentation to make sure the versions are matching
The modal <div> is missing the modal class
The id of the modal <div> is incorrect. (eg: you wrongly prepended # in the id of the <div>)
# sign is missing in the Jquery selector
I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'),
`
<button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
$('#btnPurchaseClose').trigger('click');// for close popup
$('#btnOpenPurchase').trigger('click');`// for open popup
My root cause was that I forgot to add the # before the id name. Lame but true.
From
$('scheduleModal').modal('show');
To
$('#scheduleModal').modal('show');
For your reference, the code sequence that works for me is
<script>
function scheduleRequest() {
$('#scheduleModal').modal('show');
}
</script>
<script src="<c:url value="/resources/bootstrap/js/bootstrap.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/fastclick/fastclick.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/slimScroll/jquery.slimscroll.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/jquery.dataTables.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/dataTables.bootstrap.min.js"/>">
</script>
<script src="<c:url value="/resources/dist/js/demo.js"/>">
</script>
Use .modal({show:true}) and .modal({show:false}) instead of ('show') and ('hide') ... it seems to be bootstrap / jquery version combination dependent. Hope it helps.
the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).
I wasted two days in finding this problem.
Please,
try and check if the triggering button has attribute type="button".
Working example:
<button type="button" id="trigger" style="visibility:visible;" onclick="modal_btn_click()">Trigger Modal Click</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script >
function modal_btn_click() {
$('#myModal').modal({ show: true });
}
</script>
Try This without paramater
$('#myModal').modal();
it should be worked
are you sure that the id of the modal is "myModal"? if not then the call will not trigger it.
also - just from reading your post - you are triggering a function / validation with this button
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
and then if all is well - you want to trigger the modal. - if this is hte case - then you should remove the toggle from this button click. I presume you have an event handler tied to this click? you need the .modal("show") as a part of that function. not toggled from this button. also - is this id correct "creatNewAcount" as opposed to this spelling "createNewAccount"
<button type="button" id="creatNewAcount" class="btn btn-default" >Sign up</button>
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
the first googleapis script is not working now a days use this second scripe given by jquery
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
Please also make sure that the modal div is nested inside your <body> element.
After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.
Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using
setTimeout(() => { $('#modalID').modal('show'); }, 500);
Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it
In my case, bootstrap.css and bootstrap.js versions are mismatched.
It is working if I remove the fade class. But the background is disappeared.
I added the same version of bootstrap files. Now it is working perfectly.
Thank you #Mohammed Shareef C.
Another use case that may be the cuplrit
My problem was that I had a jquery selector that was using a variable that was not assigned immediately.
My modal had a dynamic ID
<div class="modal fade" id="{{scope.modalId}}"... >
This is in angularJS, so the valud of scope.modalID wasn't being bound until $scope.onInit
vm.$onInit = function () {
$( `#${vm.modalId}` ).on('shown.bs.modal', function(){
console.log('WORKS')
});
zzz
Make sure your script tag is closed with another script tag like below
before
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"/>
After
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

time-picker in bootstrap modal dialog

I am trying to implement a time-picker in a boostrap modal dialog. However when I open the dialog the time-picker still looks like a normal text field which makes me believe that this jquery code is not running:
$('#timepicker1').timepicker(); // shown below
However I am able to get the time-picker to display using very similar code on a normal webpage. The problem seems specific to displaying it in a modal dialog.
Here is a link to the time-picker that I am using:
http://jdewit.github.io/bootstrap-timepicker/
Here is my modal dialog:
<div class="modal fade" id="dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">close</button>
<h4 class="modal-title" id="myModalLabel">New Event</h4>
</div>
<div class="modal-body">
<div class="input-append bootstrap-timepicker">
<input id="timepicker1" type="text" class="input-small">
<span class="add-on"><i class="icon-time"></i></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Here is my script that is suppose to initialize the time-picker
$( document ).ready(function() {
//$('#table').editableTableWidget();
$( "#btn-new-event" ).click(function() {
$('#dialog').modal('show');
$('#timepicker1').timepicker(); // not running properly
});
});
Any help would be greatly appreciated!
For me, I had to do this to make it work:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 99999!important;
}
and of course, remove:
template: 'modal'
ibrahimyilmaz gave you the right answer, exactly as shown on the bootstrap timepicker official site.
The only thing that maybe serves as a more precise indication here is that timepicker only works with bootstrap v2.x.
If you want to use bootstrap 3.x, you have to read the migration doc and perform the required changes. If you need help on that, just give me a sign :) Or use timepicker bootstrap3 wich is a fork of the one you have used.
Check this link example to see a working example. Check on the +view Source link to see all the required scripts and links.
Hope it's useful!
$('#timepicker1').timepicker({
template: 'modal'
});
It's a reported bug https://github.com/jdewit/bootstrap-timepicker/issues/326
you have to change the z-order as mentioned by #eugene1832:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 1050!important;
}
AND you also need to remove the initialization option:
template: 'modal'
To update the answers to this question: bootstrap-timepicker now supports Bootstrap 3, but this issue with modals is a known bug.
The bug is still open at this time, but one user suggested adding this piece of code to your css file to make the timepicker visible:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 1050!important;
}
I would note that this solution did not work for me, but it is currently listed as a possible solution. I'll try to update this response when the issue is either resolved on Github or when someone suggests another method.
Add this code for line #666 in bootstrap-timepicker.js file. It's work for me
var index_highest = 0;
$(".modal").each(function() {
// always use a radix when using parseInt
var index_current = parseInt($(this).css("zIndex"), 10);
if (index_current > index_highest) {
index_highest = index_current;
}
});
var zIndex = parseInt(this.$element.parents().filter(function() { return $(this).css('z-index') !== 'auto'; }).first().css('z-index'), 10) + index_highest;

Categories

Resources