Highlighting a text from a document in angular js - javascript

I am new to angular js. So, I want to highlight certain text from a HTML document.
My code is like -
service -
getDocumentAsHTML: function (docType, filename) {
var url = 'rez' + '/htmlContent/' + docType + '/' + filename;
var config = {};
config.headers = {
"Accept": "text/html",
"X-AUTH-TOKEN": loginService.getAuthToken()
};
return $http.get(url, config)
.then(function (response) {
return response.data;
},
function (error) {
$log.error(error);
return $q.reject(error);
});
},
and to highlight, I have written one function like -
$scope.highlight = function(content, text, className, notByWordBoundry){
var RegExpEscapeText, str;
if (!(content && content.replace)) {
return '';
}
if (!text) {
return $sce.trustAsHtml(content);
}
if (!className) {
className = 'mark';
}
RegExpEscapeText = text.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
if (!notByWordBoundry) {
str = new RegExp('(\\b)' + RegExpEscapeText + '(\\b)','gi');
} else {
str = new RegExp(RegExpEscapeText,'gi');
}
return $sce.trustAsHtml(content.replace(str , '<span class=' + className + '>$&</span>'));
};
So, I have a button , on click it opens a model which contains the html document where I can edit the document content. so, now I want to highlight a certain text from this document.So, for that
My html is -
<div id="htmlEditorModal" class="modal fade" role="dialog" aria-labelledby="confirmModal" aria-hidden="true" data-backdrop="static" data-keyboard="false" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="confirmback()">×</button>
<h4 class="modal-title">
<strong>Edit Document</strong>
</h4>
</div>
<div class="modal-body">
<div ng-show="fetchingDocumentAsHTML || updatingDocumentAsHTML"
class="loading-backdrop">
<div class="spinner-container text-center">
<h3>
<strong>{{htmlEditorLoadingMsg}}</strong>
<span class="text-color"><i class="fa fa-spin fa-refresh"></i></span>
</h3>
</div>
</div>
<div text-angular
class="html-editor-container "
ng-hide="fetchingDocumentAsHTML || updatingDocumentAsHTML"
ng-model="htmlDocument">
</div>
</div>
<div class="modal-footer">
<button class="button-size btn btn-labeled btn-info pull-left"
ng-click="confirmback()">
<i class="fa fa-arrow-left" aria-hidden="true"></i>
<span class="small-left-margin">Back</span>
</button>
<button class="button-size btn btn-primary pull-right"
ng-disabled="fetchingDocumentAsHTML || updatingDocumentAsHTML"
ng-click="updateDocument()"
<i class="fa fa-save" aria-hidden="true"></i>
<span class="small-left-margin">Save</span>
</button>
</div>
</div>
</div>
</div>
So, In this was planning to use
<span ng-bind-html="highlight(value, text)"></span>
I am not able to highlight the text.Can any one help me ?

Related

How to add interactive modal dynamically into html with Javascript

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.

Is there a possibility to bind the Form to a modal bootstrap window without using the load call?

I'm using ajax to make a request and open a modal bootstrap window afterwards. The problem is that when I use ajax, I make a request to my controller, and the return (modal content) I load as follows:
//modal loading
$('#contentModalFinanceiroParcela').html(data);
//exibição da modal
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
So far, everything perfect. The problem is that from then on, I can't bind the form to register the submit event of the form. In the function bindFormFinanceiroParcela, no matter how much I pass the "dialog", bind does not work.
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
Searching the forums, I found that the process works if I load the modal using the "load" command, as below, but I can't do it like that, otherwise it will make a second request to the controller, because previously, I already used ajax .
//That way it works, but I can't use it.
$('#contentModalFinanceiroParcela').load(url, function () {
$('#modalFinanceiroParcela').modal({
keyboard: true
}, 'show');
// Inscreve o evento submit
bindFormFinanceiroParcela(this);
stopLoadPage();
});
Is there a possibility that I can bind the form without using the "load" command mentioned in the script above?
function openModalFinanceiroParcelaSemURL(data) {
startLoadPage();
//Create the modal window block in the body of the page
if (!$("#modalFinanceiroParcela").data('bs.modal'))
CreateModalFinanceiroParcela();
//Load modal content via ajax request
$('#contentModalFinanceiroParcela').html(data);
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
stopLoadPage();
}
function bindFormFinanceiroParcela(dialog) {
$('form', dialog).submit(function (e, i) {
if ($(this).valid() || i) {
startLoadOneMoment();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
window.location = window.location;
} else {
$('#contentModalFinanceiroParcela').html(result);
bindFormFinanceiroParcela();
}
stopLoadOneMoment();
}
});
return false;
} else {
return false;
}
});
function CreateModalFinanceiroParcela() {
var html = '<div class="modal modal-primary modal-system" tabindex="-1" role="dialog" id="modalFinanceiroParcela" data-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="content-modal-system" id="contentModalFinanceiroParcela"></div></div></div></div>';
$("body").append(html);
}
RAZOR DELETE:
#using Retaguarda.Domain.Enuns
#model Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela.FinanceiroParcelaViewModel
#{
ViewData["Title"] = "Excluir Parcela";
Layout = null;
}
<div>
<form asp-action="Delete" id="frm-excluir-financeiro-parcela">
#Html.AntiForgeryToken()
<div class="modal-shadow">
<div class="modal-header modal-header-primary">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4><i class="modal-title text-center glyphicon glyphicon-trash"></i> #ViewData["Title"] </h4>
</div>
<div class="panel">
<div class="panel-body container-fluid pt-15 pl-15 pr-15">
<div class="form-horizontal">
<vc:summary />
<br />
<div class="message-delete">
#Html.HiddenFor(model => model.Id, new { id = "hid-financeiro-parcela-id" })
<i class="icon fa-trash" aria-hidden="true"></i>
<p>
Tem certeza de que deseja excluir a parcela #(Model.Parcela)?<br />
</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-md-offset-2 col-md-10">
<div class="float-right">
<div class="btn-group btn-group-sm mr-auto"
role="group">
<div class="btn-group btn-group-sm" role="group">
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
<button id="btn-excluir-financeiro-parcela" type="button" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>
<button id="btn-cancelar-financeiro-parcela" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Ajax call
$('#dtFinanceiroParcela').on('click', 'tr .btn-excluir-financeiro-parcela', function (e) {
e.preventDefault();
startLoadOneMoment();
var id = $(this).attr('data-id');
var data = { id: id };
var dataURL = jQuery.param(data);
$.ajax({
url: "/financeiro-parcela-gerenciar/remover-financeiro-parcela/" + id,
type: "GET",
// data: dataURL,
contentType: "application/json",
async: false,
success: function (result) {
if (typeof result.success !== 'undefined') {
if (!result.success) {
stopLoadOneMoment();
swal("Oops", result.message, "error");
return false;
}
}
// alert(this.url);
stopLoadOneMoment();
openModalFinanceiroParcelaSemURL(result);
return false;
},
error: function () {
stopLoadOneMoment();
alert("Oops! Algo deu errado.");
return false;
}
});
Your form inside razor does not contain any submit button because its commented out.
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
Remove the comment or change the type of the other button to "submit"
I guess the submit event is attached successfully but never called due to the missing submit button inside your form.

Increasing space between rows in table dynamically created from js function

I have a JS function in a modal that is creating a table in a grid from data being returned from a controller action. It works fine, however I wish there was a little more space between the rows. I have tried adding &nbsp and it doesn't seem to do the trick.
Can anyone give me a solution to this? Below is a picture of the modal, my JS function and the markup for the modal.
modal:
JS function:
$("button[name='paramsBtn']").click(function () {
/* Grabs ID from col selected */
var $col = $(this).closest('.row').find('.requestId');
var jobRequestId = $col.data('id');
var nameType = $col.data('name');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId, "name" : nameType},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var name = [];
var value = [];
var arr = results;
//loop through arr created from dictionary to grab key(s) and value(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
//name += key;
//value += results[key];
name.push(key);
value.push(results[key])
//Remove previous rows
$("div[name='params']").remove();
for (var i in name) {
//Adding parameters as rows
$('<div class="col-md-6 text-break" name="params"> ' + name[i] + '</div>'+ '<div class="col-md-6 text-break" name="params">' + value[i] + '</div>').insertAfter($('#modalGridHeader'));
}
}
}
}
});
});
markup for modal:
<div class="modal fade" id="paramsModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header modal-header-primary" style="margin-bottom:-16px;">
<a class="btn btn-xs btn-primary pull-right" data-dismiss="modal" aria-label="Close"><span class="glyphicon glyphicon-remove"></span></a>
<h4 class="modal-title" id="modalTitleText">Job Parameters</h4>
</div>
<div class="modal-body" style="height:250px;">
<div class="list-group">
<div class="row list-group-item list-group-item-heading container divTableHeading" style="width:inherit; margin-bottom:0px;" id="modalGridHeader">
<div class="col-md-6 font-weight-bold"> Parameter(s): </div>
<div class="col-md-6 font-weight-bold"> Value(s): </div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The line that is adding the rows is:
$('<div class="col-md-6 text-break" name="params"> ' + name[i] + '</div>'+ '<div class="col-md-6 text-break" name="params">' + value[i] + '</div>').insertAfter($('#modalGridHeader'));
Here is where I have tried adding &nbsp. I have also tried adding margin-bottom:5px, but it looked very odd.
Thanks
Quick and dirty
In <div class="col-md-6 text-break" name="params"> add style="height:20px;".

jQuery don't see my id

This is my html(modal)
<div id="myModal" 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>
<h4 class="modal-title"></h4>
</div>
<div id="modal-text" class="modal-body">
<p id="modalMessage"> </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
and here is my jQuery
$('a[href="#myModal"]').click(function () {
if ($("#TermsConditions")) {
$("#modal-title").html(`<h4>` + "Terms Conditions" + `</h4>`);
$("#modalMessage").html(`<p>` + "message" + `</p>`);
}
else if ($("#Cookies")) {
$("#modal-title").html(`<h4>` + "Cookies" + `</h4>`);
$("#modalMessage").html(`<p>` + "message2" + `</p>`);
}
else {
$("#modal-title").html(`<h4>` + "Privacy Policy" + `</h4>`);
$("#modalMessage").html(`<p>` + "message3" + `</p>`);
}
})
modal should be opened when i am clicking on link
and when i click,modal should show some header and text from chosen link(id)
it will just looks like that(picture)
it just wrotes "message"...
and this is a code of my links
<ul class="list-unstyled list-inline gray">
<li class="footerDistance" style="display:inline;"><a data-target="#myModal" data-toggle="modal" href="#myModal" id="TermsConditions">Terms&Conditions</a></li>
<li class="footerDistance" style="display:inline;"><a data-target="#myModal" data-toggle="modal" href="#myModal" id="Cookies">Політика Cookies</a></li>
<li class="footerDistance" style="display:inline;"><a data-target="#myModal" data-toggle="modal" href="#myModal" id="PrivacyPolicy">Політика Конфіденційності</a></li>
</ul>
Help please!
Do it simpler.
$("#TermsConditions").click(function(){...});
$("#Cookies").click(function(){...});
...
You are trying to fetch an element by id of "modal-tile" but in your html there is not element with id "modal-title"
$("#modal-title").html(`<h4>` + "Privacy Policy" + `</h4>`);
<h4 class="modal-title"></h4>
I think you need to change code to
<h4 class="modal-title" id="modal-title"></h4>
Also, you can change click method like this:
$('a[href="#myModal"]').click(function () {
var clickedAnchorId = $(this).attr('id');
if (clickedAnchorId === "TermsConditions") {
$("#modal-title").html(`<h4>` + "Terms Conditions" + `</h4>`);
$("#modalMessage").html(`<p>` + "message" + `</p>`);
}
else if (clickedAnchorId === "Cookies") {
$("#modal-title").html(`<h4>` + "Cookies" + `</h4>`);
$("#modalMessage").html(`<p>` + "message2" + `</p>`);
}
else {
$("#modal-title").html(`<h4>` + "Privacy Policy" + `</h4>`);
$("#modalMessage").html(`<p>` + "message3" + `</p>`);
}
})

Bootstrap Modal and Badges

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>

Categories