let http = new XMLHttpRequest();
http.open('get', 'recipe.json', true);
http.send();
http.onload = function () {
if (this.readyState == 4 && this.status == 200) {
let products = JSON.parse(this.responseText);
let output = "";
for (let item of products) {
output += `
<div class="product">
<img src="${item.imageURL}" alt="${item.imageURL}">
<p class="title">${item.name}</p>
</p>
<button type="button" name="${item.name}" class="btn btn-primary modaltrigger" id="btn${item.name}" data-bs-toggle="modal" data-bs-target="#${item.name}">
Get Recipe
</button>
</div>
<div class="modal fade" id="${item.name}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
${item.data}
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
`;
}
document.querySelector(".products").innerHTML = output;
}
}
$(document).ready(function () {
$(".modaltrigger").click(function () {
var id = $(this).attr('name');
$('#' + id).modal();
});
});
I want to make a dynamic modal for all the products in my json file with help of javascript.
When i click on "Get recipe" Button the modal doesn't pops up and i get an error "ARIA hidden element must not contain focusable elements" in Dev tools.
You are not calling your modal function with your modals id.
$("#myModal").modal();
Jquery selector must match modal elements id to modal to show up.
And you dont have to create a modal clone for each product you can just change contents of the modal.This will speed up your page loading time.
let http = new XMLHttpRequest();
http.open('get', 'recipe.json', true);
http.send();
http.onload = function () {
if (this.readyState == 4 && this.status == 200) {
let products = JSON.parse(this.responseText);
let output = "";
for (let item of products) {
output += `
<div class="product">
<img src="${item.imageURL}" alt="${item.imageURL}">
<p class="title">${item.name}</p>
</p>
<button type="button" name="${item.name}" class="btn btn-primary modaltrigger" data-bs-toggle="modal" data-bs-target="#${item.name}">
Get Recipe
</button>
</div>
<div class="modal fade" id="${item.name}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
</div>
<div class="modal-body">
${item.data}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
`;
}
document.querySelector(".products").innerHTML = output;
}
}
$(document).ready(function () {
$(".modaltrigger").click(function () {
var id = $(this).attr('name');
$('#'+id).modal();
});
});
Try this.
Related
With the following code I'm trying to validate an entry field in JavaScript. The validation requires only 10 characters. When you authenticate, it is supposed to display a modal with a confirmation message:
function myFunction() {
var con_code, text;
//getting the field
con_code = document.getElementById("con_code").value;
if ($.trim($('con_code').val()).length == 0) {
text = "Authentication code is not valid";
}
//trigger to the modal if it meets the condition
$(document).ready(function() {
$("#con_code").click(function() {
$("#myModal").modal();
});
});
document.getElementById("error_con_code").innerHTML = text;
}
<div class="container">
<h2>Activate Modal with JavaScript</h2>
<!-- Trigger the modal with a button -->
<div class="form-group">
<label>Confirmation Code.</label>
<input type="text" name="con_code" id="con_code" class="form-control" required="required" placeholder="Enter your Confirmation Code" />
<br> //the error code display
<span id="error_con_code" class="text-danger"></span>
<br> //the authenticate button
<button type="button" class="btn btn-success btn-sm" id="con_code" onclick="myFunction()">Authenticate</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button> //the modal
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
However, it is not authenticating the confirm code. How can I fix it?
You have an error at:
if($.trim($('con_code').val()).length ==0){...}.
It should be $('#con_code')
Also you have 2 elements with the same id="con_code".
Please check with the following codes.
I am assuming you want to show the modal when there is 10 chars in the input field. If the rule changes, then please edit at: 'if ($.trim(con_code.val()).length != 10) {}' in the below codes.
$(document).ready(function() {
myFunction();
});
function myFunction() {
$("#con_code_btn").click(function() {
var con_code = $('#con_code');
var error_con_code = $('#error_con_code');
error_con_code.html('');// Remove Previous Error Message(if any);
if ($.trim(con_code.val()).length != 10) {
error_con_code.html("entication code is not valid");
}
else {
$("#myModal").modal();
}
});
}
Also please change the id of the button to "con_code_btn" in the form:
<button type="button" class="btn btn-success btn-sm" id="con_code_btn" onclick="myFunction()">Authenticate</button>
I'm creating a ASP.NET Webpage using Bootstrap and jQuery.
I have recently implemented a modal to show a log. The modal is shown when clicking a link:
<a data-toggle="modal" data-target="#logData">Open</a>
<div class="modal fade" id="logData" tabindex="-1" role="dialog" aria-labelledby="logDataLabel">
<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="myModalLabel">Log for #Html.DisplayFor(model => model.Alias)</h4>
</div>
<div class="modal-body">
<textarea class="form-control log" rows="5" placeholder="Log is empty.">#Html.DisplayFor(model => model.Log)</textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The modal contains a textarea that doesn't autoresize.
I have found the following code:
$('textarea').each(function () {
this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
which should enable my textareas to autoresize and it works other places in my code, but not in this modal above. At least not when typing in the textarea, but upon opening the modal it does seem to autoresize.
Does anyone have an idea of why? And eventually on how to fix it?
Thanks!
You can use this code which will work if the textarea is not hidden (e.g in a modal that is not shown yet)
let setHeight = (input) => {
input.style.overflow = 'hidden';
input.style.height = 0;
input.style.height = `${ input.scrollHeight + 2 }px`;
};
$('textarea').on('input, keyup', function () {
setHeight(this);
})
for bootstrap modal, u can do something like this:
$('.modal').on('shown.bs.modal', function () {
$(this).find('textarea').each(function () {
setHeight(this);
});
})
I've replace my JS Confirm function with a bootstrap modal, this modal is async so I also had to change my code and add callbacks.
What I'm trying to is:
Pseudo Code
if `simApp["con1"]` then show first modal with 2 buttons
if return is clicked -> close modal.
if continue is clicked -> open second modal
if return is clicked -> close modal
if submit is clicked -> submit form (not included in code)
else open second modal
if return is clicked -> close modal
if submit is clicked -> submit form (not included in code)
This is all very simple when you don't use callbacks, which I'm fairly new to.
So this is what I did, its NOT working, I guess it has something to do with the generic use of the modal. - JSFIDDLE
HTML
<div class="modal fade" id="generalModalTwoButtons" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" id="btn-return" class="btn btn-primary" data-dismiss="modal"></button>
<button type="button" id="btn-submit" class="btn btn-primary" data-dismiss="modal"></button>
</div>
</div>
</div>
</div>
<button id="go">GO</button>
JS
simApp = {};
simApp["con1"] = true; //in this code I hard-coded the conditions to ture
simApp["arr"] = [1];
$("#go").click(function () {
if (simApp["con1"] && simApp["arr"].length < 5) {
var msg = '<p>msg1</p>';
updateGeneralTwoButtonsModal('#a94442', 'header1', msg, 'Return', 'Continue', function (result) {
if (result === true) {
confirmBeforeSubmit(submitFormApproved);
}
});
} else {
confirmBeforeSubmit(submitFormApproved)
}
});
function submitFormApproved(result) {
if (result === true) {
console.warn("submitted");
}
}
function confirmBeforeSubmit(callback) {
var msg = '<p>msg2</p>';
if (simApp["con1"]) msg = '<p>msg2-changed</p>';
updateGeneralTwoButtonsModal('#31708f', 'header2', msg, 'Return', 'Submit', callback);
}
function updateGeneralTwoButtonsModal(color, title, body, btnReturn, btnSubmit, callback) {
var confirm = $('#generalModalTwoButtons');
confirm.find('.modal-header').css('color', color);
confirm.find('.modal-title').text(title);
confirm.find('.modal-body').html(body);
confirm.modal('show');
confirm.find('#btn-return').html(btnReturn).off('click').click(function () {
confirm.modal('hide');
callback(false);
});
confirm.find('#btn-submit').html(btnSubmit).off('click').click(function () {
confirm.modal('hide');
callback(true);
});
}
Any idea what I did wrong?
P.S - for learning purposes I would like to avoid using promises on this solution.
Here you go, the main problem I found was the fact that you don't block the propagation of the click event which automatically closes the modals. I added the event handler stopPropagation in the event of the continue/submit button.
simApp = {};
simApp["con1"] = true;
simApp["arr"] = [1];
$("#go").click(function () {
if (simApp["con1"] && simApp["arr"].length < 5) {
var msg = '<p>msg1</p>';
updateGeneralTwoButtonsModal('#a94442', 'header1', msg, 'Return', 'Continue', function (result) {
if (result === true) {
confirmBeforeSubmit(submitFormApproved);
}
});
} else {
confirmBeforeSubmit(submitFormApproved)
}
});
function submitFormApproved(result) {
if (result === true) {
console.warn("submitted");
}
}
function confirmBeforeSubmit(callback) {
var msg = '<p>msg2</p>';
if (simApp["con1"]) msg = '<p>msg2-changed</p>';
updateGeneralTwoButtonsModal('#31708f', 'header2', msg, 'Return', 'Submit', callback);
}
function updateGeneralTwoButtonsModal(color, title, body, btnReturn, btnSubmit, callback) {
var confirm = $('#generalModalTwoButtons');
confirm.find('.modal-header').css('color', color);
confirm.find('.modal-title').text(title);
confirm.find('.modal-body').html(body);
confirm.modal('show')
confirm.find('#btn-return').html(btnReturn).off('click').click(function () {
confirm.modal('hide');
callback(false);
});
confirm.find('#btn-submit').html(btnSubmit).off('click').click(function (event) {
event.preventDefault();
event.stopPropagation();
if(btnSubmit != "Continue") {
confirm.modal('hide');
}
callback(true);
});
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/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.5/js/bootstrap.min.js"></script>
<div class="modal fade" id="generalModalTwoButtons" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" id="btn-return" class="btn btn-primary" data-dismiss="modal"></button>
<button type="button" id="btn-submit" class="btn btn-primary" data-dismiss="modal"></button>
</div>
</div>
</div>
</div>
<button id="go">GO</button>
I have the following lines of code in my webpage - example/demo.
HTML:
<p data-toggle="modal" data-target="#messagesModal">Messages <span class="badge">2</span>
</p>
<!-- Modal -->
<div class="modal fade" id="messagesModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Messages</h4>
</div>
<div class="modal-body">
<div class="alert fade in">
×
<strong>Message 01</strong>:
<p>Lipsum Ipsum
</p>
</div>
<div class="alert fade in">
×
<strong>Message 02</strong>:
<p>Ipsum Lipsum</p>
</div>
</div>
<div class="modal-footer">
<div class="col-md-8 pull-left">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
How can I update the badge to represent the correct amount of messages in the modal?
For example, when the user closes or removes a message in the modal, the badge will go from displaying the number 2 to 1?
Also, is it possible to display the text "There are no more messages." when all of the messages have been removed?
Try this:
//Find message number initially, before editing
$(".badge").text($(".alert").length);
//when the modal is closed
$('#messagesModal').on('hidden.bs.modal', function () {
//Set .badge text equal to the length of the .alert array, i.e the number of messages
$(".badge").text($(".alert").length);
//If there are no '.alert' divs, i.e. no messages
if ($(".alert").length == 0) {
$(".badge").text("No messages");
}
});
This takes all the .alert elements (messages) into an array, and sees how long that array is (i.e. how many messages there are).
Then, it updates .badge to reflect that number.
Working JSFiddle: http://jsfiddle.net/joe_young/62hbqmtp/
Well... I've spend some time, but all that you should do for now:
populate message array with your actual data;
add some actual AJAX for removing messages.
So...
$(function() {
var informer = $("#messageInformer a");
var refreshBadge = function(messageCount) {
var badge = informer.find(".badge");
if (messageCount > 0) {
if (!badge.length) {
informer.text("Messages ");
informer.append("<span class=\"badge\">" + messageCount + "</span>");
} else {
badge.text(messageCount);
}
} else {
informer.text("No messages");
}
};
var buildMessage = function(message) {
var htmlMessage = "<div class=\"alert fade in\">";
htmlMessage += "×";
htmlMessage += "<strong>" + message.title + "</strong>:";
htmlMessage += "<p>" + message.text + "</p>";
return htmlMessage;
}
// There should be real data
var messages = [
{ id: "1", title: "Message 01", text: "Lipsum Ipsum" },
{ id: "2", title: "Message 02", text: "Ipsum Lipsum" }];
refreshBadge(messages.length);
informer.on("click", function(e) {
e.preventDefault();
var modalBody = $(".modal-body");
modalBody.empty();
for (var i = 0; i < messages.length; i++) {
modalBody.append(buildMessage(messages[i]));
}
});
$("body").delegate(".alert .close", "click", function() {
var messageId = $(this).data("id");
// There should be some AJAX possibly
messages = messages.filter(function(el) {
return el.id != messageId;
});
if (messages.length == 0) {
$("#messagesModal").modal("hide");
}
refreshBadge(messages.length);
});
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<p data-toggle="modal" data-target="#messagesModal" id="messageInformer">Messages <span class="badge"></span>
</p>
<!-- Modal -->
<div class="modal fade" id="messagesModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Messages</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="col-md-8 pull-left">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
I am using bootstrap to invoke a simple modal form which contains only a textarea field and couple of buttons. I am setting some custom text (variable length) in the textarea while invoking the modal form. What I want is to focus on the textarea field after the custom text so the user can start typing after that. I have mentioned my implemenation of this below. Can anyone tell how to achieve this?
Here is the Fiddle: http://jsfiddle.net/jLymtdg8/
A bit explanation here as well -
Here is my modal (all bootstrap stuff)-
<div class="modal fade" id="msg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Type a message</h4>
</div>
<div class="modal-body">
<textarea id="Message" class="form-control"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Cancel</button>
<button id="PostModalButton" class="btn btn-primary btn-sm">Post</button>
</div>
</div>
</div>
And here is how it gets invoked -
<div class="pull-right">
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#msg" data-screenname="Type after this">
Post A Message
</button>
</div>
This is how I am prefilling the textarea and setting focus, but this is only setting cursor on first line rather than after screen_name -
$(this).on('shown.bs.modal', '#msg', setFieldAndFocus)
var setFieldAndFocus = function () {
var screen_name = $("button[data-target='#msg']").data("screenname");
$("#Message").val(screen_name + " ");
$("#Message").focus();
};
Sam you can try the following javascript code:-
var screen_name = '',
old_message = '',
new_message = '';
$("#msg").on('shown', function() {
screen_name = $("button[data-target='#msg']").data("screenname"),
old_message = $.trim($('#Message').val()),
new_message = ( old_message.length == 0 ) ? screen_name : old_message;
$("#Message").focus().val(new_message + " ");
});
Let me explain why i have used this code. From the js fiddle link that you have provided what i understand is you are using the bootstrap 2 version, but the code that you are using
$("#msg").on('shown.bs.modal', function(){
...
}
was introduced only in bootstrap 3. so I have changed it to
$("#msg").on('shown', function(){
...
}
and the line
$("#Message").focus().val(new_message + " ");
is used so that you can set the focus after the custom text.I hope this will resolve your issue.
You can take reference of this link : http://jsfiddle.net/3kgbG/433/
It is working for me.
$('.launchConfirm').on('click', function (e) {
$('#confirm')
.modal({ backdrop: 'static', keyboard: false })
.on('')
.one('click', '[data-value]', function (e) {
if($(this).data('value')) {
//alert('confirmed');
} else {
//alert('canceled');
}
});
});
$('#confirm').on('shown', function () {
$('#txtDemo').val($('#txtDemo').val());
$('#txtDemo').focus();
// do something…
})
body,
.modal-open .page-container,
.modal-open .page-container .navbar-fixed-top,
.modal-open .modal-container {
overflow-y: scroll;
}
#media (max-width: 979px) {
.modal-open .page-container .navbar-fixed-top{
overflow-y: visible;
}
}
<div class="page-container">
<div class="container">
<br />
<button class="btn launchConfirm">Launch Confirm</button>
</div>
</div>
<div id="confirm" class="modal hide fade">
<div class="modal-body">
Do you want to continue?
<input id="txtDemo" type="text" value="Jayesh" class="form-control"/>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-primary" data-value="1">Continue</button>
<button type="button" data-dismiss="modal" class="btn" data-value="0">Cancel</button>
</div>
</div>