How get clicked id when clicked element in modal window? - javascript

I am beginner web developer.
I have code to dynamic load data to iframe:
$(document).ready(function () {
function loadMaterials(type, query) {
$.ajax({
type: 'GET',
url: '/getMaterials',
dataType: "text",
data: {
query: query,
type: type,
},
success: function (data) {
$('.dynamic-materials').html(data);
}
});
}
$('.product-material-front').on('show.bs.select', function () {
$('.product-query-string-body').val('');
loadMaterials(2, "");
$('.select-material-title').html('MateriaĹ frontu')
$('.material-type-input').val(2);
$('#material-dialog-modal').modal('show');
});
$('.product-material-body').on('show.bs.select', function () {
$('.product-query-string-body').val('');
loadMaterials(1, "");
$('.select-material-title').html('MateriaĹ korpusu');
$('.material-type-input').val(1);
$('#material-dialog-modal').modal('show');
});
});
<div id="material-dialog-modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body pt-0">
<h3 class="select-material-title px-3"></h3>
<form method="get" action="{{ route('frontend.get.materials') }}" class="px-3 select-material-url">
<input type="hidden" name="type" value="" class="material-type-input">
<div class="inner-addon rounded-0 modal-search-form">
<i class="fa fa-search"></i>
<input type="text" class="form-control product-query-string-body"
placeholder="Szukaj produktu"
aria-label="Wpisz nazwę lub kod koloru"/>
</div>
</form>
<div class="row material-list px-5 pt-4 dynamic-materials">
</div>
</div>
</div>
</div>
</div>
It's work fine.
I need to change the classes of the clicked elements.
Additionally, I want to select select with the option selected.
I made a code like this:
$('.select-material-body').on('click', function(e){ console.log('ok');
if($('.material-type-input').val() == 1){
$(".select-material").removeClass("selected-material");
$(this).addClass("selected-material");
$('select[name=product-material-body]').val($(this).attr('id'));
$('.product-material-body').selectpicker('refresh');
$('#material-dialog-modal').modal('hide');
} else{
$(".select-material").removeClass("selected-material");
$(this).addClass("selected-material");
$('select[name=product-material-front]').val($(this).attr('id'));
$('.product-material-front').selectpicker('refresh');
$('#material-dialog-modal').modal('hide');
}
});
But unfortunately it doesn't work :(
How can i repair it?
My preview: http://serwer1356363.home.pl/_nauka/ - popup is visible after click select (with icon)
Please help me..

Since the modal content isn't append on the document, you can't bind event to it.
Instead, you can add an on() event to the body, passing your sub-selector :
$('body').on('click', '.select-material-body', function(e) { console.log('ok'); });

Related

Is there a way to reload page and after that inmediately open a modal?

I want to refresh the page after I press the ".parseo" button and then open the "#modal_parseo" modal window but with this code all it does it's open the modal first then refresh the page and closes everything again.
What I tried so far(to clear cache and see If I could fix the issue I had without having to reload the page but the code works fine only after I reload the page before I open the modal):
$('#modal_parseo').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');//this doesn't do anything at all
});
And this:
$("#modal_parseo").on("hidden.bs.modal", function(){
graph_editor.html.set('');//this clears content inside froala editor
$("#tabla_grafico").html("");//this clears datatable I build using the data pasted inside froala editor
});
This is the HTML
<div class="modal fade" id="modal_parseo" tabindex="-1" role="dialog" aria-labelledby="modalLabelparseo" aria-hidden="true">
<div class="modal-dialog modal-98" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabelparseo">Constructor de Gráfico </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="body-parseo">
<div class="row mt-2">
<div class="col-md-6">
<div id="froala-grafico"></div>
<input type="hidden" name="editor_grafico" id="editor_grafico">
<input type="hidden" name="id_temporal" id="id_temporal">
</div>
<div class="col-md-6" id="container_parseo">
<table id="tabla_grafico" data-pagination="false" data-classes="table table-hover table-condensed" data-striped="false" style="width: 100%;"></table>
<br>
<div id="graph_selector" style="display:none; text-align: center;" >
<p><b>Tipo de Grafico: </b></p>
<div class="cc-selector">
<input id="axes" type="radio" name="sel_graph" class="radio_selector" value="axes" checked/>
<label class="drinkcard-cc axes"for="axes"></label>
<input id="activity" type="radio" name="sel_graph" class="radio_selector" value="activity" />
<label class="drinkcard-cc activity" for="activity"></label>
<input id="pie" type="radio" name="sel_graph" class="radio_selector" value="pie" />
<label class="drinkcard-cc pie" for="pie"></label>
</div>
</div> <!--DIV SELECTOR TIPO GRAFICO -->
</div> <!--DIV COL MD 6 -->
</div> <!--DIV ROW -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
<button type="button" class="btn btn-info" id="limpiar_froala">Limpiar</button>
<button type="button" class="btn btn-warning" id="vista_preliminar">Vista Preliminar</button>
<button type="button" class="btn btn-success" id="guardar_grafico">Guardar</button>
</div>
</div>
</div>
Here is the js
window.accionesFila = {
'click .parseo': function(e, value, row, index) {
window.location.reload();
$('#modal_parseo').modal('show');
//FUNCTION TO SAVE DATA
$('#guardar_grafico').click(function() {
//TABLE ID
var $table = $('#tabla_grafico');
//console.log(editor);
//$("#editor_grafico").val(graph_editor.html.get());
//GRAPH TYPE SELECTOR VALUE
var graph_selector = document.querySelector('input[name=sel_graph]:checked').value
function getRowSelections() {
return $.map($table.bootstrapTable('getSelections'), function(row) {
return row;
})
}
//SAVE SELECTED ROWS HERE
var selectedRows = getRowSelections();
agrupacion_array = [];
//ITERATE
$.each(selectedRows, function(index, value) {
id_grafico = value.col_grafico_id;
agrupacion_array.push(value.val_agrupacion);
});
$.ajax({
url: 'inc/datos-graficos-data',
dataType : "json",
type: 'POST',
data: {
q: 'guardar_grafico',
id: row.id_indicador,
graph_id: id_grafico,
agrupacion: agrupacion_array,
datos: editor
},
async: false,
beforeSend: function() {
//$("#ventasGrafico").html("<img src='images/loading.gif'>");
},
success: function(json) {
$('#modal_parseo').modal('hide');
//SWAL
Swal.fire(
'Exito!',
json,
'success'
)
},
cache: true
});
}); //INSERT GRAPH
}
}
Edit: I added this inside the 'click .parseo' function
'click .parseo': function(e, value, row, index) {
//$('#modal_parseo').modal('show');
var url = window.location.href;
if (url.indexOf('#modal') > -1){
window.location.href.split('#')[0]//I tried this to remove the hash now but it doesn't work
} else {
url += '#modal'
}
window.location.href = url;
window.location.reload();
And this outside, thanks to the 1st answer
$(function() {
if($(location).attr('hash') === '#modal') {
$('#modal_parseo').modal('show');
}
});
Edit2: I managed to remove the hash after I close my modal with this
$('#modal_parseo').on('hide.bs.modal', function(e) {
history.replaceState(null, null, ' ');
});
When you call window.location.reload(), the page is reloaded just like when you press f5 or hit enter on your url bar. This means your current page state is lost, so the execution of your code is interrupted and starts over from the beginning on the freshly loaded page.
What you could do is add a hash to your url when the user clicks the button (for example https://www.my.page/#modal) and then check if this is present when you load the page:
//this executes when the page is ready
$(function() {
if($(location).attr('hash') === '#modal') {
$('#modal_perso').modal('show');
}
});
Note that if somebody bookmarks the page including the hash, this will also be executed.
In your edit, you are trying to use window.location.href.split('#')[0] to remove the hash from the url. By itself, this doesn't do anything - it is just a value. You need to assign the value to something. You can not assign the value directly to window.location.href here because this will make most browsers reload the page.
What you can do is use HTML5 history API like this for example:
window.history.pushState(null, document.title, window.location.href.split("#")[0]);

why my modal is not closing on clicking add area button

on click add area button my modal should be closed but it is not working. everything looks fine but i can not find error. id="category-popup" should close modal by $("#category-popup").modal('hide'); but it is not working can someone help me?
<div class="modal fade" id="category-popup" tabindex="-1" role="dialog" aria-labelledby="category-
popup" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Area</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="{{ route("save.area.ajax") }}" class="category-form">
{{ csrf_field() }}
<div class="form-group">
<label>Area Name</label>
<input type="text" name="name" class="form-control old-category" required="">
</div>
<div class="form-group">
<button type="button" class="btn btn-primary btn-block add-area-submit-btn">Add
Area</button>
</div>
</form>
</div>
</div>
</div>
</div>
java script
$('.add-category').click(function(event){
event.preventDefault();
$('.old-category').val('')
$('.category-form').attr('action' , '{{ route("save.area.ajax") }}');
$('#category-popup .modal-title').html('Add Area');
$('#category-popup .modal-footer button').text('Add Area');
});
$(document).on('click', '.add-area-submit-btn', function(e){
e.preventDefault();
var btn = $(this);
if($('.category-form .old-category').val() != ""){
$.ajax({
type: 'post',
data: $('.category-form').serialize(),
url: $('.category-form').attr('action'),
success: function(res){
$("#area-select").html(res);
$("#category-popup").modal('hide');
}
});
}
});
The syntax for hiding modal is correct but please make sure that your $.ajax request is succeeding. Try doing console.log() in $.ajax success. Or add error in your ajax so you could know the error
$.ajax({
type: 'post',
data: $('.category-form').serialize(),
url: $('.category-form').attr('action'),
success: function(res) {
console.log("ajax request success");
$("#area-select").html(res);
$("#category-popup").modal('hide');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("ajax request failed: " + errorThrown);
}
});
check errors in the cnsole it submit area in option field but not closed
Hm, weird, are you sure you include jQuery correctly? Could you show your included scripts?
jQuery should be like: <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
In JavaScript one error results in broking whole script. And without jQuery your "modal" action will not work. I think it's the reason why your script not working.

File is stored couple of times instead of once

When I upload a file it is stored X times where X is the time count you upload it. If I try to upload it three times in a row it will store one file, two files, three files which gives us 6 in total.
Why does that happen?
$(function() {
$("#uploadButton").on('click', function() {
const job_id = $(this).attr("data-item");
$("#cvForm").submit(function(e) {
e.preventDefault();
var form_data = new FormData(document.getElementById("cvForm"));
axios({
method: 'post',
url: '/job/apply/' + job_id,
data: form_data,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function(response) {
console.log(response);
}).catch(function(response) {
console.log(response);
});
return false;
});
});
});
Form is:
<div class="modal fade" id="CVModalUpload" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">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">
<form id="cvForm" name="cv" method="post" action="{{ path('student_candidate', {'id':job.id}) }}" enctype="multipart/form-data">
<div class="input-group">
<div class="custom-file">
<input type="file" name="cv[file]" class="custom-file-input" id="uploadGroup" aria-describedby="uploadButton">
<label class="custom-file-label" for="uploadGroup">Choose CV</label>
</div>
<div class="input-group-append">
<button type="submit" name="cv[send]" class="btn btn btn-primary shadow rounded-0" id="uploadButton" data-item="{{ job.id }}">Upload CV</button>
</div>
</div>
{{ form_row(form._token) }}
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The issue is because you're nesting your event handlers. To fix this move submit() outside of click().
That said, now that you've added the HTML to the question, I can see that you don't need the click handler at all. You can simply read the data-item from the button when the form is submit. Try this:
jQuery(function($) {
$("#cvForm").submit(function(e) {
e.preventDefault();
let form_data = new FormData(this); // note 'this' here
let job_id = $('#uploadButton').data('item'); // note 'data()' here
axios({
method: 'post',
url: '/job/apply/' + job_id,
data: form_data,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function(response) {
console.log(response);
}).catch(function(response) {
console.log(response);
});
});
});
Its propably because of the location where you implemented submit(). You should propably move it outside of the click()-eventHandler.
That's because you have placed your submit button inside a form. Now whenever a button is pressed inside a form, it automatically submits the form. In your case form is submitting two times, once when button is clicked and second time inside your click handler.
Easy solution to this is, just change type attribute of your submit button to "button".

CKEditor is not working with bootstrap modal

I want to show ckEditor on bootstrap modal but the ckEditor is not opening as shown below. After searching through the internet I have got some solution in a different way like this link but I will perform an ajax request hence I have to open the modal using $('.cia_modal').modal('toggle'). The above-mentioned solution link does not work for me
Modal Button:
<button class="btn btn-info btn-xs cia_modal_btn" data-id="<?php echo $post->post_id; ?>" data-table="post" data-attr="post_id">
Create New Post
</button>
Modal:
<!--Modal-->
<div class="modal fade cia_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">Create New Post</h4>
</div>
<div class="modal-body">
<form action="/action_page.php">
<div class="form-group">
<textarea class="ck_editor" name="post" id="" cols="30" rows="10"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--End Modal-->
Javascript:
<script type="text/javascript">
$(document).on("click", ".modal_btn", function (e) {
e.preventDefault();
e.stopPropagation();
let cia_modal = $('.cia_modal');
//Set modal show/hide
cia_modal.modal('toggle');
let id = $(this).attr('data-id');
let table = $(this).attr('data-table');
let attr = $(this).attr('data-attr');
//Set Form Data
let formData = new FormData();
formData.append('id',id);
formData.append('table',table);
formData.append('attr',attr);
$.ajax({
type: 'post',
url: '<?php echo base_url()?>post/create_post',
data: formData,
contentType: false,
processData: false,
success: function (data) {
//
}
});
});
</script>
Please help me. Thanks
I assume, you are using CKEditor 4.x.
You need to create editor using CKEDITOR.replace( 'ck_editor' ), you can do it only on element that is existing inside document. It doesn't matter if it's hidden or not. If your modal is inside DOM, but hidden, then just initialize editor. Otherwise you need to wait until element is appended then call CKEDITOR.replace.
Depending on how bootstraps implements modal.show. If it's just changes CSS to make it visible, then most likely you can initialize editor at the start of your script, if it adds elements to document, then you need to use some of bootstrap events to create editor in right time. See shown.bs.modal: https://getbootstrap.com/docs/4.0/components/modal/#events
Just initialize the editor:
<script type="text/javascript">
ClassicEditor.create($('.ck_editor')[0])
.then( editor => {
console.log( editor );
})
.catch( error => {
console.log( error );
});
$(document).on("click", ".modal_btn", function (e) {
//....

Google Maps autocomplete in Bootstrap modal with Vue.js

I have Boostrap modal with <input>. I have implemented Google autocomplete for it with the following well-known trick:
.pac-container {
z-index: 10000 !important;
}
Now I'm struggling to make autocomplete working inside 2nd layer Boostrap Modal. Unfortunately, the z-index trick doesn't work here.
<div class="modal fade" id="editItemModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div id="editItem" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Update Address <b>{{selectedItem.properties.NAME}}</b>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label class="sr-only" for="editItem_ADRESS1"></label>
<input v-model="selectedItem.properties.ADRESS1" type="text" class="form-control" id="editItem_ADRESS1" ref="editItem_ADRESS1" placeholder="{{selectedItem.properties.ADRESS1}}">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-success btn-ok" #click="save_item()" data-dismiss="modal">Save</a>
</div>
</div>
</div>
</div>
Then comes the Vue object
const editItem = new Vue({
el: "#editItem",
data: {
items: null,
selectedItem: null,
},
methods: {
save_item() {
this.selectedItem = itemsList.selectedItem;
var ip = location.host;
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://' + ip + '/updateItem',
data: {
command: "edit_item",
item_id: this.selectedItem.id,
adress1: this.selectedItem.properties.ADRESS1
},
success: function (responseData) {
if (responseData.result === false) {
console.log(responseData.result);
}
else {
console.log("successfully updated");
}
},
error: function (error) {
console.log('error', error);
}
}); // end of ajax
} // end od save_item()
} // end of methods
});
Finally, I was able to figure out what was the issue. It turns out that the DOM object is not created yet by Vue when the Google iniAutocomplete() function sets listeners.
In addition, my <input> didn't run the Google geolocate() function. That's how the <input> looks now:
<div class="form-group">
<label class="sr-only" for="edit-item_ADRESS1"></label>
<input id="edit-item_ADRESS1" v-model="selectedItem.properties.ADRESS1" type="text" class="form-control" onFocus="geolocate('edit-item')">
</div>
The next step was to make a minor change in the geolocate() function. I pass action variable onFocus event and use it to determine what DOM object initiated the call.
if (action == "add-item") {
autocomplete_add_item.setBounds(circle.getBounds());
}
if (action == "edit-item") {
// we need to run iniAutocomplete again after the DOM object was finally created by Vue
initAutocomplete();
autocomplete_edit_item.setBounds(circle.getBounds());
}

Categories

Resources