I have some modal forms to complete some fields, in this case I have 2 modal forms, 1 for Jury and 1 for Contact, when I press 'Add' link, in both cases works fine, but the problem is when I want to edit contact.
When I press Edit in both cases I call controller to complete the Java form and then, return to view and simulate a click in "Add" button with JQuery. In jury case works fine, but in Contact I only get a dark screen (like if modal works), but modal window never appear. Other problem is, when I press Edit button in Jury and then close the jury modal form, when I press Edit in Contact it launch the jury modal form...
Contact Modal and Add link (Edit link doesn't works)
<div class="row margin-top-10">
<div class="col-xs-2 col-md-2 col-md-push-10">
<a id="btnAddCForm" href="#modal-cForm-form" data-toggle="modal" class="btn fpa btn-block pull-right">AÑADIR NUEVO</a>
</div>
</div>
<div id="modal-cForm-form" class="modal fade" tabindex="-1" 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"></button>
<h4 class="modal-title">Nuevo/Editar Forma de contacto</h4>
</div>
<div class="modal-body">
<div class="scroller" style="height:390px" data-always-visible="1" data-rail-visible1="1">
Some fields
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn default">CANCELAR</button>
<button type="button" onclick="addContactForm();" class="btn fpa">ACEPTAR</button>
</div>
</div>
</div>
</div>
Jury Modal and Add link (Works fine)
<div class="row margin-top-10">
<div class="col-xs-2 col-md-2 col-md-push-10">
<a id="btnAddJurado" href="#modal-jury-form" data-toggle="modal" class="btn fpa btn-block pull-right">AÑADIR NUEVO</a>
</div>
</div>
<div id="modal-jury-form" class="modal fade" tabindex="-1" 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" onclick="resetValues();"></button>
<h4 class="modal-title">Nuevo/Editar Jurado</h4>
</div>
<div class="modal-body">
<div class="scroller" style="height:300px" data-always-visible="1" data-rail-visible1="1">
Some Fields
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" onclick="resetValues();" class="btn default">CANCELAR</button>
<button type="button" onclick="addJury();" class="btn fpa">ACEPTAR</button>
</div>
</div>
</div>
</div>
Onload (In main html document)
window.onload = function () {
/*<![CDATA[*/
var idJuryAux = /*[[${person.juryAux.id}]]*/
null;
var idContactFormAux = /*[[${person.contactFormAux.id}]]*/
null;
/*]]>*/
var idProvincia = $('#provinceField').val();
var idPais = $('#countryField').val();
if (idPais == '-1') {
$('#provinceField').attr("readonly", true);
} else {
$('#provinceField').attr("readonly", false);
}
if (idProvincia == '-1') {
$('#cityField').attr("readonly", true);
} else {
$('#cityField').attr("readonly", false);
}
if (idJuryAux != null) {
/*<![CDATA[*/
var idCat = /*[[${person.juryAux.category}]]*/
null;
var idCargo = /*[[${person.juryAux.juryType}]]*/
null;
var catName = /*[[${person.juryAux.categoryName}]]*/
null;
var cargoName = /*[[${person.juryAux.juryTypeName}]]*/
null;
/*]]>*/
$('#btnAddJurado').trigger('click');
$("#categoryField").select2('data', {
id: idCat,
text: catName
});
$("#juryTypeField").select2('data', {
id: idCargo,
text: cargoName
});
}
if (idContactFormAux != null) {
/*<![CDATA[*/
var idType = /*[[${person.contactFormAux.type}]]*/
null;
var typeName = /*[[${person.contactFormAux.typeName}]]*/
null;
var idTag = /*[[${person.contactFormAux.tag}]]*/
null;
var tagName = /*[[${person.contactFormAux.tagName}]]*/
null;
var idPais = /*[[${person.contactFormAux.country}]]*/
null;
var paisName = /*[[${person.contactFormAux.countryName}]]*/
null;
var idProvincia = /*[[${person.contactFormAux.province}]]*/
null;
var provName = /*[[${person.contactFormAux.provinceName}]]*/
null;
var idCity = /*[[${person.contactFormAux.city}]]*/
null;
var cityName = /*[[${person.contactFormAux.cityName}]]*/
null;
var idInst = /*[[${person.contactFormAux.institution}]]*/
null;
var instName = /*[[${person.contactFormAux.institutionNme}]]*/
null;
/*]]>*/
$('#btnAddCForm').trigger('click');
$("#typeField").select2('data', {
id: idType,
text: typeName
});
$("#tagField").select2('data', {
id: idTag,
text: tagName
});
$("#countryField").select2('data', {
id: idPais,
text: paisName
});
$("#provinceField").select2('data', {
id: idProvincia,
text: provName
});
$("#cityField").select2('data', {
id: idCity,
text: cityName
});
$("#institutionField").select2('data', {
id: idInst,
text: instName
});
}
}
P.S. addJury(); and addContactForm(); only closes modal window, both works fine!
EDIT: I'm still waiting for a response...
Related
I create a modal and inside I insert an input field. When I write inside this input field a product name term, it must appear all the terms.
On blank page, I can see for ap (apple terms) all the apple products, no problem my ajax works fine
Now inside a page with some html element, I call a modal when there is my input fields. In this case, the ajax complexion does not work and inside the console log / result, I see my input field and not the result about my request.
I do not understand where my error below the result with a picture.
My modal call : works very fine
<!-- Link trigger modal -->
<div class="row">
<div class="col-md-12">
<div class="form-group row">
<label for="<?php echo $this->getDef('text_select_products'); ?>" class="col-5 col-form-label"><?php echo $this->getDef('text_select_products'); ?></label>
<div class="col-md-5">
<a
href="<?php echo $this->link('SelectPopUpProducts'); ?>"
data-bs-toggle="modal" data-refresh="true"
data-bs-target="#myModal"><?php echo '<h4><i class="bi bi-plus-circle" title="' . $this->getDef('icon_edit') . '"></i></h4>'; ?></a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="te"></div>
</div>
</div> <!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div>
</div>
</div>
</div>
<script src="<?php echo this->link('modal_popup.js'); ?>"></script>
now my modal with the field displayed
<div class="col-md-12">
<div class="form-group row">
<label for="<?php echo $this->getDef('text_products_name') ; ?>" class="col-5 col-form-label"><?php echo $this->getDef('text_products_name') ; ?></label>
<div class="col-md-7">
<?php echo HTML::inputField('products_name', '', 'id="ajax_products_name" list="products_list" class="form-control"'); ?>
<datalist id="products_list"></datalist>
</div>
</div>
</div>
<?php $products_ajax = $this->link('ajax/products.php'); ?>
<script>
window.addEventListener("load", function(){
// Add a keyup event listener to our input element
document.getElementById('ajax_products_name').addEventListener("keyup", function(event){hinterManufacturer(event)});
// create one global XHR object
// so we can abort old requests when a new one is make
window.hinterManufacturerXHR = new XMLHttpRequest();
});
// Autocomplete for form
function hinterManufacturer(event) {
var input = event.target;
var ajax_products_name = document.getElementById('products_list'); //datalist id
// minimum number of characters before we start to generate suggestions
var min_characters = 0;
if (!isNaN(input.value) || input.value.length < min_characters ) {
return;
} else {
window.hinterManufacturerXHR.abort();
window.hinterManufacturerXHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse( this.responseText );
ajax_products_name.innerHTML = "";
response.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
option.value = item.id + ' - ' + item.name;//get name
option.hidden = item.id; //get id
ajax_products_name.appendChild(option);
});
}
};
window.hinterManufacturerXHR.open("GET", "<?php echo $products_ajax ; ?>?q=" + input.value, true);
window.hinterManufacturerXHR.send()
}
}
</script>
Addedd js open modal
$( document ).ready(function() {
$("#myModal").on("show.bs.modal", function(e) {
const link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
});
there the screen shot of the result.
console result
Maybe the event keyup never fires because the input ajax_products_name doesn't exists until shown.bs.modal event is fired.
Try:
$("#myModal").on("shown.bs.modal", function(ev) {
document.getElementById('ajax_products_name').addEventListener("keyup", function(event) {
hinterManufacturer(event)
});
})
Let's set up an example
$('#exampleModal').on('shown.bs.modal', function() {
// $('#myInput').trigger('focus')
console.log("modal opened, *now* can addEventListener to stuff within modal")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Anyway, The idea is to do the addEventListener on the ajax_products_name only after it's loaded. So given your new snippet, try this:
// instead of
$(this).find(".modal-body").load(link.attr("href"));
// do:
$(this).find(".modal-body").load(link.attr("href"), function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success") {
// now that modal is opened AND content loaded
document.getElementById('ajax_products_name').addEventListener("keyup", function(event) {
hinterManufacturer(event)
})
}
});
I have a page where multiple images are present and I want to make the users able to crop any of them so I made a for loop to make a modal for each image and I looped the js function also.
this is my modal.
{% for image in Patient_detail.images.all %}
<div class="modal fade" id="modalCrop{{image.pk}}">
<div class="modal-dialog">
<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>
<h4 class="modal-title">Crop the photo</h4>
</div>
<div class="modal-body">
<img src="" id="image{{image.pk}}" style="max-width: 100%;">
</div>
<div class="modal-footer">
<div class="btn-group pull-left" role="group">
<button type="button" class="btn btn-default js-zoom-in">
<span class="glyphicon glyphicon-zoom-in"></span>
</button>
<button type="button" class="btn btn-default js-zoom-out">
<span class="glyphicon glyphicon-zoom-out"></span>
</button>
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Nevermind</button>
<button type="button" class="btn btn-primary js-crop-and-upload">Crop and upload</button>
</div>
</div>
</div>
</div>
{% endfor %}
and here's the function I used
{% for image in Patient_detail.images.all %}
$(function () {
/* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */
$("#crop{{image.pk}}").click(function () {
var img_src = document.getElementById("img{{image.pk}}").src
$("#image{{image.pk}}").attr("src", img_src);
$("#modalCrop{{imahge.pk}}").modal("show");
}
});
/* SCRIPTS TO HANDLE THE CROPPER BOX */
var $image = $("#image{{image.pk}}");
var cropBoxData;
var canvasData;
$("#modalCrop{{image.pk}}").on("shown.bs.modal", function () {
$image.cropper({
viewMode: 1,
aspectRatio: 1/1,
minCropBoxWidth: 200,
minCropBoxHeight: 200,
ready: function () {
$image.cropper("setCanvasData", canvasData);
$image.cropper("setCropBoxData", cropBoxData);
}
});
}).on("hidden.bs.modal", function () {
cropBoxData = $image.cropper("getCropBoxData");
canvasData = $image.cropper("getCanvasData");
$image.cropper("destroy");
});
$(".js-zoom-in").click(function () {
$image.cropper("zoom", 0.1);
});
$(".js-zoom-out").click(function () {
$image.cropper("zoom", -0.1);
});
/* SCRIPT TO COLLECT THE DATA AND POST TO THE SERVER */
$(".js-crop-and-upload").click(function () {
var cropData = $image.cropper("getData");
$("#id_x{{image.pk}}").val(cropData["x"]);
$("#id_y{{image.pk}}").val(cropData["y"]);
$("#id_height{{image.pk}}").val(cropData["height"]);
$("#id_width{{image.pk}}").val(cropData["width"]);
$("#formUpload{{image.pk}}").submit();
});
});
{% endfor %}
but the problem is the modal never shows so I don't really get what's the problem ?
what should I do to make this work is the problem with the first function to show the modal is there easier way to do this all i want is the users to be able to specify a part of the image they want ?
I use Backbone to create a menu in my app where I can open a project:
app.Tools = Class.extend({
init: function(elementId, app, view) {
this.html = $("#" + elementId);
this.view = view;
this.app = app;
this.openButton = $('<li><button data-toggle="modal" data-target="#openProject" class="btn btn-primary nav-item nav-link" title="Open"><i class="glyphicon glyphicon-folder-open" aria-hidden="true"></i></button></li>');
this.html.append(this.openButton);
this.openButton.click($.proxy(function(){
if (!document.getElementById('openProject')) {
//modal view to confirm new project
this.html.append(
`<div class="modal fade" id="openProject" tabindex="-1" role="dialog">
<div class="modal-dialog">
<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>
<h4 class="modal-title">Open a project</h4>
</div>
<div class="modal-body">
<span class="glyphicon glyphicon-warning-sign"></span> <p>Are you sure you want to do this? If you didn\'nt save your actual project, all your work will be lost for ever.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<span class="btn btn-primary btn-file">Open project<input id="open-project-butt" type="file" class="btn btn-primary"></span>
</div>
</div>
</div>
</div>`
);
};
//listen for new inputs
document.getElementById('open-project-butt').addEventListener('change', readSingleFile, false);
function readSingleFile() {
$('#openProject').modal('hide');
app.view.clear();
newProject(app.view);
var file = this.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function() {
//parse result of the upload
var parsed = new DOMParser().parseFromString(this.result, "text/xml");
var stringXML = (new XMLSerializer()).serializeToString(parsed);
}
}
reader.readAsText(file);
}
},this));
}
});
The first time I open a file everything works fine. Problem is the readSingleFile() function is called as many times as files I open.
I created a codepen but it works fine without Backbone.
Any help or lead to solve the issue? Thanks.
Well, your mistake is adding event listener inside function on button click. You should move it out of click handler.
Each click will add a new listener. Function will be called as many times as you click.
I have 3 modals that all have the same format and are activated by different onclicks (Create Contact, Update Contact, Delete Contact). I am wanting the modal-title and modal-body to change depending on which button was clicked. How would I go about creating a function that appends the modal content depending on which button was clicked? Thank you for your help!
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Contact Created!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div>
</div>
I have written the JavaScript "BootstrapModel" class for the same purpose.
It also depends on jQuery so don't forget to embed jQuery before using this class.
class is :
var BootstrapModal = (function (options) {
var defaults = {
modalId: "#confirmModal",
btnClose: "#btnClose",
title: "Confirm",
content: "Some bootstrap content",
onClose: function () {
},
onSave: function () {
}
};
defaults = options || defaults;
var $modalObj = $(defaults.modalId);
var hideModal = function () {
$modalObj.modal("hide");
};
var showModal = function () {
$modalObj.modal("show");
};
var updateModalTitle = function (title) {
defaults.title = title;
//$($modalObj).find(".modal-title").eq(0).html(title);
$modalObj.find(".modal-title").eq(0).html(title);
};
var updateModalBody = function (content) {
defaults.content = content;
$modalObj.find(".modal-body").eq(0).html(content);
};
return {
getDefaults: function () {
return defaults;
},
hide: function () {
hideModal();
},
show: function () {
showModal();
},
updateTitle: function (title) {
updateModalTitle(title);
return this;
},
updateBody: function (body) {
updateModalBody(body);
return this;
}
}
});
Usage :
var emailModal = new BootstrapModal({modalId: "#confirmModal"});
emailModal.updateTitle("Mail sent successfully").updateBody("<br/>This box will automatically close after 3 seconds.").show();
// Hide the Modal
emailModal.hide();
HTML Structure for the Modal:
<div class="modal fade" id="confirmModal" role="dialog" aria-labelledby="thankyouModal" aria-hidden="true" style="overflow-y: hidden;">
<div class="modal-dialog" style="padding-top: 225px">
<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>
<h4 class="modal-title" id="thankyouModal">Thank you</h4>
</div>
<div class="modal-body">
Thank you. We'll let you know once we are up.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The way I got around this is by loading the data in from external files. So you'd have your initial declaration of your modal box (just the surrounding div), and then in each file you have the containing code for the rest of the modal, then use a bit of jQuery to fire them off:
HTML (in main file)
<div class="modal" id="modal-results" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
JQuery
$('#create-contact').click(function(){
e.preventDefault();
$("#modal-results").html('create-contact.html');
$("#modal-results").modal('show');
});
I have problem, with knockout.js and bootstrap modal. On button click i open bootastrap modal, for creating new city. Then i submit form and save in base. Problem is because submiting works only first time. After that it doesn't work.
Here is how it look like
html file
> <!-- Modal add new city
> ==================================================-->
> <div class="modal fade" id="addCity" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
> <div class="modal-dialog">
> <form data-bind="submit: onSubmit">
> <div class="modal-content">
> <div class="modal-header">
> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
> <h4 class="modal-title">Dodaj novi grad</h4>
> </div>
> <div class="modal-body">
> <div class="input-group">
> <span class="input-group-addon">Ime grada</span>
> <input type="text" class="form-control" placeholder="Ime grada" data-bind="value : city_name">
> </div
>
>
> </div>
> <div class="modal-footer">
> <button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
> <button type="submit" class="btn btn-success">Sacuvaj</button>
> </div>
> </div><!-- /.modal-content -->
> </form>
> </div><!-- /.modal-dialog -->
> </div><!-- /.modal -->
js file
var viewModel = ko.computed(function()
{
var self = this;
var cities = getAllCities();
self.cities = ko.observableArray(cities);
self.city_name = ko.observable();
self.logo_path = ko.observable();
//add new city
self.onSubmit = function()
{
var data = JSON.stringify(
{
city_name : self.city_name(), logo_path : self.logo_path()
}); // prepare request data
var response = ajaxJsonPost("/services/private_service/add_city", data, false, false);
if (response.status === ResponseStatus.SUCCESS) {
$("#cityName").attr("value", "");
$('#addCity').modal('hide');
self.cities.push(data);
} else {
//handle error
}
};
});
ko.applyBindings(new viewModel());
Can you not just do an ajax request instead of a form submit? Something like:
$.ajax({
url: "/services/private_service/add_city",
data: data,
success: function (data) {
$("#cityName").attr("value", "");
$('#addCity').modal('hide');
self.cities.push(data);
}
});
Unless you have written script for this method, I'm not familiar with "ajaxJsonPost()".