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>
Related
I'm stuck with my project, please help...
This is the situation: In my project I have to assign a teacher to give permission to grade students, because a group can have 2 or more teachers, but only one has to have permission to grade, so... I added a column in my table 'teachers' in the database with the name 'grade' of type boolean. And in my view I added a checkbox... How do I change the value of a checkbox without using any form or button to trigger the action and activate the checkbox in the teacher who is going to have permission to grade? And this value should also be updated in the database.
This is my view...
<!--teachers-->
<table class=" table table-sm table-striped table-bordered ">
<thead class="text-white bg-primary">
<tr>
<th>#lang('show.Identifier')</th>
<th>#lang('show.email')</th>
<th>#lang('show.grade')</th>
<th>#lang('show.delete')</th>
</tr>
</thead>
<tbody class="small text-center">
#foreach ($group->teachers as $teacher)
<tr>
<td >{{$teacher->Identifier}} </td>
<td >{{$teacher->email}} </td>
<td>
<input id="active" {{$teacher->grade == 1 ?'checked':''}} type="checkbox" name="grade" value="1">
</td>
<td>
<form method="post" action="{{url('Groups/Disenroll/'.$group->idGroup.'?idTeacher='.$teacher->idTeacher)}}">
{{csrf_field()}}
<button type="submit" class="btn btn-sm btn-outline-danger" > <i class="material-icons small" >call_split</i></button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
And this is an image of the table, if it helps...
I think you can use something like JQuery for this.
You can firstly add a class of toggle-class to your checkbox
<input class="active toggle-class" {{$teacher->grade == 1 ?'checked':''}} type="checkbox" name="grade">
And secondly, make sure that you have a way to keep track of who's doing the grades.
Add data-id="{{ $teacher->Identifier}}" on your checkbox
<input data-id="{{ $teacher->Identifier}}" class="active toggle-class" {{$teacher->grade == 1 ?'checked':''}} type="checkbox" name="grade">
In your web.php add a new route
Route::get('/path/to/updateGrader/status', [App\Http\Controllers\MyController::class, 'updateGraderStatus']);
Add the below code to where your checkbox is located
$('.toggle-class').on('change',function(){
let status = $(this).prop('checked') == true ? true : false;
let grader_id = $(this).data('id');
$.ajax({
type:'GET',
dataType:'json',
url:'/path/to/updateGrader/status', // add your earlier created route here
data:{'grade': status, 'grader_id': grader_id},
success: function(data){
console.log('success');
}
});
});
In your Controller, MyController in our case create a new function
public function updateGraderStatus(Request $request)
{
$grader = MyModel::find($request->grader_id);
$grader->grade = $request->grade;
$grader->save();
}
Please let me know if this helps you. I didn't test it out but I think this is how you would go about it.
Is there a way to read through an HTML page and return the value of the dynamic checkboxes which are clicked?
Now, I know how to get values from static check boxes even without using JS but since I am generating the below check boxes using data from Database I am not sure how to pin point each one and know which one the user checked,
When I went through developer tools in chrome I can see that the value of the generated check boxes changes but when I refer to them it still does not work.
<!DOCTYPE html>
<html lang="en">
<form action="/test" method="post">
<button type="submit" id="exporst-btn" class="btn btn-primary">Import Test Data <span class="glyphicon glyphicon-import"></span></button>
<br>
<br>
<div id="table">
<table class="table table-condensed">
<thead>
<tr>
<th>Selection</th>
<th>Slno</th>
<th>Region</th>
</tr>
</thead>
<tbody>
{% for obj in TD %}
<tr>
<td>
<input type="checkbox" name="chb[]" > {{obj.OEHR_Mtest_Slno}}
</td>
<td>
{{obj.OEHR_Mtest_Slno}}
</td>
<td>
{{obj.OEHR_Mtest_SF_Part_Number}}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!--<p id="export" name="test"></p>-->
<input type="hidden" id="exp" name="test">
<button type="submit" id="export-btn" class="btn btn-success">Execute <span class="glyphicon glyphicon-play"></span></button>
</form>
</body>
<script type="text/javascript"><!--
$('#export-btn').click(function () {
alert($('#mytable').find('input[type="checkbox"]:checked').length + ' checked');
});
</script>
</html>
I can use the above JS to know how many checkboxes have been checked, I want to know the value of the ones checked and I am not able to get that.
If I'm not mistaken,
var foo = $('#mytable').find('input[type="checkbox"]:checked')
will return an array of html elements which are checkboxes, and are checked. You can then do:
var bar = [];
foo.each(function (index) {
var baz = this.parentNode.textContent || this.parentNode.innerText;
if (baz && baz.length > 0)
bar.push(baz);
});
console.log(bar);
That will make bar an array of the values which were checked. It gets the checkboxes which were checked, finds their parents (<td> tags), and gets the text inside (which skips the <input> tags). This will do it client-side.
Because you're dynamically generating the checkboxes, it's helpful to also dynamically generate the values for the checkboxes. That way, when you POST the request via the submit button, Flask can determine which checkboxes were checked by reading the values. I would change your HTML to:
{% for obj in TD %}
<tr>
<td>
{# Assuming obj.OEHR_Mtest_Slno is a unique value #}
<input type="checkbox" name="chkbox" value="{{obj.OEHR_Mtest_Slno}}"> {{obj.OEHR_Mtest_Slno}}
</td>
<td>
{{obj.OEHR_Mtest_Slno}}
</td>
<td>
{{obj.OEHR_Mtest_SF_Part_Number}}
</td>
</tr>
{% endfor %}
Then in your backend, you can access the values via:
# Use .getlist if you are using HTML form elements with the same name
chkbox_values = request.form.getlist('chkbox') # returns a list of values that were checked
I need the array length
html code
<form action="#" method="POST" name="form1">
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr id="profile_1_">
<td>Geethu</td>
<td>2017-05-10 06:20:35</td>
<td><button type="button" class="btn btn-danger btn-xs remove-profile" id="1">Remove</button></td>
<td><input type="hidden" name="candidate[1]"></td>
</tr>
<tr id="profile_2_">
<td>John</td>
<td>2017-05-10 09:04:12</td>
<td><button type="button" class="btn btn-danger btn-xs remove-profile" id="2">Remove</button></td>
<td><input type="hidden" name="candidate[2]"></td>
</tr>
</tbody>
</table>
</form>
I want to get the count of candidate array each time i remove a table row.
javascript code
<script type="text/javascript">
$(".remove-profile").click(function(){
alert($('input[name="candidate[]"]').length);
var id = $(this).attr('id');
$('#profile_'+id).remove();
getTotal();
});
function getTotal(){
var count = $('input[name="candidate[]"]').length;
var total = count * 10 ;
$('input[name=total]').val(total);
}
</script>
but I'am getting count as 0 always.
Firstly add a class to your table tbody say .profile-tbody
<tbody class="profile-tbody">
#foreach($data as $key => $item)
...
#endforeach
</tbody>
Next add the following jQuery code
$(".profile-tbody").on( "click", ".remove-profile", function() {
$('.profile-tbody tr').length;
});
Since you're removing elements dynamically, you need to use the event delegation approach to attach an event handler to the element. A simple .click(function would not work.
Assuming the number of <tr>(rows) are the number of items($item) in your array
Also please remove the $('input[name="candidate[]"]').length you have added, you are just checking the length of a input field(textbox) which is not even present & hence it will always return 0.
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.
How can I get the id of tbody's input when #moveToAnTable is clicked using jQuery? Thanks.
<table id="yearSectionAdd2Table">
<thead>
<tr id="columnHeader">
<th>
<div>
<input id="moveToAnTable" type="button" value="<<">
</div>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<center>
<input id="moveToAnTableOne" type="button" value="<<">
</center>
</td>
</tr>
</tbody>
</table>
Use jQuery.closest to get the table of the button.
After that search for the input.
jQuery.attr will return the attribute of the first element in the match:
$("#moveToAnTable").click(function(){
var id = $(this).closest("table").find("tbody input").attr("id");
alert(id);
});
See the fiddle:
http://jsfiddle.net/URGVp/
You can also write it like this with the on method, and test out your results in a console window if that better suits you, rather than constant pop-ups.
$('#moveToAnTable').on("click",function(){
var mvalue = $(this).closest('table').find('tbody input').attr('id');
console.log('my value is: ' + mvalue);
});