Bootstrap modal doesn't toggle on first click - javascript

Hi I have the same problem as this thread twitter bootstrap modal won't work on first call
I tried to follow the answer and replace $('#modal').modal('toggle') to $('#modal').modal('show'). It still only registers on the second click. (you have to click on the poster 2 times to show modal, and you have to click on 'Select' button 2 times to close it).
Here's my code: Javascript
var zipcode = 92660;
var showDate = '2018-06-10';
var selectedMovieTitles = [];
var selectedMoviePosters = [];
var selectState = false;
var tmsURL = 'http://data.tmsapi.com/v1.1/movies/showings?startDate=' + showDate + '&zip=' + zipcode + '&api_key=' + tmsAPIKey;
$('#button').on('click', function () {
getMovieList();
});
function litmitMovieSelect() {
$('#limitSelection').modal('show');
}
function selectMovie() {
$(this).on('click', function () {
$('#movieInfoModal').modal('hide');
if (selectedMovieTitles.length >= 3) {
litmitMovieSelect();
}
else {
selectState = true;
selectedMovieTitles.push($(this).attr('data-title'));
selectedMoviePosters.push($(this).attr('data-poster'));
$(`.posters[data-title='${$(this).attr('data-title')}']`).css('border', '3px solid #008000');
$(`.posters[data-title='${$(this).attr('data-title')}']`).attr('data-state-selected', selectState);
console.log('selected movie titles: ' + selectedMovieTitles);
}
});
}
function launchModal() {
$(this).on('click', function () {
selectState = false;
$(this).css('border', '');
var titleToBeRemove = $(this).attr('data-title');
if (selectedMovieTitles.indexOf(titleToBeRemove) !== -1) {
selectedMovieTitles.splice(selectedMovieTitles.indexOf(titleToBeRemove), 1);
}
$('.modal-title').text($(this).attr('data-title'));
var movieInfoDiv = $(`<div>
<p><strong>Actors:</strong> ${$(this).attr('data-actors')}</p>
<p><strong>Director:</strong> ${$(this).attr('data-director')}</p>
<p><strong>Genre:</strong> ${$(this).attr('data-genre')}</p>
<p><strong>Year:</strong> ${$(this).attr('data-year')}</p>
<p><strong>Duration:</strong> ${$(this).attr('data-runtime')}</p>
<p><strong>Rating:</strong> ${$(this).attr('data-rating')}</p>
<p><strong>Plot:</strong> ${$(this).attr('data-plot')}</p>
</div>`)
$('.modal-body').html(movieInfoDiv);
var selectButton = $(` <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-title="${$(this).attr('data-title')}" data-poster="${$(this).attr('data-poster')}">
Select
</button>`)
selectButton.on('click', selectMovie);
$('#movieInfoModalFooter').html(selectButton);
$('#movieInfoModal').modal('show');
});
}
function getMovieList() {
var movieTitles = [];
axios.get(tmsURL)
.then(function (tmsResp) {
console.log(tmsResp);
tmsResp.data.forEach(function (element) {
movieTitles.push(element.title);
});
console.log(movieTitles);
movieTitles.forEach(function (element) {
var omdbURL = 'https://omdbapi.com/?t=' + element + '&apikey={}';
axios.get(omdbURL)
.then(function (omdbResp) {
console.log(omdbResp);
var posterDiv = $(`<img class='posters m-3' id='${omdbResp.data.imdbID}'
data-title='${omdbResp.data.Title}'
data-actors='${omdbResp.data.Actors}'
data-director='${omdbResp.data.Director}'
data-genre='${omdbResp.data.Genre}'
data-plot='${omdbResp.data.Plot}'
data-year='${omdbResp.data.Year}'
data-runtime='${omdbResp.data.Runtime}'
data-rating='${omdbResp.data.imdbRating}'
data-poster='${omdbResp.data.Poster}'
src=${omdbResp.data.Poster}
>`);
posterDiv.on('click', launchModal);
$('#movie-display').append(posterDiv);
})
.catch(function (err) {
console.error(err);
});
});
}).catch(function (err) {
console.error(err);
});
}
Here's the HTML:
<div class="modal fade" id="litmitSelection" tabindex="-1" role="dialog" aria-labelledby="litmitSelection" aria-hidden="true">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-body">
Sorry, You Can Only Select Up To 3 Movies.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Movie Info Modal -->
<div class="modal fade" id="movieInfoModal" tabindex="-1" role="dialog" aria-labelledby="movieInfoModal" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">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" id="movieInfoModalFooter">
<!-- <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> -->
<!-- <button type="button" class="btn btn-primary">Select</button> -->
</div>
</div>
</div>
</div>

Something like this would suffice.
Note: I assume you are using bootstrap 4 for your project, although bootstrap 3 would work too, just tweak it a bit to suit your needs
$(document).ready(function() {
/**
* for showing edit item popup
*/
$(document).on('click', "#edit-item", function() {
$(this).addClass('edit-item-trigger-clicked'); //useful for identifying which trigger was clicked and consequently grab data from the correct row and not the wrong one.
var options = {
'backdrop': 'static'
};
$('#edit-modal').modal(options)
})
// on modal show
$('#edit-modal').on('show.bs.modal', function() {
var el = $(".edit-item-trigger-clicked"); // See how its usefull right here?
/*
You now have a reference to which element caused the modal to showup , you can use this to do anything as shown below
*/
var row = el.closest(".data-row");
// get the data
var id = el.data('item-id');
var name = row.children(".name").text();
var description = row.children(".description").text();
// fill the data in the input fields
$("#modal-input-id").val(id);
$("#modal-input-name").val(name);
$("#modal-input-description").val(description);
})
// on modal hide
$('#edit-modal').on('hide.bs.modal', function() {
$('.edit-item-trigger-clicked').removeClass('edit-item-trigger-clicked')
$("#edit-form").trigger("reset");
})
})
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<div class="main-container container-fluid">
<!-- heading -->
<div class="container-fluid">
<div class="row">
<div class="col">
<h1 class="text-primary mr-auto">Example list</h1>
</div>
</div>
</div>
<!-- /heading -->
<!-- table -->
<table class="table table-striped table-bordered" id="myTable" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th>#</th>
<th> Name</th>
<th> Description</th>
<th> Action</th>
</tr>
</thead>
<tbody>
<tr class="data-row">
<td class="align-middle iteration">1</td>
<td class="align-middle name">Name 1</td>
<td class="align-middle word-break description">Description 1</td>
<td class="align-middle">
<button type="button" class="btn btn-success" id="edit-item" data-item-id="1">edit</button>
</td>
</tr>
</tbody>
</table>
<!-- /table -->
</div>
<!-- Attachment Modal -->
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-labelledby="edit-modal-label" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="edit-modal-label">Edit Data</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="attachment-body-content">
<form id="edit-form" class="form-horizontal" method="POST" action="">
<div class="card text-white bg-dark mb-0">
<div class="card-header">
<h2 class="m-0">Edit</h2>
</div>
<div class="card-body">
<!-- id -->
<div class="form-group">
<label class="col-form-label" for="modal-input-id">Id (just for reference not meant to be shown to the general public) </label>
<input type="text" name="modal-input-id" class="form-control" id="modal-input-id" required>
</div>
<!-- /id -->
<!-- name -->
<div class="form-group">
<label class="col-form-label" for="modal-input-name">Name</label>
<input type="text" name="modal-input-name" class="form-control" id="modal-input-name" required autofocus>
</div>
<!-- /name -->
<!-- description -->
<div class="form-group">
<label class="col-form-label" for="modal-input-description">Email</label>
<input type="text" name="modal-input-description" class="form-control" id="modal-input-description" required>
</div>
<!-- /description -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Done</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /Attachment Modal -->

Related

The Content of the Popup don't Display after Pressing the Textlink

Goal:
Display the popup screen Search5 by clicking on the arrow icon in relation to the link textlink "test".
Firstly, click on the textlink test, then click on the displayed icon arrow and then the popup screen Search will appear.
Problem:
When you click on the linktext "test" the icon will appear. When you click on the icon, the content of the popup Search will not appear.
What code am I missing? I have tried with different solution but I failed.
Compare the the third row from the table, the icon works that you can show the content of the popup search.
Info:
*Im using bootstrap 3
Thank you!
<!DOCTYPE html>
<meta name="robots" content="noindex">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table">
<thead>
<tr>
<th>Search</th>
<th>Test</th>
</tr>
</thead>
<tbody id="datafromtbody">
<tr id="tr_row1">
<td id="tr_row1_td1"></td>
<td>test</td>
</tr>
<tr>
<td id="tr_row2_td2"></td>
<td>test</td>
</tr>
<tr id="tr_row3">
<td id="tr_row2_td3">
<a href="#myModal-search5" data-toggle="modal" data-target="#myModal-search5" class="showseconddata" id="data_3">
<img src="https://cdn4.iconfinder.com/data/icons/aiga-symbol-signs/581/aiga_uparrow_inv-512.png" width="15" height="15" />
</a>
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="modal fade" id="myModal-firstdata" role="dialog" data-backdrop="static">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">First data</h4>
</div>
<div class="modal-body">
<div id="firstdata_content"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myModal-search5" role="dialog" data-backdrop="static">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Search 5</h4>
</div>
<div class="modal-body">
<div id="showdatafor5"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$('.firstdata').click(function () {
var alldata = $(this).attr("id");
var number = alldata.split('_')[1];
var display ="<table><thead><tr><th>a</th><th>b</th></tr></thead><tbody>";
display +="<tr>";
display +="<td>a</td><td><button onclick='createicon(" + number + ")'>add data in table</button></td>";
display +="</tr>";
display +="</tbody></table>";
var anydata = document.getElementById("firstdata_content");
anydata.innerHTML = display;
});
function createicon(data)
{
var idname = "tr_row" + data + "_td" + data;
var anydata = document.getElementById(idname);
if (anydata.innerHTML === "") {
var addData = document.getElementById(idname);
addData.innerHTML = "<a href='#myModal-search5' data-toggle='modal' data-target='#myModal-search5' class='showseconddata'><img src='https://cdn4.iconfinder.com/data/icons/aiga-symbol-signs/581/aiga_uparrow_inv-512.png' width='15' height='15' /></a>";
}
}
$('.showseconddata').click(function () {
var display ="<table><thead><tr><th>a</th><th>b</th></tr></thead><tbody>";
display +="<tr>";
display +="<td>show data</td>";
display +="<td>show data</td>";
display +="</tr>";
display +="</tbody></table>";
var anydata = document.getElementById("showdatafor5");
anydata.innerHTML = display;
});
</script>
</body>
</html>
The new icons are created after you attached the click event handler to .showseconddata. Hence, you need to delegate this event, changing from:
$('.showseconddata').click(function () {
to:
$('.container').on('click', '.showseconddata', function () {
function createicon(data) {
var idname = "tr_row" + data + "_td" + data;
var anydata = document.getElementById(idname);
if (anydata.innerHTML === "") {
var addData = document.getElementById(idname);
addData.innerHTML = "<a href='#myModal-search5' data-toggle='modal' data-target='#myModal-search5' class='showseconddata'><img src='https://cdn4.iconfinder.com/data/icons/aiga-symbol-signs/581/aiga_uparrow_inv-512.png' width='15' height='15' /></a>";
}
}
$('.firstdata').click(function () {
var alldata = $(this).attr("id");
var number = alldata.split('_')[1];
var display ="<table><thead><tr><th>a</th><th>b</th></tr></thead><tbody>";
display +="<tr>";
display +="<td>a</td><td><button onclick='createicon(" + number + ")'>add data in table</button></td>";
display +="</tr>";
display +="</tbody></table>";
var anydata = document.getElementById("firstdata_content");
anydata.innerHTML = display;
});
$('.container').on('click', '.showseconddata', function () {
var display ="<table><thead><tr><th>a</th><th>b</th></tr></thead><tbody>";
display +="<tr>";
display +="<td>show data</td>";
display +="<td>show data</td>";
display +="</tr>";
display +="</tbody></table>";
var anydata = document.getElementById("showdatafor5");
anydata.innerHTML = display;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class="container">
<table class="table">
<thead>
<tr>
<th>Search</th>
<th>Test</th>
</tr>
</thead>
<tbody id="datafromtbody">
<tr id="tr_row1">
<td id="tr_row1_td1"></td>
<td>test</td>
</tr>
<tr>
<td id="tr_row2_td2"></td>
<td>test</td>
</tr>
<tr id="tr_row3">
<td id="tr_row2_td3">
<a href="#myModal-search5" data-toggle="modal" data-target="#myModal-search5" class="showseconddata" id="data_3">
<img src="https://cdn4.iconfinder.com/data/icons/aiga-symbol-signs/581/aiga_uparrow_inv-512.png" width="15" height="15" />
</a>
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="modal fade" id="myModal-firstdata" role="dialog" data-backdrop="static">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">First data</h4>
</div>
<div class="modal-body">
<div id="firstdata_content"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myModal-search5" role="dialog" data-backdrop="static">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Search 5</h4>
</div>
<div class="modal-body">
<div id="showdatafor5"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

How do I remove content from a modal-body upon closing the modal?

My goal is to display a fresh modal every time it is opened. Currently, that is only true when the modal window is first displayed after refreshing the page. For the subsequent closing/opening of the modal, it just appends the current content to the end of the previous content, which is still displayed.
It may be worth noting that with this particular configuration of the countless efforts tried, I get an
Uncaught ReferenceError: $ is not defined
in my Javascript console for the line
$(document).ready(function() {
but I'm not sure why. The jQuery library (3.2.1) is initialized for the script type it's being used with after all. Any clue?
<!-- Form -->
<form onsubmit="return false">
<!-- Heading -->
<h3 class="dark-grey-text text-center">
<strong>Calculate your payment:</strong>
</h3>
<hr>
<div class="md-form">
<i class="fa fa-money prefix grey-text"></i>
<input type="text" id="income" class="form-control">
<label for="income">Your income</label>
</div>
<div class="text-center">
<button type="button" class="btn btn-pink" onclick="calculator()" data-toggle="modal" data-target="#exampleModal">Calculate</button>
<script type='text/javascript'>
function calculator() {
let payment = ((document.getElementById("income").value - 18210)*0.1)/12;
payment = Math.round(payment);
if (payment <= 0) {
$('.modal-body').append("$0 per month.");
}
else {
$('.modal-body').append(payment + " or less per month.");
}
}
</script>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">You should be paying:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="test" 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>
<!-- Clear content from modal -->
<script type="text/javascript">
$(document).ready(function() {
$('.exampleModal').on('hidden.bs.modal', function () {
$('.modal-body').clear();
});
});
</script>
<hr>
<label class="grey-text">* This is just an estimate. Please call for a quote.</label>
</fieldset>
</div>
</form>
<!-- Form -->
You should use .html or .text instead of .append
if (payment <= 0) {
$('.modal-body').text("$0 per month.");
}
else {
$('.modal-body').text(payment + " or less per month.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Form -->
<form onsubmit="return false">
<!-- Heading -->
<h3 class="dark-grey-text text-center">
<strong>Calculate your payment:</strong>
</h3>
<hr>
<div class="md-form">
<i class="fa fa-money prefix grey-text"></i>
<input type="text" id="income" class="form-control">
<label for="income">Your income</label>
</div>
<div class="text-center">
<button type="button" class="btn btn-pink" onclick="calculator()" data-toggle="modal" data-target="#exampleModal">Calculate</button>
<script type='text/javascript'>
function calculator() {
let payment = ((document.getElementById("income").value - 18210)*0.1)/12;
payment = Math.round(payment);
if (payment <= 0) {
$('.modal-body').text("$0 per month.");
}
else {
$('.modal-body').text(payment + " or less per month.");
}
}
</script>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">You should be paying:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="test" 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>
<!-- Clear content from modal -->
<script type="text/javascript">
$(document).ready(function() {
$('.exampleModal').on('hidden.bs.modal', function () {
$('.modal-body').clear();
});
});
</script>
<hr>
<label class="grey-text">* This is just an estimate. Please call for a quote.</label>
</fieldset>
</div>
</form>
<!-- Form -->
Try doing $('modal-body').empty() instead of clear

Close current modal and open new modal using jquery

I have two modals, one is View and other is Edit.
Issue is that when I open a view modal and click on edit button then edit modal is open but view modal is still open its will be disappear when edit modal is open.
I am doing like this
$("#editModal").click(function() {
var id = $("#editModal").val();
$('#' + id).modal('hide');
$('#' + id).modal('show');
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
View
<div id="viewTasks_50" class="modal fade show" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h6 class="pull-left">Code : <label class="modal_label">T-10-Yes</label></h6>
<h6 class="pull-right">Task Date : <label class="modal_label">17 May, 2018</label></h6>
</div>
<div class="modal-body">
<table class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Title</th>
<th>Progress</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Review system generated T&Cs for deploying to website</td>
<td>0%</td>
<td>Pending</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<div class="pull-left">
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#editTasks_50" value="50" id="editModal">Edit</button>
</div>
<div class="pull-right">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div id="editTasks_50" class="modal fade show" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="pull-left">
<input type="button" class="btn btn-info" value="Update">
</div>
<div class="pull-right">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
I need that when I click on edit button then edit Modal is open and view modal is closed.
Here is an working example of how you can do it.
$("#editModal").click(function() {
var button = $(this);
var id = button.val();
button.closest(".modal").modal('hide');
$('#' + id).modal('show');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
View
<div id="viewTasks_50" class="modal fade show" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h6 class="pull-left">Code : <label class="modal_label">T-10-Yes</label></h6>
<h6 class="pull-right">Task Date : <label class="modal_label">17 May, 2018</label></h6>
</div>
<div class="modal-body">
<table class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Title</th>
<th>Progress</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Review system generated T&Cs for deploying to website</td>
<td>0%</td>
<td>Pending</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<div class="pull-left">
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#editTasks_50" value="50" id="editModal">Edit</button>
</div>
<div class="pull-right">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div id="editTasks_50" class="modal fade show" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="pull-left">
<input type="button" class="btn btn-info" value="Update">
</div>
<div class="pull-right">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
What I would say is close all the modals that are opened and then open only the modal you want. Something like:
$("#editModal").click(function() {
var id = $("#editModal").val();
$('.modal').modal('hide');
$('#' + id).modal('show');
});
Since all modal have a common class 'modal' it will close all the
modal and show the modal you want.
Hope this helps!!
Cheers
This is a bit more dynamic.
let modals = [
{
'callToAction': 'toggleVisitorProfileModal',
'modalToToggle': 'visitorProfileModal'
}, {
'callToAction': 'toggleBuyTokensModal',
'modalToToggle': 'tokensModal'
},
];
$.each(modals, function (key, value) {
$('.' + value.callToAction).on('click', function () {
if ($('#' + value.modalToToggle).hasClass('in') === false) {
$('.modal').modal('hide');
$('.modal-backdrop').remove();
$('#' + value.modalToToggle).modal('show');
}
}
)
});
Whenever you click an element to activate a modal
Check if the current modal is open. An open modal has the IN class
associated. If this is false we know that the modal you try to open
is currently NOT open.
We then close all modals.
When there are multiple modals on the same page you might come across the black background not disappearing. To remove this we remove all elements containing the MODAL-BACKDROP class.
And last we show the modal that is toggled.
Closing all Modals in background
$('.modal').modal('hide');
Now, opening new Modal
$('#myModal').modal('show');
I know this post is too old but I spend a lot of time in this type of issues and it's a simple solution by hiding modals in the webpage and then show new modal
$('#mymodal').modal('hide');
it works correct,
If not closing modal then use below script
$('#mymodal').modal('hide');
$('div.modal-backdrop.fade.in').attr('class','none');

Knockout loading and saving view model

I have the following code, is an example of one view model that I'm using in two sections (2 bootstrap modals). But I can't access the value from the second view model "UpdateviewModel". When I click Save button in the first Modal there is no problem, I get the Name value, but when I click Update button in the second modal the Name value is undefined. What am I doing wrong?
$(document).ready(function () {
CustomerSetupViewModel = function () {
var self = this;
self.Name = ko.observable();
var CustomerSetup = {
Name: self.Name
};
self.CustomerSetup = ko.observable();
self.GetCustomer = function () {
var data = { Name: "A00622" };
self.CustomerSetup(data);
}
Save = function () {
var test = viewModel.Name();
}
Update = function () {
var test2 = UpdateviewModel.Name();
}
}
var viewModel = new CustomerSetupViewModel();
var UpdateviewModel = new CustomerSetupViewModel();
ko.applyBindings(viewModel, document.getElementById("NewCustomer"));
ko.applyBindings(UpdateviewModel, document.getElementById("UpdateCustomer"));
$("#updateCustomer").click(function () {
UpdateviewModel.GetCustomer();
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<a id="addCustomer" class="btn btn-default" data-toggle="modal" data-target="#NewCustomer">Add Customer</a>
<a id="updateCustomer" class="btn btn-default" data-toggle="modal" data-target="#UpdateCustomer">Update Customer</a>
<!-- Modal -->
<div id="NewCustomer" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="NewModalLabel">
<div class="modal-dialog" 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>
<h4 class="modal-title" id="NewModalLabel">New Customer</h4>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="row">
<div class="col-md-4">
<label>Customer Name</label>
<input type="text" id="Name" class="form-control" data-bind="value: Name" />
</div>
</div>
</div>
<div class="modal-footer">
<a role="button" class="btn btn-default" data-dismiss="modal">Close</a>
<a role="button" class="btn btn-primary" data-bind="click: Save">Save</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div id="UpdateCustomer" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="NewModalLabel">
<div class="modal-dialog" 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>
<h4 class="modal-title" id="NewModalLabel">New Customer</h4>
</div>
<div class="modal-body" data-bind="foreach: CustomerSetup">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="row">
<div class="col-md-4">
<label>Customer Name</label>
<input type="text" id="Name" class="form-control" data-bind="value: Name" />
</div>
</div>
</div>
<div class="modal-footer">
<a role="button" class="btn btn-default" data-dismiss="modal">Close</a>
<a id="Update" class="btn btn-default" data-bind="click: Update">Update</a>
</div>
</div>
</div>
</div>
</div>
</div>
I am not sure about the problem, as I tried to log your UpdateviewModel it was an empty object.
I made your code works but there will be changes just for coding structure using mainViewModel and its subViewModel contents.
$(document).ready(function () {
var CustomerSetupViewModel = function () {
var self = this;
self.Name = ko.observable("");
self.Save = function () {
var test = self.Name();
alert(test);
}
self.Update = function () {
var test2 = self.Name();
alert(test2);
}
}
var MainViewModel = function () {
console.log("init")
self = this;
self.CustAdd = new CustomerSetupViewModel();
self.CustUpd = new CustomerSetupViewModel();
}
vm = new MainViewModel();
ko.applyBindings(vm);
$("#updateCustomer").click(function () {
vm.CustUpd.Name("ToBeUpdated");
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<a id="addCustomer" class="btn btn-default" data-toggle="modal" data-target="#NewCustomer">Add Customer</a>
<a id="updateCustomer" class="btn btn-default" data-toggle="modal" data-target="#UpdateCustomer">Update Customer</a>
<!-- Modal -->
<div id="NewCustomer" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="NewModalLabel">
<div class="modal-dialog" 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>
<h4 class="modal-title" id="NewModalLabel">New Customer</h4>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="row">
<div class="col-md-4">
<label>Customer Name</label>
<input type="text" id="Name" class="form-control" data-bind="value: CustAdd.Name" />
</div>
</div>
</div>
<div class="modal-footer">
<a role="button" class="btn btn-default" data-dismiss="modal">Close</a>
<a role="button" class="btn btn-primary" data-bind="click: CustAdd.Save">Save</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div id="UpdateCustomer" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="UpdateModalLabel">
<div class="modal-dialog" 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>
<h4 class="modal-title" id="UpdateModalLabel">Update Customer</h4>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="row">
<div class="col-md-4">
<label>Customer Name</label>
<input type="text" id="Name" class="form-control" data-bind="value: CustUpd.Name" />
</div>
</div>
</div>
<div class="modal-footer">
<a role="button" class="btn btn-default" data-dismiss="modal">Close</a>
<a role="button" class="btn btn-primary" data-bind="click: CustUpd.Update">Update</a>
</div>
</div>
</div>
</div>
</div>
</div>

Check the last and the first page and disable button next-previous buttons accordingly

I've 2 pop-ups to display the user list & admin list which would display 10 results per page, which is working fine.
I'm getting the page nos. from the java servlet in the JSON.
Note: There are 2 parameters passed in the url - resType and pageNo.
pageNo. returns 0, 10, 20 ...(multiples of 10).
resType: checks what sort of result I want. You can ignore this part.
So my url in the createTable function looks something like this instead -
How do I disable the previous button, when it is the first page? Likewise, how do I disable the last button, when it is the last page?
Here's the code.
var currentPageNo = 0; // Keep track of currently displayed page
$('.next-btn').unbind("click").on("click",function(){ // Give buttons an ID (include them in HTML as hidden)
userList(currentPageNo+10);
adminList(currentPageNo+10);
});
$('.prev-btn').unbind("click").on("click",function(){
userList(currentPageNo-10);
adminList(currentPageNo-10);
});
function userList(pageNo) {
var resType="userList";
createTable(resType,pageNo);
}
function adminList(pageNo) {
var resType="adminList";
createTable(resType,pageNo);
}
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the "prev" button:
$('.prev-btn').toggle(pageNo > 0);
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&start="+pageNo, function(data) {
$('#datatable tr:has(td)').empty();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('.next-btn').toggle(data.results.length > 10);
// Slice results, so 11th record is not included:
data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
var json = JSON.stringify(record);
$('#datatable').append(
$('<tr>').append(
$('<td>').append(
$('<input>').attr('type', 'checkbox')
.addClass('selectRow')
.val(json),
(i+1+pageNo) // display row number
),
$('<td>').append(
$('<a>').attr('href', record.picture.thumbnail)
.addClass('imgurl')
.attr('target', '_blank')
.text(record.name.first)
),
$('<td>').append(record.dob)
)
);
});
// Show the prev and/or buttons
}).fail(function(error) {
console.log("**********AJAX ERROR: " + error);
});
}
var savedData = []; // The objects as array, so to have an order.
function saveData(){
var errors = [];
// Add selected to map
$('input.selectRow:checked').each(function(count) {
// Get the JSON that is stored as value for the checkbox
var obj = JSON.parse($(this).val());
// See if this URL was already collected (that's easy with Set)
if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it
savedData.push(obj);
}
});
refreshDisplay();
if (errors.length) {
alert('The following were already selected:\n' + errors.join('\n'));
}
}
function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}
function logSavedData(){
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(savedData, null, 2));
}
function getIndex(elem) {
return $(elem).parent('.parent').index();
}
$(document).on('click', '.removeMe', function() {
// Delete this from the saved Data
savedData.splice(getIndex(this), 1);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index, 2, savedData[index+1], savedData[index]);
// And redisplay
refreshDisplay();
});
$(document).on('click', ".top-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
// And redisplay
refreshDisplay();
});
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
$(".top-btn, .down-btn").prop("disabled", false).show();
$(".parent:first").find(".top-btn").prop("disabled", true).hide();
$(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
$(document).ready(function(){
$('#showExtForm-btn').click(function(){
$('#extUser').toggle();
});
$("#extUserForm").submit(function(e){
addExtUser();
return false;
});
});
function addExtUser() {
var extObj = {
name: {
title: "mr", // No ladies? :-)
first: $("#name").val(),
// Last name ?
},
dob: $("#dob").val(),
picture: {
thumbnail: $("#myImg").val()
},
location: { // maybe also ask for this info?
}
};
savedData.push(extObj);
refreshDisplay(); // Will show some undefined stuff (location...)
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#userList" onclick="userList(0)">User List</button>
<button class="btn btn-primary btn-sm" onclick="logSavedData()">Get Saved Data</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#adminList" onclick="adminList(0)">User Admin</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#extUser">Open External Form</button>
<div class="modal fade" id="userList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="adminList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Admin List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="extUser" role="dialog">
<div class="modal-dialog modal-lg">
<!-- External User-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add External User</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="extUserForm">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="name" name="name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="myImg">Image:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="myImg" name="myImg" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="dob">DOB:</label>
<div class="col-sm-8">
<input type="date" class="form-control" id="dob" name="dob" required>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-primary btn-sm">Submit</button>
</div>
<div class="col-sm-3">
<button type="reset" class="btn btn-primary btn-sm">Reset</button>
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container"></div>
In createTable a distinction should be made between which of the two tables you want to populate. So you should use a selector like:
$('#' + resType + ' table')
The same distinction should be made for the prev/next button selectors:
$('#' + resType + ' .next-btn')
And it is also wrong to call both userList and adminList in the same click handler, as it will make you skip a page of results (from 0 to 20). You should call the appropriate one based one the selector. So change your prev/next click handlers to:
// Select button that is descendant of userList
$('#userList .prev-btn').click(function(){
userList(currentPageNo-10);
});
$('#userList .next-btn').click(function(){
userList(currentPageNo+10);
});
$('#adminList .prev-btn').click(function(){
adminList(currentPageNo-10);
});
$('#adminList .next-btn').click(function(){
adminList(currentPageNo+10);
});
Finally, the code will hide the next button if you change one thing on the server: let it return 11 records instead of 10. The JavaScript code can then know if after the 10 records there is still more data (without showing the 11th record).
Here is updated code:
var currentPageNo = 0; // Keep track of currently displayed page
// Select button that is descendant of userList
$('#userList .prev-btn').click(function(){
userList(currentPageNo-10);
});
$('#userList .next-btn').click(function(){
userList(currentPageNo+10);
});
$('#adminList .prev-btn').click(function(){
adminList(currentPageNo-10);
});
$('#adminList .next-btn').click(function(){
adminList(currentPageNo+10);
});
function userList(pageNo) {
var resType="userList";
createTable(resType,pageNo);
}
function adminList(pageNo) {
var resType="adminList";
createTable(resType,pageNo);
}
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the correct "prev" button:
$('#' + resType + ' .prev-btn').toggle(pageNo > 0);
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
var $table = $('#' + resType + ' table');
$('tr:has(td)', $table).empty();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('#' + resType + ' .next-btn').toggle(data.results.length > 10);
// Slice results, so 11th record is not included:
data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
var json = JSON.stringify(record);
$table.append(
$('<tr>').append(
$('<td>').append(
$('<input>').attr('type', 'checkbox')
.addClass('selectRow')
.val(json),
(i+1+pageNo) // display row number
),
$('<td>').append(
$('<a>').attr('href', record.picture.thumbnail)
.addClass('imgurl')
.attr('target', '_blank')
.text(record.name.first)
),
$('<td>').append(record.dob)
)
);
});
// Show the prev and/or buttons
}).fail(function(error) {
console.log("**********AJAX ERROR: " + error);
});
}
var savedData = []; // The objects as array, so to have an order.
function saveData(){
var errors = [];
// Add selected to map
$('input.selectRow:checked').each(function(count) {
// Get the JSON that is stored as value for the checkbox
var obj = JSON.parse($(this).val());
// See if this URL was already collected (that's easy with Set)
if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it
savedData.push(obj);
}
});
refreshDisplay();
if (errors.length) {
alert('The following were already selected:\n' + errors.join('\n'));
}
}
function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}
function logSavedData(){
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(savedData, null, 2));
}
function getIndex(elem) {
return $(elem).parent('.parent').index();
}
$(document).on('click', '.removeMe', function() {
// Delete this from the saved Data
savedData.splice(getIndex(this), 1);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index, 2, savedData[index+1], savedData[index]);
// And redisplay
refreshDisplay();
});
$(document).on('click', ".top-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
// And redisplay
refreshDisplay();
});
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
$(".top-btn, .down-btn").prop("disabled", false).show();
$(".parent:first").find(".top-btn").prop("disabled", true).hide();
$(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
$(document).ready(function(){
$('#showExtForm-btn').click(function(){
$('#extUser').toggle();
});
$("#extUserForm").submit(function(e){
addExtUser();
return false;
});
});
function addExtUser() {
var extObj = {
name: {
title: "mr", // No ladies? :-)
first: $("#name").val(),
// Last name ?
},
dob: $("#dob").val(),
picture: {
thumbnail: $("#myImg").val()
},
location: { // maybe also ask for this info?
}
};
savedData.push(extObj);
refreshDisplay(); // Will show some undefined stuff (location...)
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#userList" onclick="userList(0)">User List</button>
<button class="btn btn-primary btn-sm" onclick="logSavedData()">Get Saved Data</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#adminList" onclick="adminList(0)">User Admin</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#extUser">Open External Form</button>
<div class="modal fade" id="userList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="adminList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Admin List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="extUser" role="dialog">
<div class="modal-dialog modal-lg">
<!-- External User-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add External User</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="extUserForm">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="name" name="name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="myImg">Image:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="myImg" name="myImg" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="dob">DOB:</label>
<div class="col-sm-8">
<input type="date" class="form-control" id="dob" name="dob" required>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-primary btn-sm">Submit</button>
</div>
<div class="col-sm-3">
<button type="reset" class="btn btn-primary btn-sm">Reset</button>
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container"></div>

Categories