jQuery remove class on closest - javascript

I'm trying to action a removeClass request using jQuery. Most of the below script is working fine except for the $(this).closest('.press-continue').removeClass('hidden'); part.
I have posted the jQuery and HTML below. Any ideas what could be the problem?
$(function () {
$('.step2').on('click', '.btn-book', function (e) {
$.ajax({
url: '/reserve/' + this.id,
type: 'get',
dataType: 'json',
context: this,
success: function (json) {
if (json['success']) {
$(this).addClass('btn-selected');
$('.btn-book').not(this).addClass('book-disabled').prop('disabled', true);
$('.next-step-hidden').addClass('show-button').prop('href', '/confirm/' + this.id);
$('.cancel').addClass('show-button').prop('id', this.id);
$('.alert-danger').addClass('hidden-error');
$(this).closest('.press-continue').removeClass('hidden');
} else if (json['error']) {
if (json['error'] == 1) {
alert("Another user has already booked this slot, please choose another slot.");
$(this).addClass('btn-selected').addClass('book-disabled').prop('disabled', true);
}
}
}
});
});
});
HTML
<div id="main">
<h2 class="info-bar clearfix"><b>Select parking time</b> <span>Step <i>2</i></span></h2>
<div class="alert alert-danger hidden-error">
<strong>Expired!</strong> Sorry, the slot that you reserved has now expired. Please choose another slot below.
<br><i>Note: slots are reserved for 15 minutes.</i>
</div>
<form class="step2">
<fieldset>
<legend><span>Select a Parking Slot</span></legend>
<div class="parking-time">
<div class="input-row">
<label class="label">12/06/2015
<br>Morning
<br>7am - 1pm</label>
<button class="btn btn-small btn-important btn-book" type="button" id="67"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
<div class="input-row">
<label class="label">12/06/2015
<br>Afternoon
<br>2pm - 7pm</label>
<button class="btn btn-small btn-important btn-book" type="button" id="68"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
<div class="input-row">
<label class="label">12/06/2015
<br>All Day
<br> </label>
<button class="btn btn-small btn-important btn-book" type="button" id="69"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
</div>
<!-- end parking-time -->
<div class="input-row input-row-last"> <a class="btn btn-small btn-info cancel">Cancel</a> <a class="btn btn-info next-step next-step-hidden">Continue <i class="sprite arrow"></i></a> </div>
</fieldset>
</form>
</div>
<!-- end main -->

.closest() is used to find an ancestor element, where as what you are looking for is the next sibling so you can use .next()$(this).next('.press-continue').removeClass('hidden');
$(function () {
$('.step2').on('click', '.btn-book', function (e) {
$.ajax({
url: '/reserve/' + this.id,
type: 'get',
dataType: 'json',
context: this,
success: function (json) {
if (json['success']) {
$(this).addClass('btn-selected');
$('.btn-book').not(this).addClass('book-disabled').prop('disabled', true);
$('.next-step-hidden').addClass('show-button').prop('href', '/confirm/' + this.id);
$('.cancel').addClass('show-button').prop('id', this.id);
$('.alert-danger').addClass('hidden-error');
$(this).next('.press-continue').removeClass('hidden');
} else if (json['error']) {
if (json['error'] == 1) {
alert("Another user has already booked this slot, please choose another slot.");
$(this).addClass('btn-selected').addClass('book-disabled').prop('disabled', true);
}
}
}
});
});
});

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]);

Laravel How to reset modal ajax data values upon closing the modal

I am currently working on populating a user's searching for available appointments by selecting a date, start time and end time. I am trying to populate them onto a modal which is currently working. However I realise that whenever I close the modal and search for the new timeslots, the previous data populated on the modal will still be there.
I have tried doing function when I close the modal, the modal data will be cleared.
Below are my html codes for the modal:
<div class="modal fade" id="myModalNewAppointment">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Select Appointment</h4>
</div>
<!-- Modal body -->
<div class="modal-body">
{{-- <form id="test" action="" method="post"> --}}
<div class="form-group">
<label for="modal">Select a Timeslot</label>
<div class="spacer"></div>
<div class="timeslots-section">
<div class="timeslots text-center">
</div> <!-- end timeslots -->
</div>
</div>
{{-- </form> --}}
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="new_appt_cfm_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Confirm</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Below is my ajax method to retrieve the timeslots:
$("#find_appointment_btn").click(function(event){
event.preventDefault();
let select_date = $('#select_date').val();
let start_time = $('#start_time').val();
let end_time = $('#end_time').val();
let data = { select_date: select_date, start_time: start_time, end_time: end_time };
$.ajax({
type:"POST",
url: "{{ route('assistant.newappts.get') }}",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
dataType: "json",
success:function(data){
console.log(data);
if(data == ""){
alert("Clinic is close!");
return;
}
else if(data != ""){
$('#myModalNewAppointment').modal({backdrop: 'static', keyboard: false});
data.forEach(function(dt) {
// do something with `item`
// $(".timeslots").append(dt);
$('.timeslots').append('<input type="checkbox" class="timeslotchk" name="timeslot" value="'+ dt +'"/>' + dt );
});
}
},
error: function(error) {
console.log(error);
}
});
});
Below is the method I have tried to reset the data populated on my modal:
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').reset();
});
When you call the ajax request on the success you have appended the data in model "timeslots" division so its obvious that data will be still there on the hiding model try to empty the timeslots, try below code hope it work for you and make sure that method trigger on closing of model
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').find(".timeslots").empty();
});

How get clicked id when clicked element in modal window?

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

How to reset modal contents?

The process is like this.
A user searches any words in a search form. Ajax calls with the word and gets the data, then it will be showed with the modal.
So, I tried to make modal dynamically with ajax.
But the modal contents didn't change once it called.
1) This is the function include a search form and it calls the modal.
function answer() {
//console.log('answer');
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = `<!-- file form start -->
<!-- file form end -->
<label class="col-md-2 col-form-label">문의내용</label>
<!-- text form start -->
{!! Form::open([ 'route' => ['qnamembercreate', $qnaMemberData->idx], 'method' => 'post', 'files' => true, 'accept-charset' => 'utf-8','class' => 'col-md-10 col-xs-9' ])!!}
<div class="col-sm-6 offset-md-6 p-0">
<div class="input-group">
<input type="text" id="f_search" name="f_search" class="form-control">
<span class="input-group-append">
<button type="button" class="btn waves-effect waves-light btn-inverse" onclick="faq_search()">Search</button>
</span>
</div>
</div>
<input type="hidden" name="subject" value="{{ $qnaMemberData->subject }}">
<textarea id="answer_content" class="mb-0" rows="20" style="width:100%;" name="add_answer"></textarea>
<div class="form-group">
<input name="fileToUpload" type="file" class="filestyle" data-input="false" id="filestyle-1" tabindex="-1" style="display: none;">
<div class="bootstrap-filestyle input-group">
<div style="position: absolute; width: 100%; height: 35.375px; z-index: -1;"></div>
<span class="group-span-filestyle " tabindex="0">
<label for="filestyle-1" style="margin-bottom: 0;" class="btn btn-secondary btn-sm fload-right">
<input type="file" name="fileToUpload" class="filestyle-1" data-placeholder="" data-buttontext="첨부파일" data-buttonname="btn-secondary">
</label>
</span>
</div>
</div>
<button type="button" class="btn btn-danger btn-sm float-right ml-1 mt-1" onclick="history.back()">취소</button>
<button type="submit" class="btn btn-success btn-sm float-right mt-1">등록</button>
{!! Form::close() !!}
<!-- text form end -->`;
document.getElementById('replyData').appendChild(div);
document.getElementById('answer').remove();
$('#answer_content').summernote({
// placeholder: {!! json_encode($qnaMemberData->content) !!},
tabsize: 2,
height: 200,
lang: 'ko-KR',
fontNames: ['Gulim', 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', ],
fontNamesIgnoreCheck: ['Gulim'],
});
}
2) This is the 'faq_search' function when the user clicks the 'search' button.
function faq_search() {
var word = $('#f_search')[0].value;
//console.log(word);
$.ajax({
url : '/guidesearch',
type : 'POST',
data : {
keyword: word
},
cache : false,
success : function(data, jqXHR, textStatus) {
console.log(data);
faq_popup(data);
}
});
}
3) This is the 'faq_popup' function which is called after getting the data.
function faq_popup(data) {
var _data = data;
console.log("here", _data);
const appendedDiv = $(`
<div class="modal fade show" tabindex="-1" id="faqModal" role="dialog" style="positon:center;">
<div class="modal-dialog modal-dialog-centered">
<!-- Modal content-->
<div class="modal-content">
<div class="table-responsive">
<table class="table mb-0">
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
`);
const tbody = appendedDiv.find('tbody')[0];
_data.forEach(({ content, subject }, i) => {
//console.log(i);
const tr = tbody.appendChild(document.createElement('tr'));
tr.innerHTML = `
<th scope="row">${i + 1}</th>
<td><a style="cursor:pointer">${subject}</a></td>
`;
tr.querySelector('a').addEventListener('click', () => getContent(content));
});
$('#modal_place').append(appendedDiv);
$('#faqModal').modal('show');
}
I tried to reset the modal with this code below. But the problem is, once the modal content is cleared, the new data is not called at all.
$(document).ready(function(){
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).find('tbody td').html("");
});
});
I really don't get it. Because I call the 'faq_popup' after the ajax got the data, the new data should be showed. But it doesn't work as I think.
What did I wrong here?
** I also tried to wipe out the whole modal-content. The modal contents doesn't show up at all.
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).find('.modal-content').html("");
});
I found the solution. Thanks to #KaseyChang, gave me the hint.
The reason was I didn't destroy the modal correctly. The modal was added and added on itself. So I just did this.
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).remove(); <--- here!
});
In the AJAX function you can just empty() the modal before the call is made, using beforeSend. This way it will happen sequentially:
function faq_search() {
var word = $('#f_search')[0].value;
$.ajax({
url : '/guidesearch',
type : 'POST',
data : {
keyword: word
},
cache : false,
beforeSend : function() {
$('.modal-content').empty();
},
success : function(data, jqXHR, textStatus) {
console.log(data);
faq_popup(data);
}
});
}

How to display data from API inside a bootstrap collapse/modal?

I have a school project about API, and I have problems displaying specific data inside a bootstrap collapse.
I have a school project, where I take data about coins from API server and present it. Every coin is presented in a different div and within that div there is a button. This button is "More Info", and should display more info about that coin, from a link with a specific id, similar to the coin. I managed to present the data from the API server, but couldn't make the button work.
This is the link for the "More Info" button: https://api.coingecko.com/api/v3/coins/{id}
This is the html:
<body>
<div class = "header">
Cryptonite
</div>
<div class="line"></div> </br>
<div class="container">
<div class="navigation">
<div id="buttons">
<button type="button" class="btn btn-link" id="home-btn" onClick="selectTab" name="home">Home</button>
<button type="button" class="btn btn-link" id="live-btn" onClick="selectTab" name="live">Live Reports</button>
<button type="button" class="btn btn-link" id="about-btn" onClick="selectTab" name="about">About</button>
</div>
<div class="search">
<input type="search" placeholder="Search" aria-label="Search through site content"/> <button type="button" class="btn btn-link" id="src-btn" name="src">Search</button>
</div>
</div>
</br>
<div class="coins">
</div>
</div>
</body>
This is the script:
//This is the function to call the data from the API server
function callCoins() {
$.ajax({
url: "https://api.coingecko.com/api/v3/coins/list",
dataType: "json",
success: function(data){
console.log(data);
for(let i=0;i<100;i++){
$(".coins").append(`
<div class="coin">
<span>
<p id="coin-sym">${data[i].symbol}</p>
<p>${data[i].name}</p>
<button class="btn btn-primary" data-toggle="collapse" data-target="#a${data[i].id}">More Info</button>
<div class="collapse" id="a${data[i].id}">example</div>
</span>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="b${data[i].id}">
<label class="custom-control-label" for="#b${data[i].id}"></label>
</div>
</div>
</br>
`)
}
}
})
}
//This is the function for 'More Info'
function moreInfo() {
$.ajax({
url: "https://api.coingecko.com/api/v3/coins/{id}",
dataType: "json",
success: function(data){
$(".collapse").append(`
<div class="moreInfo">
<span>
<p>${data.image.thumb}</p>
</span>
</div>
`)
}
})
}
When I click on "More Info", it should display data from a link with the coin specific id.
Here is a Demo File
Seems like you are not invoking the moreInfo function on click of the button. so your More Info HTML Button has to be like this.
<button class="btn btn-primary" data-toggle="collapse" data-target="#a${data[i].id}" onClick="moreInfo('${data[i].id}')">More Info</button>
and the moreInfo() function to be like this
function moreInfo(id) { /* change 1 - added id parameter*/
$.ajax({
url: "https://api.coingecko.com/api/v3/coins/"+id, /* change 2 - added the id parameter to the api call */
dataType: "json",
success: function(data){
$(".collapse").append(`
<div class="moreInfo">
<span>
<p>${data.image.thumb}</p>
</span>
</div>
`)
}
})
}
Hope this helps. And to Make it appear as an image you have add an image tag inside the p tag and bind the image url into the src attribute.

Categories

Resources