Accessing HTML Element after Adding with innerHtml - javascript

I am adding the data received as a result of a request to my page as follows.
showMovieInfo(movies) {
this.tableDiv.innerHTML = "";
movies.forEach(movie => {
this.tableDiv.innerHTML +=
`
<table class="table align-middle mb-0 bg-white">
<thead class="bg-light">
<tr>
<th>Movie Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="d-flex align-items-center">
<img src="${movie.image}"
alt="" style="width: 120px; height: 120px" class="rounded-circle" />
<div class="ms-3">
<p class="fw-bold mb-1">${movie.title}</p>
<p class="text-muted mb-0">${movie.description}</p>
</div>
</div>
</td>
<td>
<button type="button" id="showonmap" class="btn btn-link btn-sm btn-rounded">
Show on map
</button>
</td>
</tr>
</tbody>
</table>`
});
}
then i want to add addEventListener to buttons with id="showonmap".But I am getting an error and when I click the buttons, any function does not work.

To support the comment made above regarding the delegated event listener I quickly rattled up this simple demo that slightly rewrites your original class method as a standalone function so that you can see the effect in action. As the event handler is assigned to a parent element within the DOM which does exist when the page is loaded you can use the event to identify which button ( or other element ) was clicked and from there do whatever operations are required.
const movies = [{
image: 'http://t1.gstatic.com/images?q=tbn:ANd9GcQsJW_I8KPZiq4mXcpRCd8uKBsUMR4Gz691k6gwEiLqVOoTl8pf',
title: 'The Life of Brian',
description: 'this is a great movie'
},
{
image: 'https://m.media-amazon.com/images/M/MV5BOTI4MDdjMmUtOTZhOS00MTYwLWEyZTUtYTdhMTQxNGM1YTUxXkEyXkFqcGdeQXVyMzg1ODEwNQ##._V1_UX140_CR0,0,140,209_AL_.jpg',
title: 'The Wasp Woman',
description: 'this is a terrible movie'
}
];
// slightly re-written as no longer part of a class/object
showMovieInfo = (movies) => {
// exlicitly define this.tableDiv here rather than in constructor earlier ( & not shown )
this.tableDiv = document.getElementById('movies');
this.tableDiv.innerHTML = "";
movies.forEach(movie => {
this.tableDiv.innerHTML +=
`
<table class="table align-middle mb-0 bg-white">
<thead class="bg-light">
<tr>
<th>Movie Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="d-flex align-items-center">
<img src="${movie.image}"
alt="" style="width: 120px; height: 120px" class="rounded-circle" />
<div class="ms-3">
<p class="fw-bold mb-1">${movie.title}</p>
<p class="text-muted mb-0">${movie.description}</p>
</div>
</div>
</td>
<td><!-- modified id to data-id and added data-title for demo -->
<button type="button" data-id="showonmap" data-title="${movie.title}" class="btn btn-link btn-sm btn-rounded">
Show on map
</button>
</td>
</tr>
</tbody>
</table>`;
});
this.tableDiv.addEventListener('click', function(e) {
if (e.target != e.currentTarget && e.target.tagName == 'BUTTON' && e.target.hasAttribute('data-id')) {
alert(e.target.dataset.title);
// ... here you would do other operations to actually "view on map"
// ... etc
}
})
}
showMovieInfo(movies);
<div id='movies'></div>

Related

Error dynamically adding table rows in reactJs [duplicate]

This question already has answers here:
ES6 array map doesn't return anything: ReactJS
(2 answers)
Closed 4 years ago.
I am trying to create a reactJs page that allows an admin add a user to a platform. Now, instead of submitting the form for each new user, I want the admin to be able to add as many users as possible before submitting the form. By default, one table row containing input fields is displayed and then on click of the add button, a new row is added and the admin can fill the necessary details. However, I can't get my page to show the default row and the add button does not work either and unfortunately, my page throws no error. Here is my code:
export default class Admins extends React.Component{
constructor(props){
super(props);
this.state = {
errors : '',
success : '',
rows : [1]
}
this.addRow = this.addRow.bind(this);
this.fetchRows = this.fetchRows.bind(this);
}
addRow(){
var last = this.state.rows[this.state.rows.length-1];
var current = last + 1;
this.setState({
rows : this.state.rows.concat(current)
});
}
fetchRows(){
this.state.rows.map((row, index) => (
//console.log(row, index)
<tr key={row}>
<td className="text-center">
<button type="button" data-toggle="tooltip" className="btn btn-xs btn-danger"
data-original-title=""><i className="fa fa-trash"></i>
</button>
</td>
<td>
<input type="text" className="form-control"/>
</td>
<td>
<input type="text" className="form-control"/>
</td>
<td>
<input type="text" className="form-control"/>
</td>
</tr>
));
}
render(){
return(
<div>
<Top/>
<SideBar/>
<div className="breadcrumb-holder">
<div className="container-fluid">
<ul className="breadcrumb">
<li className="breadcrumb-item"><Link to="/">Dashboard</Link></li>
<li className="breadcrumb-item active">Admins</li>
</ul>
</div>
</div>
<section className="forms">
<div className="container-fluid">
<header>
<h3 className="h5 display">Admins</h3>
</header>
<div className="row">
<div className="col-lg-6">
<h5 className="text-danger">{this.state.errors}</h5>
<h5 className="text-success">{this.state.success}</h5>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<div className="card">
<div className="card-header d-flex align-items-center">
<h5></h5>
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th width="5%">Actions</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{this.fetchRows()}
<tr>
<td className="text-center">
<button type="button" onClick={this.addRow} data-toggle="tooltip" className="btn btn-xs btn-primary"
data-original-title=""><i className="fa fa-plus"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
}
You are not returning anything from fetchRows. Return it or simply put it directly in the render method and it will work as expected.
Example
class Admins extends React.Component {
state = {
errors: "",
success: "",
rows: [1]
};
addRow = () => {
var last = this.state.rows[this.state.rows.length - 1];
var current = last + 1;
this.setState({
rows: this.state.rows.concat(current)
});
};
render() {
return (
<div>
<div className="breadcrumb-holder">
<div className="container-fluid">
<ul className="breadcrumb">
<li className="breadcrumb-item active">Admins</li>
</ul>
</div>
</div>
<section className="forms">
<div className="container-fluid">
<header>
<h3 className="h5 display">Admins</h3>
</header>
<div className="row">
<div className="col-lg-6">
<h5 className="text-danger">{this.state.errors}</h5>
<h5 className="text-success">{this.state.success}</h5>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<div className="card">
<div className="card-header d-flex align-items-center">
<h5 />
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th width="5%">Actions</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{this.state.rows.map((row, index) => (
//console.log(row, index)
<tr key={row}>
<td className="text-center">
<button
type="button"
data-toggle="tooltip"
className="btn btn-xs btn-danger"
data-original-title=""
>
<i className="fa fa-trash" />
</button>
</td>
<td>
<input type="text" className="form-control" />
</td>
<td>
<input type="text" className="form-control" />
</td>
<td>
<input type="text" className="form-control" />
</td>
</tr>
))}
<tr>
<td className="text-center">
<button
type="button"
onClick={this.addRow}
data-toggle="tooltip"
className="btn btn-xs btn-primary"
data-original-title=""
>
<i className="fa fa-plus" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
}

Clickable link inside UI Sortable field

I am making a custom field for the Advanced Custom Fields plugin for wordpress.
Now I have been able to allow javascript to be used inside of the field but the field has UI-sortable active which makes my anchor tag not firering but instead clicks the sortable anchor.
Is there a way to make sure that my click event gets fired inside a sortable element?
So I created this link, to be placed inside a element :
<a id="addTable" href="#">Voeg tabel toe</a>
Which gets turned into an element like this :
<div id="normal-sortables" class="meta-box-sortables ui-sortable">
<div id="acf-group_5a93d53605864" class="postbox acf-postbox seamless">
<button type="button" class="handlediv" aria-expanded="true">
<span class="screen-reader-text">paneel Bridge verbergen</span>
<span class="toggle-indicator" aria-hidden="true"></span>
</button>
<h2 class="hndle ui-sortable-handle">
<span>Bridge</span>
<a href="{link}/wp-admin/post.php?post=12695&action=edit"
class="dashicons dashicons-admin-generic acf-hndle-cog acf-js-tooltip"
title="Bewerk groep">
</a>
</h2>
<div class="inside acf-fields -top">
<div class="acf-field acf-field-Bridge acf-field-5a93d538671c7"
data-name="bridge"
data-type="Bridge" data-key="field_5a93d538671c7">
<div class="acf-label">
<label for="acf-field_5a93d538671c7">Bridge</label>
</div>
<div class="acf-input">
<!-- Here is the anchor tag -->
<a id="addTable" href="#">Voeg tabel toe</a>
<div id="ContentWrapper">
<div id="North"></div>
<div id="East"></div>
<div id="Middle">
<table bgcolor="#c0c0c0">
<tbody>
<tr>
<td colspan="3" align="center"><strong>N</strong></td>
</tr>
<tr>
<td align="left"><strong>W</strong></td>
<td> </td>
<td align="right"><strong>O</strong></td>
</tr>
<tr>
<td colspan="3" align="center"><strong>Z</strong></td>
</tr>
</tbody>
</table>
</div>
<div id="South"></div>
<div id="West"></div>
</div>
</div>
</div>
<script type="text/javascript">
if ( typeof acf !== 'undefined' ) {
acf.postbox.render({
"id": "acf-group_5a93d53605864",
"key": "group_5a93d53605864",
"style": "seamless",
"label": "top",
"edit_url": "http:\/\/{link}\/wp-admin\/post.php?post=12695&action=edit",
"edit_title": "Bewerk groep",
"visibility": true
});
}
</script>
</div>
</div>
</div>
(function($) {
$("#addTable").click(function () {
alert( "Click" );
});
})(jQuery);

Hide div on click with Javascript (a click that already show other div)

I've built a feedback function to be used on the bottom of pages on our company website. The visitor can vote YES or NO on the question, "Was this information useful to you?" The click show a div (feedbackDiv1/feedbackDiv2) via Javascript.
The function works, but I want the question and the answer buttons to disappear after the visitor has voted, I.e. hide the div #pagefeedback.
I've tried all my tools, but I cant get this to work.
Help would be very much appreciated!
This is the JavaScript used:
function showFeedback1() {
document.getElementById('feedbackDiv1').style.display = "block";
function showFeedback2() {
document.getElementById('feedbackDiv2').style.display = "block";}
This is the HTML used:
<div class="greycontentbox">
<div id="pagefeedback">
<h4 style="text-align: center;">Was this information useful to you?</h4>
<table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
<tbody>
<tr>
<td align="center"><a class="knappfeedbackyes knappsmall" href="#" onclick="showFeedback1()"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES</a></td>
<td align="center"><a class="knappfeedbackno knappsmall" href="#" onclick="showFeedback2()"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO</a></td>
</tr>
</tbody>
</table></div>
<div align="center"><div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">POSITIVE FEEDBACK</div></div>
<div align="center"><div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">NEGATIVE FEEDBACK</div></div>
</div>
Kind regards,
Pete
Based on Robert's answer, you could do a simple function which receive the ID of the element that has to be shown.
function showFeedback(feedback) {
document.getElementById(feedback).style.display = "block";
document.getElementById('options').style.display = "none";
}
<div class="greycontentbox">
<div id="pagefeedback">
<h4 style="text-align: center;">Was this information useful to you?</h4>
<table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
<tbody id="options">
<tr>
<td align="center"><a class="knappfeedbackyes knappsmall" href="#" onclick="showFeedback('feedbackDiv1')"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES</a></td>
<td align="center"><a class="knappfeedbackno knappsmall" href="#" onclick="showFeedback('feedbackDiv2')"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO</a></td>
</tr>
</tbody>
</table></div>
<div align="center">
<div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">POSITIVE FEEDBACK</div></div>
<div align="center"><div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">NEGATIVE FEEDBACK</div>
</div>
</div>
If you give your table an ID it's fairly easy to just change it's display css to none. Also you can accomplish the same with 1 function and simply pass an argument to it that you can use in a conditional statement to show your appropriate feedback.
function showFeedback(feedback) {
if (feedback == 'yes') {
document.getElementById('feedbackDiv1').style.display = "block";
} else {
document.getElementById('feedbackDiv2').style.display = "block";
}
document.getElementById('options').style.display = "none";
}
<div class="greycontentbox">
<div id="pagefeedback">
<h4 style="text-align: center;">
Was this information useful to you?
</h4>
<table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
<tbody id="options">
<tr>
<td align="center">
<a class="knappfeedbackyes knappsmall" href="#" onclick="showFeedback('yes')">
<i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES
</a>
</td>
<td align="center">
<a class="knappfeedbackno knappsmall" href="#" onclick="showFeedback('no')">
<i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO
</a>
</td>
</tr>
</tbody>
</table>
</div>
<div align="center">
<div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">
POSITIVE FEEDBACK
</div>
</div>
<div align="center">
<div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">
NEGATIVE FEEDBACK
</div>
</div>
</div>

Thymeleaf pass data from html id to thymeleaf variable

I've a problem with below code. I need to pass a variable from html id to thymeleaf variable.
<table class="responsive-table highlight bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr th:each="worker: ${workersList}">
<td th:text="${worker.id}"></td>
<td th:text="${worker.name}"></td>
<td th:text="${worker.surname}"></td>
<td th:text="${worker.email}"></td>
<td>
<a href="#deleteModal" class="btn tooltipped modal-trigger" th:attr="data-id=${worker.id}, data-name=${worker.name +' '+ worker.surname}"
data-position="top" data-delay="50" data-tooltip="Delete"><i class="material-icons">delete</i></a>
</td>
</tr>
<!-- Delete Modal -->
<div id="deleteModal" class="modal modal-fixed-footer">
<div class="modal-content">
<p id="modal-name"></p>
<p id="modal-id"></p>
</div>
<div class="modal-footer">
<a th:href="#{'/delete/'+${modal-id} }" class="modal-action modal-close waves-effect waves-red btn-flat">Yes</a>
</div>
</div>
</tbody>
</table>
<script th:inline="javascript">
$('#deleteModal').modal({
ready: function(modal, trigger) {
var button = $(trigger);
var id = button.data('id');
$('#modal-id').html(id);
}
});
</script>
It won't work. I've to pass it using js because this id's are changeable depends on worker I click. This works, but It can't pass an id to th:href Thanks for help!
They way you have it done, you need to use Javascript to update the ID, as your modal is outside the loop. I would do something like this:
<div class="modal-footer">
<a id="idModalLink" href="#" class="modal-action modal-close waves-effect waves-red btn-flat">Yes</a>
</div>
And in your javascript code:
$('#deleteModal').modal({
ready: function(modal, trigger) {
var button = $(trigger);
var id = button.data('id');
$('#modal-id').html(id);
$('#idModalLink').attr("href", "/delete/" + id);
}
});

modal inside an ng-repeat directive causes crash

i am trying to put inside a table abutton that will open a modal.
but no matter which button i click it seems that it tries to open it many times.
i have put the openModal and closeModal inside the main controller.
i believe the problem might be because i am using it inside an ng-repeat?
but in any case i do not know what is going wrong. what am i doing wrong?
i am using this modal:
http://angular-ui.github.io/bootstrap/#/modal
the html code:
<div class="row">
<div class="span4" ng-repeat="court in courts">
<table class="table table-condensed table-bordered table-hover">
<caption><h4>court {{court.records[0].id}}<h4></caption>
<tr>
<th style='text-align:center'>Hour</th>
<th style='text-align:center'>Player 1</th>
<th style='text-align:center'>Player 2</th>
<th></th>
</tr>
<tr ng-repeat="record in court.records">
<td width="50" >{{record.hour}}</td>
<td ng-style="user1Payed(record)" style='text-align:center'>{{record.u1_first}} {{record.u1_last}}</td>
<td ng-style="user2Payed(record)" style='text-align:center'>{{record.u2_first}} {{record.u2_last}}</td>
<td> <!-- options button -->
<button class="btn" ng-click="openModal()">Open me!</button>
<div modal="shouldBeOpen" close="closeModal()" options="opts">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">{{item}}</li>
</ul>
</div>
<div class="modal-footer">
<button class="btn btn-warning cancel" ng-click="closeModal()">Cancel</button>
</div>
</div>
</td> <!-- options button end -->
</tr>
</table>
</div>
</div>
and the controller code:
function CourtsController($scope, $window, $http, CourtsService, $timeout) {
$scope.openModal = function () {
$scope.shouldBeOpen = true;
};
$scope.closeModal = function () {
$scope.closeMsg = 'I was closed at: ' + new Date();
$scope.shouldBeOpen = false;
};
$scope.items = [
"Guest Payment",
"Member Payment",
"League (no payment)",
"no Payment"
];
$scope.opts = {
backdropFade: true,
dialogFade:true
};
Move you modal div of the ng-repeat and set $scope variable according your openModal().

Categories

Resources