How to get each array value outside loop to modal? - html

I have this in JS and the code below. I want to send the data-id into modal and also when closing the modal to dismiss the data-id. how can I do that using javaScript???
fetch("https://data.uk/api/" + $searchValue).then(
res => {
res.json().then(
data => {
if (data.length > 0) {
var temp = "";
temp += "<thead>";
temp += "<tr>";
temp += "<th>ID</th>";
temp += "<th>Force Name</th>";
temp += "<th>Details</th>";
temp += "</tr>";
temp += "</thead>";
temp += "<tbody>";
data.forEach((itemData) => {
temp += "<tr><td>" + itemData.id + "</td>";
temp += "<td>" + itemData.name + "</td>";
temp += "<td><a href='#' data-id='" + itemData.id + "' data-toggle='modal' data-target='#myModal'>More Detail</a></td></tr>";
});
temp += "</tbody>";
document.getElementById('data').innerHTML = temp;
}
}
)
}
)
and I want to get each data-id value into modal using this
$("myModal").on("show.bs.modal", function(e) {
var b = $(e.relatedTarget);
var r = b.data("id");
var modal = $(this);
modal.find("#me").text(r);
})
and this is my modal, I want when I open the modal to be able to capture the data-id and display it in id="me"
<div class="modal-body" id="modal-body">
<div class="row m-0">
<div class="col-4">
People name & twitter
</div>
<div class="col-8">
Descriptions
<h2 id="me"></h2>
</div>
</div>
</div>

You can access data-... attribute with dataset property, e.g. given
<div id="my-element" data-id="myData"></div>
you can get it with
document.getElementById("my-element").dataset.id

Related

How to edit array value using jquery?

I am trying to edit array values using jquery. here is what I did.
From a modal, everytime I click the "Add item" button it will push values to an array and just append the data to a table
var iteminfo = {
"row": 'row' + cnt,
"make": make,
"body": body,
"cabin": cabin,
"horsepower": horsepower,
"wheels": wheels,
"chassis": chassis,
"engine": engine,
"remarks": remarks,
"shipmenttag": shipmenttag
};
trucksarray.push(iteminfo);
//append to table:
$("#truckstable > tbody").prepend(<tr><td>.....</td></tr>);
and my html table looks like this:
now I am able to delete a table row and the corresponding data from the array with this code:
//removing the table row
$("#truckstable").on('click', '.remrow', function () {
var id = $(".remrow").attr("id");
$(this).parent().parent().remove();
removeitem(id)
});
//removing array item
function removeitem(row) {
const itemToRemoveIndex = trucksarray.findIndex(function (item) {
return item.row === row;
});
if (itemToRemoveIndex !== -1) {
trucksarray.splice(itemToRemoveIndex, 1);
}
toastr.warning('Item removed!');
}
Now, my problem is, If I click the edit button a modal should popup and be able to edit the selected item value , the table data and the array values as well? Any idea?
You can give data-* to your edit button i.e : data-id="row1"..etc then on click of this button get the data-id value and use filter to filter the JSON Array already created and get only data where row == data-id.
Now , once you got the array values put this values inside the input-box of modal using .val("yourfromarray"). Then, onclick of save button get the value from input box and loop through your JSON Array and update value of array with new values.Lastly add these updated value inside trs.
Demo Code :
var cnt = 0;
var trucksarray = [];
$('#BtnAddTruck').on('click', function() {
var make = $('#tmake').val();
var body = $('#tbody').val();
var cabin = $('#tcabin').val();
var horsepower = $('#thorsepower').val();
var wheels = $('#twheels').val();
var chassis = $('#tchassis').val();
var engine = $('#tengine').val();
var remarks = $('#tremarks').val();
var shipmenttag = 'Truck';
cnt = cnt + 1;
var iteminfo = {
"row": 'row' + cnt,
"make": make,
"body": body,
"cabin": cabin,
"horsepower": horsepower,
"wheels": wheels,
"chassis": chassis,
"engine": engine,
"remarks": remarks,
"shipmenttag": shipmenttag
};
trucksarray.push(iteminfo);
//added here `id` to tr and `data-id` to edit button
$("#truckstable > tbody").
prepend("<tr id='trow" + cnt + "'>" +
"<td>" + make + " " + body + " " + cabin + " " + horsepower + " " + wheels +
"</td>" +
"<td>" + chassis + "</td>" +
"<td>" + engine + "</td>" +
"<td>" + remarks + "</td>" +
"<td>" +
" <button class='btn-primary edit' data-toggle='modal' data-target='#myModal' data-id='row" + cnt + "'>Edit</button>" +
" <button class='remrow btn-danger' id='row" + cnt +
"'>delete</button>" +
"</td>" +
"</tr>"
);
//clearmodalinput();
$(".empty_k input").val("");
//toastr.info('Item added!');
console.log(trucksarray)
});
var id;//delcare this globally
//on click of edit
$(document).on('click', '.edit', function() {
id = $(this).data('id');//get id
console.log(id)
//filter json array and get value only where match
var trucks = $(trucksarray)
.filter(function(i, n) {
return n.row === id;
});
//put value inside input in modal
$('.make').val(trucks[0].make);
$('.body').val(trucks[0].body);
$('.cabin').val(trucks[0].cabin);
$('.horsepower').val(trucks[0].horsepower);
$('.wheels').val(trucks[0].wheels);
$('.chassis').val(trucks[0].chassis);
$('.engine').val(trucks[0].engine);
$('.remarks').val(trucks[0].remarks);
});
//click on save button
$(".save").click(function() {
//loop through array
$(trucksarray).each(function() {
if (this.row == id) {
//creplace value inside array
this.horsepower = $('.horsepower').val();
this.make = $('.make').val();
this.remarks = $('.remarks').val();
this.engine = $('.engine').val();
this.chassis = $('.chassis').val();
this.cabin = $('.cabin').val();
this.body = $('.body').val();
this.wheels = $('.wheels').val();
return false;//got it stop loop
}
});
replace_values(); //replace table datas
})
function replace_values() {
//get values
var make = $('.make').val();
var body = $('.body').val();
var cabin = $('.cabin').val();
var horsepower = $('.horsepower').val();
var wheels = $('.wheels').val();
var chassis = $('.chassis').val();
var engine = $('.engine').val();
var remarks = $('.remarks').val();
//replace trs values
$("#t" + id).html("<td>" + make + " " + body + " " + cabin + " " + horsepower + " " + wheels +
"</td>" +
"<td>" + chassis + "</td>" +
"<td>" + engine + "</td>" +
"<td>" + remarks + "</td>" +
"<td>" +
" <button class='btn-primary edit' data-toggle='modal' data-target='#myModal' data-id='" + id + "'>Edit</button>" +
" <button class='remrow btn-danger' id='" + id +
"'>delete</button>" +
"</td>")
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="empty_k">
<input type="text" id="tmake">
<input type="text" id="tbody">
<input type="text" id="tcabin">
<input type="text" id="thorsepower">
<input type="text" id="twheels">
<input type="text" id="tchassis">
<input type="text" id="tengine">
<input type="text" id="tremarks">
<button id="BtnAddTruck">Add</button>
</div>
<div class="table-responsive">
<table class="table table-bordered" id="truckstable">
<thead>
<tr>
<th scope="col">Description</th>
<th scope="col">Chassis</th>
<th scope="col">Engine</th>
<th scope="col">Remarks</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<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>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Edit..</p>
tmake : <input type="text" class="make"><br/> tbody : <input type="text" class="body"> <br/>tcabin : <input type="text" class="cabin"> <br/>thorsepower :<input type="text" class="horsepower"> <br/>twheels : <input type="text" class="wheels"><br/> tchassis :
<input type="text" class="chassis">
<br/> tengine :<input type="text" class="engine"><br/> tremarks : <input type="text" class="remarks">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default save" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Combine Slick Slider with Bootstrap 4

I have this next issue in which I am having quite a significant problem.
First of all, I am trying to integrate three div into my slider and all of them retain a Bootstrap 4 skeleton.
The code would be like this and furthermore it is being generated from another Jquery function in which I am inserting info from a Database. Therefore, I am putting this info into one of each card.
//FUNCIONES
//Crear especialista
function CrearEspecialistaCard(especialista, mostrarNombreEspecialidad) {
let cardHTML = "";
cardHTML += '<div><div class="col-xs-12 col-lg-3 col-md-3 float-left has_border_grey border_10 px-0 overflow-hidden mr-2 profile-box">'
+ '<div class="card d-inline"><div class="col-lg-6 col-md-6 bg-light float-left py-2 text-md-left text-center" style="z-index:101;"> ';
cardHTML += '<h2 class="text-secondary profile-name">' + ((especialista.sexo == "F") ? "Dra. " : "Dr. ")
+ especialista.nommed + " " + especialista.apemed + '</h2>' +
'<button class="btn btn-secondary btn-profile btn-sm my-2" data-toggle="modal" data-target="#modalDoctor' + especialista.idEspecialista + '"'
+ '>Ver perfil' + '</button>';
cardHTML += '<h3 class="spec-title">' + especialista.descesp + '</h3>' + '<h4 class="center-title">' +
'' + '</h4>'+ '<h5 class="prov-title mb-1">' + especialista.provincias + '</h5>';
cardHTML += '<p id="reservarCita" class=""> RESERVAR CITA</p>' +
(especialista.teleConsulta === true) ?
'<a class="d-inline-block mr-1" href="/videoConsulta"><img class="bg-purple py-1 px-1" src="/Content/Img/videoconsulta30.png" style="max-width:30px;" />' +
'</a>' : '';
cardHTML += (especialista.videoConsulta === true) ?
'<a class="d-inline-block mr-1" href="/teleConsulta"><img class="bg-purple-red py-1 px-1" src="/Content/Img/teleconsulta-30.png" style="max-width:30px;" />' +
'</a>' : '';
cardHTML += (especialista.consulta === true) ? '<a class="d-inline-block mr-1" href="/pedirCita">' +
'<img class="bg-light-purple py-1 px-1" src="/Content/Img/presencial30.png" style="max-width:30px;" />' +
'</a>' : '';
cardHTML += '</div>';
cardHTML += ' <div class="col-md-6 float-left" style="z-index:100;">' +
'<img class="profile-img img-fluid" src="/Content/Img/Medicos/CuadroAsistencial/FORMATO-MEDICOS.jpg" alt="Doctor" />' +
'</div>';
if (mostrarNombreEspecialidad != undefined && mostrarNombreEspecialidad == true) {
cardHTML += '<br /><span style="font-size:small;" class="colorcard bold">' + especialista.descesp + '</span>';
} else {
cardHTML += '<br />';
}
cardHTML += '</div></div></div>';
return cardHTML;
}
I am going to show you where I create the row which inserts one of every card with an anonymous function.
const MuestraEspecialistasFavoritos = (qRow) => {
let resultadoHTML = "";
let modalHTML = "";
resultadoHTML += '<div class="preview-carousel">'; // this is where I generate the class for my carousel
for (var a = 0; a < globalModeloFavoritos.length; a++) {
let toto = ca_model.listaEspecialistas.filter(b => b.idEspecialista == globalModeloFavoritos[a]);
if ( toto ) resultadoHTML += CrearEspecialistaCard(toto[0] , false);
if( toto )
var doctor = toto[0];
modalHTML += loadModal(doctor, toto[0].idEspecialista);
}
modalesRecientes.html(modalHTML);
resultadoHTML += '</div>';
qRow.html(resultadoHTML);
}
When I already have constructed my cards, which in this case they are functioning and being displayed as I want to, I am calling the slick slider so that I can interpret one of every card as one unique slider.
$('.preview-carousel').slick({
slidesToShow: 2,
slidesToScroll: 1
});
My slick.js is loaded as I already checked but it doesn't do absolutely nothing.
FYI every one of the cards generates a div firstly with no classes and no ids so I can be able to interpret every one of the items as if they were items of the slider.
Ok, found it already.
It wasn't that hard actually.
I was trying to run the slick function inside a document ready function.
With an on load functions, it works perfectly.
$(window).on('load', function() {
$('.preview-carousel').slick({
slidesToShow: 2,
slidesToScroll: 1
});
});

Bind an even to dynamically appended html in ionic 3

I am developing an app with the help of ionic 3
in the application i am generating dynamic html from .ts file and appending in HTML . Now i want to bind and click event to html
After user done an click event i want to refresh the content present in the dynamically generated html
please help to solve this
enter code here
my .ts file
with the below code i am generating html and appending to html
outputHtml = '<div id="rpl_crt"><div class="sys_ot"><h6 class="itm_nme">My Cart</h6>';
var innerHTML = '';
let amount = 0;
let savings = 0;
for (let dt in data) {
amount += data[cart].vv.value;
savings += data[cart].aa.value;
innerHTML += '<div class="cartlist">'
innerHTML += '<div class="row ">'
innerHTML += '<div col-3 class="itemimg">'
let img_url=data[cart].product.images ? ConfigurationPage.commonURL+data[dt].aa.images[1].url:'assets/img/place_holder.png'
innerHTML += '<img src="'+img_url+'" >'
innerHTML += '</div>'
innerHTML += '<div col-9>'
innerHTML += '<h6>' + data[dt].aa.name + '</h6>'
innerHTML += '</div>'
innerHTML += '</div>'
innerHTML +='<div class="btn_qnty row">'
innerHTML += '<div col-5>'
innerHTML += '<div class="row">'
innerHTML += '<div col-3 click="abc(dt)"><span class="circle">-</span></div>'
innerHTML += '<div text-center col-6 >'+data[dt].q+'</div>'
innerHTML += '<div col-3 (click)="xyz(dt)"><span class="circle " >+</span></div>'///I want an click event here to do some action
//
innerHTML += '</div>'
innerHTML += '</div>'
innerHTML += '<div col-7>'
innerHTML += '<div class="prd_dtl">'
innerHTML += '<div class="proctprice">'
if (data[dt].ss.value != 0) {
innerHTML += '<span class="orgin_prc">' + this.currency.transform((parseFloat(data[dt].tp.value) + parseFloat(data[dt].ss.value)), 'INR') + '</span>'
}
innerHTML += '<span class="dsc_prc">' + this.currency.transform(data[dt].tp.value, 'INR') + '</span>'
innerHTML += '</div>'
if (data[cart].savings.value != 0) {
innerHTML += '<p class="save_prc">' + this.currency.transform(data[dt].ss.value, 'INR') + '</p>'
}
innerHTML += '</div>'
innerHTML += '</div>'
// innerHTML += '<div class="quantity">' + data[dt].qt+ '</div>'
innerHTML += '</div>'
innerHTML += '</div>'
let abc={
code:data[dt].aa.code,
data:data[dt]
}
clickEventMethod.push(abc);
}
this.totalAmount = amount;
this.totalSaving = savings;
// outputHtml += '</ion-list>';
let footerHtml = '<div class="row cartfooter">'
footerHtml += '<div col-4><p>Total amount</p>' + this.currency.transform(this.totalAmount, 'INR') + '</div>'
footerHtml += '<div col-4><p>Total amount</p>' + this.currency.transform(this.totalSaving, 'INR') + '</div>'
footerHtml += '<div col-4><p>Say <strong>Checkout</strong> to checkout all items</p></div>'
console.log(clickEventMethod,'clickEventMethod')
outputHtml += innerHTML + footerHtml + '</div></div>';
this.appenData.nativeElement.insertAdjacentHTML('beforeend', outputHtml);//Appending the data at the end of the ion-content // break;
HTML
<ion-header [ngClass]="!isFromHome ? 'leftPaddingCssTitle':'cssTitle'">
<ion-navbar color="danger">
<ion-title>{{headerName}}</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div class="hint">
<p>To go back , say <b>Go Back</b></p>
<p>To Go cart , Say <b>Open Cart </b> or <b>Go to Cart</b></p>
</div>
<div class="main" #appenData id="main">
</div>
<ion-content>

How to add click event to dynamically added html element in typescript [duplicate]

This question already has answers here:
Angular2 - catch/subscribe to (click) event in dynamically added HTML
(2 answers)
Closed 8 months ago.
I'm building an app in angular 2. I want to add a click event to a dynamically added html element.
I define a string (contentString), and in this string I define the html element.
var contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + '<br/> Click here for more information <button (click)="navigate()">Navigate here</button>';
This string is put inside a html element like this:
var boxText = document.createElement("div");
boxText.innerHTML = contentString;
Although when I inspect the element, it has the click event defined, but it does not trigger.
on click it should console log
navigate() {
console.log("eeeehnnananaa");
}
But that does not work.
Anyone a solution?
Angular processes the template when the component is compiled. HTML added later is not compiled anymore and bindings are ignored.
You can use
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
// assume dynamic HTML was added before
this.elRef.nativeElement.querySelector('button').addEventListener('click', this.onClick.bind(this));
}
In my case I do these--
var boxText = document.createElement("div");
const contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category +
'<br/> Click here for more information ';//as per your code
boxText.innerHTML = contentString;
const button = document.createElement('button');
button.addEventListener('click', (e) => {
this.navigate();//your typescript function
});
button.innerText = 'Navigate here';
boxText.appendChild(button);
Call click event dynamically
ConfirmThisOrder(obj) {
var orderItemID = obj.target.dataset.oid;
}
ItemDetails(orderId, itemIndex) {
if ($("#accordionNew" + itemIndex).closest("div").html().indexOf("div_" + orderId) == -1) {
this.oRequest = new ORequestParameter();
var retrievedObject = localStorage.getItem('userObject');
let userObject = JSON.parse(retrievedObject) as AdminDashboardModel;
this.oRequest.SellerId = userObject.sellerId;
this.oRequest.OrderStatus = $("#hdnOrderStatus").val().toString();
this.oRequest.OrderId = orderId;
this.oRequest.OrderConfirmationFlag = '0,1,2';
let sProviderId = "0";
if (this.MultiSelectObjTypeSelected != undefined) {
let result2 = this.MultiSelectObjTypeSelected.map(a => a.id);
if (result2.join().length > 0) {
sProviderId = result2.join();
}
}
this.oRequest.ProviderID = sProviderId;
this.orderService.GetItemDetails(this.oRequest).subscribe(
lstOrderItem => {
this.lstOrderItem = lstOrderItem;
var sData = "";
if (this.lstOrderItem.length > 0) {
sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-left' style='font-weight: bold;' id='div_" + orderId + "'>Product Name</div>";
sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-center' style='font-weight: bold;'>Price</div>";
sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-center' style='font-weight: bold;'></div>";
sData += "<div class='clearfix'></div>";
var aTag = document.createElement('a');
for (var i = 0; i < this.lstOrderItem.length; i++) {
sData += "<div style='background-color:#fff;padding:10px 0;'>";
sData += "<div class='col-4 col-sm-4 col-lg-4 col-xs-4 col-md-4'>";
sData += "<span style='text-align: justify;'>" + this.lstOrderItem[i].productName + "</span>"; /*<b style='color:red;' > (" + this.lstOrderItem[i].productType + ") < /b>*/
sData += "</div>";
sData += "<div class='col-4 col-sm-4 col-lg-4 col-xs-4 col-md-4 text-center'>";
sData += "<span><i class='fa fa-inr'></i> " + this.lstOrderItem[i].providerSellingPrice + "</span>";
sData += "</div>";
sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-2 text-center' style='font-weight: bold;'>";
sData += '<a id="btn_' + this.lstOrderItem[i].orderItemID + '" data-oid=' + this.lstOrderItem[i].orderItemID + ' class="mylink btn btn-success" style="width:70px;">Pending</a>';
sData += "</div>";
sData += "</div>";
sData += "<div class='clearfix'></div>";
}
sData += "<div style='background-color:#BFE7FF;padding:15px 0;'>";
sData += "<div class='col-6 col-sm-6 col-lg-6 col-xs-6 col-md-6' style='font-weight: bold'>Total Billed Amount</div>";
sData += "<div class='col-2 col-sm-2 col-lg-2 col-xs-2 col-md-2 pull-right text-right'>";
sData += "<span><b>Price:</b> <i class='fa fa-inr'></i> " + totalAmount + "</span></div>";
sData += "<div class='clearfix'></div>";
sData += "</div>";
}
else {
$("#errorMsg").removeClass("hidden");
$("#errorMsg").addClass("alert-danger");
$("#errorMsg").html("There was no record found");
}
$("#accordionNew" + itemIndex).closest("div").html(sData);
let children = document.getElementsByClassName("mylink");
for (let i = 0; i < children.length; i++) {
children[i].addEventListener("click", (event: Event) => {
this.ConfirmThisOrder(event);
});
}
},
error => this.errorMessage = <any>error
);
}
return false;
}

Autodividers in listview in JQM using filter

I am using autodividers in listview in JQM and populating new "pages" which works fine when all the list is displayed but when user filters the list, the corresponding page does not display. I'm sure I'm missing something obvious so would appreciate any help.
js
$(document).ready (function() {
$.getJSON("eur_countries_array.json", function (data) {
var countries = [];
for (var obj in data){
countries.push({
title: data[obj].title,
flag: data[obj].flag,
population: data[obj].population,
avg_annual_growth: data[obj].avg_annual_growth,
date: data[obj].date
});
}
// call sort function
countries.sort(compare);
// read through array
var listHTML = "";
for (var i=0; i < countries.length; i++) {
// for each country add flag and title to list
listHTML += '<li><img class="ui-li-icon ui-corner-none alt="'+ countries[i].flag + 's flag" src="flags/16/' + countries[i].flag +'.png" >' + countries[i].title + '</li>';
// Append new "pages" after "home" page for each country
var pHTML = '<div data-role="page" id="' + countries[i].flag + '">';
pHTML += '<div data-role="header"><h1>' + countries[i].title + '</h1><a data-rel="back">Back</a></div>';
pHTML += '<div role="main" class="ui-content" class="country_details">';
pHTML += '<div class="center"><img class="flag_display" alt="'+ countries[i].flag + 's flag" src="flags/64/' + countries[i].flag +'.png" ></div></div>';
pHTML += '<div><p class="center">Population of ' + countries[i].title + ' is ' + countries[i].population + '</p></div>';
pHTML += '<div><p class="center">Average annual growth: ' + countries[i].avg_annual_growth + '</p></div>';
pHTML += '<div><p class="center">Statistics correct as of: ' + countries[i].date + '</p></div>';
pHTML += '</div>';
console.log(pHTML);
$("body").append(pHTML);
}
// Display countries list
// call the refresh method to update the visual styling after adding new elements
$("#countryList").empty().append(listHTML).listview("refresh");
});
});
html
<div data-role="page" id="home">
<div data-role="header">
<h2>European Countries</h2>
</div>
<div role="main">
<ul id="countryList" data-role="listview" data-autodividers="true" data-filter="true" data-inset="true">
<li></li>
</ul>
</div>
<div data-role="footer">
</div>
</div><!-- page -->