Selector th Jquery [duplicate] - javascript

This question already has answers here:
jQuery - How to select by attribute
(3 answers)
Closed 5 years ago.
I'm trying to understand how to use the Jquery selector
https://learn.jquery.com/using-jquery-core/selecting-elements/
I have a table and I want to create an input within the modal, my difficulty actually is how to use the selector correctly to access the content of <th scope="row">
<table>
<thead>
<tr>
<th>ID</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">123</th>
<th><span class="oi" data-glyph="pencil"></span></th>
</tr>
</tbody>
</table>
When I click on edit the modal opens
Modal
<div class="modal fade" id="formModal" 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">Modal Form</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" style="padding:100px">
<div id="dvInputsUpdate"></div>
<button name='btn-update' type="submit" class="btn btn-primary">Atualizar</button>
</form>
</div>
</div>
</div>
</div>
I tried $('table.row')
Jquery
$(document).on('click', '#formModal', function() {
var inpId = 0;
$('#dvInputsUpdate').html('');
$('table.row', function() {
var chkValue = $(this).closest('th').next('td').text();
$('#dvInputsUpdate').append($('<div class="form-group"><label >ID</label><input type="text" id="' + ("input" + inpId) + '" value="' + chkValue + '" /></div>'));
inpId++;
});
return false;
});
---UPDATE---
Thank you all so much for the answers, but you have not solved it yet. I've learned that Scope is not yet supported by html5.
I inserted a class="update" in th: $('th[class="update"]')
But this is not working yet

table.row will look specifically at the table element and then of those elements, look for a class name of .row. I believe for your case, you want to look for nested .row classes in the table element so you should change it to $('table th'). I'm not sure what attribute scope is but if you want to use .row, you can define a <th class="row"> instead and then use $('table.row')
If you really want to use the attribute scope, you can also specify that in jQuery by doing ${'th[scope="row"]')

You might want to have a look at the jQuery selectors.
Elements with attributes having a specific value can be selected via [attributName="desiredValue"].
In your case: $('th[scope="row"]')

To access <th scope="row">:
var thScopeRow = $('th[scope="row"]');

scope is an attribute of <th>, not class, so the correct syntax would be $('th[scope="row"]'). In the snippet i selected this specific th using this method and changed the color of text just for example:
$('th[scope="row"]').css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>ID</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">123</th>
<th><span class="oi" data-glyph="pencil"></span></th>
</tr>
</tbody>
</table>
UPDATE
"I inserted a class="update" in th: $('th[class="update"]')"
If you are using <th class="row">123</th> and it's only one element on the page with such class, you can get it via $('.row')[0]. ([0] is needed because $('.row') will find ALL elements on the page with such class. So think about it as an array). If you have for example 2 elements on the page with such class and want to get the second, so use $('.row')[1] and so on.

Related

Show only one element of a panel using Angularjs

I am new to Angularjs and I am trying to figure out how it's different modules work. So, I am working on a project on which I wanna achieve an accordion-like style for a page, in which a table is shown when I click a panel button. The HTML code that creates(dynamically from a database) the div elements I modify is posted below.The problem is that in this panel, any number of tables can be shown,while I need to only have one opened at a time,so when one opens,the one opened before it should close.Any ideas how I can achieve this functionality?(I assume the error is because the showDB variable is local to each table scope, but I don't know how to work around it.) Thanks!' `
<div ng-repeat="(key, value) in data.services">
<div ng-show="showSection(key)" class="top_panel-section">
<button class="btn top_btn btn-header" type="button" name="showDB"
ng-click="showDB=!showDB">{{key}}</button>
<table ng-show="showDB"
class="n-table toptable table-responsive n-table-standard n-table-striped n-table-hover">
<thead class="n-table-thead">
<tr>
<th width="70%">VM Name</th>
<th width="30%">Status</th>
</tr>
</thead>
<tbody class="n-table-body">
<tr ng-repeat="vm in value.vms">
<td width="76%">{{vm.vm}}</td>
<td width="24%" ng-style="getStatusStyle(vm.status)">
{{vm.status}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Yes, you should remove that local showDB variable to achieve what you need.
You can easily replace it with a $scope.activeKey and evaluating it by the
<button ... name="showDB" ng-click="activateKey(key)">{{key}}</button>
And in your controller:
$scope.activeKey = null;
$scope.activateKey = function (keyToBeActivated) {
$scope.activeKey = keyToBeActivated;
}
Now you can reach that exclusivity by checking:
<table ng-show="activeKey === key" ... >
Using table $index as unique field: (available from ng-repeat)
<button ... name="showDB" ng-click="activateKey($index)">{{key}}</button>
And
<table ng-show="activeKey === $index" ... >

JS Script doesn't change table row background color

So, first of all, I do have 2 tables. When a row on a main table is clicked a modal window opens with secondary table. The secondary table contains date column. If a date is equal to "1111-11-11 / 11:11:11" that means there's an error and so, the row backgroud color should be switched to red.
Here's the code to open the modal window after clicking a row on the first table:
$(document).on('click', '#main-table tbody tr', function () {
var id = $(this).find("td").eq(0).text();
openPoolModal(id);
});
Nothing complicated. openPoolModal function is where I print date to the console as well as try to change the color.
function openPoolModal(id){
$.ajax({
url: "/" + id,
success: function(data){
$("#PoolModalHolder").html(data);
$("#personalModal").modal();
$("#personalModal").modal('show');
$('#poolTable').DataTable({
some DataTables settings;
});
}
});
$("#poolTable tr").each(function(){
var col_val = $(this).find("td").eq(1).text();
console.log(col_val);
if (col_val == "1111-11-11 / 11:11:11"){
$(this).css( "background-color", "yellow" );
}
});
}
And html code that gets returned from an ajax call:
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title text-center" th:text="'Network: ' + ${poolHashrates[0].networkHashrate.id}">Network Id</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table width="100%" class="table table-hover " id="poolTable">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Pool name</th>
<th class="col-md-2 text-center">Date from</th>
<th class="col-md-2 text-center">Hashrate [KH/s]</th>
</tr>
</thead>
<tbody>
<tr th:each="poolHashrate : ${poolHashrates}">
<td class="text-center" th:text="${poolHashrate.poolDef.name}"> Sample data</td>
<td class="text-center" th:text="${#getDataService.formatDate(poolHashrate.poolDef.dateFrom)}">Maven Street 10, Glasgow</td>
<td class="text-center" th:text="${#getDataService.formatHashrate(poolHashrate.hashrate)}">999-999-999</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
So now, there are actually 2 problems I'm facing. First is, that after clicking the mainTable row for the first time, nothing really happens. When I click second time, the date from the first click gets printed into console. When I click for the third time, the date from second click gets printed and so on.
Second problem is that:
$(this).css( "background-color", "yellow" );
...doesn't seem to work as it doesn't colour the background.
use like below
$(this).css( "background", "yellow" );

angularJS print directive losing 2 way binding

I have a print directive in a SPA that seems to lose its 2 way data binding after the first print function is ran. I am sure it has something to do with the cloning and appending of the element.
The Directive is as follows:
agency.directive("pasPrint", ['AgentModel','Dev',
function(agentModel, dev) {
var printSection = document.getElementById("printSection");
function printElement(elem) {
// clones the element you want to print
var domClone = elem.cloneNode(true);
if (!printSection) {
printSection = document.createElement("div");
printSection.id = "printSection";
document.body.appendChild(printSection);
} else {
printSection.innerHTML = "";
}
printSection.appendChild(domClone);
}
return {
restrict: 'A',
link: function($scope, $element, attrs) {
$scope.printModel = {};
$scope.today = new Date().toJSON().slice(0,10);
$element.on("click", function () {
var elemToPrint = document.getElementById(attrs.printElementId);
if (elemToPrint) {
printElement(elemToPrint);
window.print();
}
});
},
controller: ["$scope","$element", "AgentModel", function($scope, $element, agentModel) {
$scope.agentModel = agentModel;
}]
};
}]);
the model that is used in the entire module here is the agentModel.singleAgent which of course represents a single agent. this directive simply prints a cover sheet for an agents hard copy record. the first time we pull up an agents record the cover sheet prints correctly. when we load another agent the print preview show's the correctly updated agent information. in the agentModel.singleAgent 2 way binding (the same values being used in the printSection that gets printed. However the second print attempt also prints the first agent information and so does any other attempt to print any other agents, they all print the first agents data, even thought the singleAgent model has been updated properly.
the html from the print preview is below:
<div class="modal-header ng-scope">
<button type="button" class="close" aria-label="Close" data-ng- click="cancel()"><span aria-hidden="true"> × </span></button>
<h3 class="modal-title ng-binding"> Edit & Print Cover Sheet </h3>
</div>
<div class="modal-body">
<form class="inline-form">
<div class="form-group">
<label class="form-label" for="PRINT_DESC">File Description: </label>
<input class="input-medium" type="text" id="PRINT_DESC" name="PRINT_DESC" data-ng-model="printModel.PRINT_DESC" />
</div>
</form>
<div id="printPreview">
<table class="table table-cell-nowrap table-responsive">
<thead>
<tr>
<th colspan="2"><strong>Type: <em>{{printModel.PRINT_DESC}}</em></strong></th>
<th colspan="2" style="border: 1px #dadada dotted"><div class="clearfix pull-right"><strong>{{agentModel.singleAgent.AGENT_NUMBER}}</strong></div></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Agent Name: {{ agentModel.singleAgent.AGENT_LNAME }}, {{ agentModel.singleAgent.AGENT_FNAME }} </strong></td>
<td><strong>Agent #: {{ agentModel.singleAgent.AGENT_NUMBER }}</strong></td>
<td><strong>UID: {{ agentModel.singleAgent.AGENT_UID }}</strong></td>
<td></td>
</tr>
<tr><td colspan="4">Printed On: {{ today }} </td></tr>
</tbody>
</table>
</div>
<div id="printSection" class="col-md-12"><!-- place nothing in here except what should be printed. by default the content in the print section IS hidden -->
<table class="table table-cell-nowrap table-responsive printCoverFontSize">
<thead>
<tr>
<th colspan="2"><strong>Type: <em>{{printModel.PRINT_DESC}}</em></strong></th>
<th colspan="2" style="border: 1px #dadada dotted"><div class="clearfix pull-right"><strong>{{agentModel.singleAgent.AGENT_NUMBER}}</strong></div></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Agent Name: {{ agentModel.singleAgent.AGENT_LNAME }}, {{ agentModel.singleAgent.AGENT_FNAME }} </strong></td>
<td><strong>Agent #: {{ agentModel.singleAgent.AGENT_NUMBER }}</strong></td>
<td><strong>UID: {{ agentModel.singleAgent.AGENT_UID }}</strong></td>
<td></td>
</tr>
<tr><td colspan="4">Printed On: {{ today }} </td></tr>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<div class="pull-left">
<button class="btn btn-warning" data-pas-print data-print-element-id="printSection"><i class="fa fa-print fa-lg"></i> Print </button>
</div>
<div class="pull-right">
<button class="btn btn-default" data-ng- click="cancel()">Cancel</button>
</div>
the printModel model simply takes the value from the text box and includes it to be printed, just a descriptive term.
I am at a loss as to why this is not working. I did just piece this together from other scripts I found online to work with our application. I am a bit of an angular Newb and I really appreciate any help I can get so thank you in advance. please if you need more information feel free to ask. If I had to guess I would say it has something to do with cloning and the emptying of the element if I had to guess, but I am at a loss as to how to fix it. HELP please.

Get form contents from array of forms

I currently make a list of "forms" based on an array using twig in my html. It is kind of hard to explain what I am trying to do, but if you look at my code below it should be clear to see. Based on which pay button the user presses, I want to get the corresponding amount.
EDIT:
The problem I am having is that I cannot access the input (.payAmountForm) based on which pay button the user clicked. I tried using the selector in my js file, however I get the error provided at the bottom.
html table
<table>
<thead>
<tr class="rowTable header">
<th class="cell">Date Submitted</th>
<th class="cell">Report Name</th>
<th class="cell">Details</th>
<th class="cell">Message</th>
<th class="cell">Amount</th>
<th class="cell">Pay</th>
</tr>
</thead>
<tbody>
{% for report in submittedReports.result %}
<tr class="rowTable">
<td class="cell">{{report.dateSubmitted}}</td>
<td class="cell">{{report.errorName}}</td>
<td class="cell">
<button type="button" class="displayDetailsModal detailsButton" data-toggle="modal"
data-target="#detailsModal" data-whatever="#getbootstrap"
data-ID={{report.reportID}}>
View
</button>
</td>
<td class="cell">
<button type="button" class="messageButton" data-toggle="modal"
data-target="#messageModal" data-whatever="#getbootstrap"
data-ID={{report.reportID}}>
Edit
</button>
</td>
<td class="cell">
<div class="input-group payInput">
<span class="input-group-addon">$</span>
<input type ="text" class="form-control payAmountForm" maxlength="11" data-id={{report.reportID}}>
</div>
</td>
<td class="cell">
<button data-ID={{report.reportID}} class="btn btn-success payButton" type="button" value="Pay">Pay</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
js file contents
$(document).ready(function () {
$(".payButton").click(function(event) {
payInfo = [];
event.preventDefault();
alert($(this).attr("data-ID"));
payInfo.amount = $(".payAmountForm [data-ID]=" + $(this).attr("data-ID")).val();
});
});
I am using jquery. The error I am getting is
Uncaught Error: Syntax error, unrecognized expression: .payAmountForm [data-ID]=1
Missing quotes around data-id attribute at html; also selector is incorrect , currently selecting child element of .payAmountForm ; try removing space between class selector and attribute selector ; adding quotes around data-id attribute at html
Also missing closing brackets at attributes selector
<input type ="text" class="form-control payAmountForm" maxlength="11" data-id="{{report.reportID}}">
payInfo is an Array at js at Question, not an Object ; try using Array.prototype.push()
payInfo.push(
$(".payAmountForm[data-id='" + $(this).attr("data-ID") +"']").val()
);
or to create an array of objects
payInfo.push(
{"amount": $(".payAmountForm[data-id='" + $(this).attr("data-ID") +"']").val()
}
);
$(document).ready(function() {
$(".payButton").click(function(event) {
payInfo = [];
event.preventDefault();
// alert($(this).attr("data-ID"));
payInfo.push({
"amount": $(".payAmountForm[data-id='" + $(this).attr("data-ID")
+ "']").val()
});
console.log($(".payAmountForm[data-id='" + $(this).attr("data-ID") + "']")
, $(this).attr("data-ID")
, payInfo);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="form-control payAmountForm" maxlength="11" data-id="{{report.reportID}}" value="">
<button data-ID="{{report.reportID}}" class="btn btn-success payButton" type="button" value="Pay">Pay</button>

Data doesn't show in AngularJS

First of all I want to apologize for my bad English :)
I am having a problem with AngularJS, when I want to load a modal from datagrid.
Here is my code for the grid:
<tr ng-repeat="data in filtered = (list | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit track by $index">
<td>{{data.lastName}} {{data.firstName}}</td>
<td>{{data.email}}</td>
<td>{{data.phoneNumber}}</td>
<td>{{data.cityID}}</td>
<td><button class="btn btn-primary btn-xs" ng-click="show(data.id)">DETAILS</button></td>
Modal code :
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><strong>{{row.firstName}} {{row.lastName}}</strong> Details</h4>
</div>
<div class="modal-body">
<table class="table table-condensed table-hover info-table">
<tbody>
<tr>
<td>Email:</td>
<td>{{row.email}}</td>
</tr>
</tbody>
</table>
</div>
</div>
and JS code:
$scope.show = function (id) {
$http.get('inc/getDetails.php?id='+id).
success(function(data) {
$scope.row = data;
$('#det-modal').modal('show');
});
};
The modal is loading, but does not load the data.
The code would not work because the row variable is out of scope when the modal is invoked as its in non-angular world.
You should not access the DOM element directly in controller so the following line should not be used in angular world.
$('#det-modal').modal('show');
To fix the issue consider using https://angular-ui.github.io/bootstrap/ which would enable you to pass in the row as a scope variable.

Categories