Jquery to compare the value of dynamically generated control - javascript

Hi I am developing a mvc4 jquery application. I have dynamically generated hidden field and I am binding some value to it as below.
#foreach (var group in Model.detailsbyclientId) {
<tr>
<td> #group.clientName </td>
<td> #group.employeeId </td>
<td> #group.employeeName </td>
<td>#group.Nationality</td>
<td> #group.documentType </td>
<td scope="col">
<input type="button" class="btn btn-primary btn-cons" value="View Document" onclick="showDocumentData('#group.upld_Id');" />
</td>
<td id="Hi">#group.currentStatus</td>
<td><input type="hidden" id="Status" value="#group.currentStatus"/></td>
<td></td>
</tr>
}
In some point of time the value of #group.currentStatus will be NotVerified. For example if I generate 5 rows of data, the value of all 5 rows will be NotVerified. In such a case I want to display some message or else display nothing. So whenever all rows of the data are holding the same value then I want to display a message. This is my jquery function and I have used below logic.
var list = new Array();
$('input[type=hidden]').each(function (i, item) {
list.push($(item).val());
if(list[i]==list[i+1]) {
fun_toastr_notify('success', 'Please verify the document');
} else {
}
});
I am not able to compare each row of data. If all the values are the same then I only want to display my toaster message once. What logic should I use here? Thank you in advance.
I tried as below now.
for(var i=0;i<list.length;i++) {
if(list[i]==list[i+1]) {
fun_toastr_notify('success', 'Please verify the documents');
}
}
Now my problem is that the toaster message will display more than one time. I want to display it only once if all elements are equal.

You may want to consider putting this logic in the code that generates the viewmodel and output a flag to display the message, rather doing it while rendering the view.
This greatly simplifies your logic. An example:
public class YourModel {
public List<ClientDetails> detailsbyclientId {get;set;}
public bool AllClientsUnverified { get { return detailsbyclientId.All(client => client.currentStatus == "Unverified"); } }
}
And then in your view (inside a client <script> block)
if (#Model.AllClientsUnverified) {
fun_toastr_notify('success', 'Please verify the documents');
}

Related

How to pass values from selected checkboxes

This is my view, in this code I select all checkboxes but when I reload my values are not saved, bcs i can't pass nothing in to the controller.
<table class="table table-striped grid-table">
<tr>
<th>Id</th>
<th>Code</th>
<th>
<input type="checkbox" id="box"/>
</th>
</tr>
#foreach (var item in (IEnumerable<cit.Models.getPersonPerName_Result>)Model)
{
<tr>
<td>#item.idper</td>
<td>#item.pername</td>
<td>
<div class="pure-checkbox">
<input type="checkbox" id="#item.idper" class="chk" checked="#(item.idperson == ViewBag.idperson ? true : false)" name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
Here is my js
var selectAllBox = document.getElementById('box');
selectAllBox.addEventListener('click', function () {
var pureCheckboxes = document.getElementsByClassName('chk');
for (var i = 0; i < pureCheckboxes.length; i++) {
pureCheckboxes[i].checked = this.checked;
}
});
My boxes need to be checked on the next reload, in this code I have about 10 persons who can access to this web app
checked="#(item.idperson == ViewBag.idperson ? true : false)"
Your inputs need to be inside a form and you need a post method that accepts the form inputs as parameters when the form is submitted. Alternatively, you can post the values using Ajax. You'll need some sort of persistence like a database to store the values so they can be loaded on next reload without submitting the form.
You shouldn't need to cast your model to anything to iterate through it. You should just pass something like
var model = new List<cit.Models.getPersonPerName_Result>() {
//Populate here
}
return View(model);

How can I bind multi select list items that have been dynamically added using the .net core framework?

I am using .net core 2.2 Razor Pages to build my current project. I want to be able to have 2 multi-select lists in which I pass values from one list to the other and vice versa. I am able to load the left side list with the values required using binding. I also have the buttons to transfer X amount of selected items to the right side list. This is done using jquery. However when I submit my form and get the OnPostAsync The values from the list on the right side are lost and the ones on the left side are as if they where never removed.
I understand that to dynamically add controls that bind to a property you require adding all the necessary attributes. I have compared the generated html from the left list (generated by .net core) to the right side list (generated by me using jquery) and they are identical so I don't see what attributes might be missing...
Below is a sample of the code I am working with.
```html
<table width="100%">
<tr>
<td rowspan="2" class="role-fromto">
<select asp-for="RolesLeft" asp-items="#(new SelectList(Model.RolesLeft, "Id", "Name"))" class="form-control" multiple>
</select>
</td>
<td class="centered">
<a id="role-add" class="button-pointer">>></a>
</td>
<td rowspan="2" class="role-fromto">
<select asp-for="RolesRight" asp-items="#Model.RolesRight" class="form-control" multiple>
</select>
</td>
</tr>
<tr>
<td class="centered">
<a id="role-remove" class="button-pointer"><<</a>
</td>
</tr>
</table>
```
(Please note there is a submit button as well which performs the OnPostAsync)
The properties that are binding are in my C# code. The left side roles are a list of Role objects while on the right side I made a list of SelectListItem which I will later convert in the OnPostAsync method. The left side list is populated in the OnGetAsync method during loading (I am not putting this code here because it works and I want to avoid confusion of bloat code):
```C#
[BindProperty]
public List<Role> RolesLeft { get; set; }
[BindProperty]
public List<SelectListItem> RolesRight { get; set; } = new List<SelectListItem>();
```
Finally the javascript that runs when I select the >> link to move over the selected items to the right side executes the following code:
```JavaScript
$(document).ready(function () {
$("#role-add").on("click", function () {
moveRoles("RolesLeft", "RolesRight");
});
$("#role-remove").on("click", function () {
moveRoles("RolesRight", "RolesLeft");
});
function moveRoles(from, to) {
var items = $("#" + from + " option:selected").map(function () {
return $(this);
}).get();
for (i = 0; i < items.length; i++) {
$("#" + from + " option[value='" + items[i].val() + "']").remove();
$("#" + to).append($('<option />', {
value: items[i].val(),
text: items[i].text()
}));
}
}
});
```
I'm not sure if I missed anything but if so please let me know and I will update the post to provide more information. How can I get this working properly? I have been able to dynamically generate other types of controls and get it to bind but this one I have not had any success.

How to print data by current table on page in Laravel 5?

My problems are:
When I click the print button, it shows the data by text not in table.
I want to print data table depends on the current table show. means
here is on the current page has list of all data and select option.
When I select or filter table it still print all the data. The data
here is collected from database.
After logged in, why does the image for next page not show?
Here is my JavaScript:
<script lang='javascript'>
$(document).ready(function(){
$('#printPage').click(function(){
var data = '<input type="button" value="Print this page" onClick="window.print()">';
data += '<div id="div_print">';
data += $('#report').html();
data += '</div>';
myWindow=window.open('','','width=200,height=100');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.write(data);
myWindow.focus();
});
});
</script>
Blade template:
<tbody id="result">
#foreach($profiles as $profile)
<tr>
<td class="student_id" width="15%">{{$profile->student_id }}</td>
<td class="name" width="30%">{{$profile->student_name }}</td>
<td class="program" width="30%"> {{$profile->program }}</td>
<td class="faculty" width="25%">{{$profile->faculty }} </td>
</tr>
#endforeach
</tbody>
</table>
<p align="center"><button id="printPage">Print</button></p>
Rather than doing the method I suggest that you use a PDF generation plugin such as pdf-laravel.
PDF-LARAVEL :
to output to a file
$router->get('/pdf/output', function() {
$html = view('pdfs.example')->render();
PDF::load($html)
->filename('/tmp/example1.pdf')
->output();
return 'PDF saved';
});
Adding the functionality to your controller
class HomeController extends Controller
{
private $pdf;
public function __construct(Pdf $pdf)
{
$this->pdf = $pdf;
}
public function helloWorld()
{
$html = view('pdfs.example1')->render();
return $this->pdf
->load($html)
->show();
}
If you want to search for other options then go to packagist.org and search for "pdf laravel" and you will find some packages built for Laravel 5 PDF generation.
Answer to the question 2:
I want to print data table depends on the current table show. means
here is on the current page has list of all data and select option.
When I select or filter table it still print all the data. The data
here is collected from database
If you want to filter data and display there, you have two options, either filter data form the controller or you can use jQuery Datatables for that. Link here
All you have to do is:
Add the Js.
https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css
Add the css
http://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js
Call your table.
$(document).ready(function(){
$('#myTable').DataTable();
});
function printData()
{
var print_ = document.getElementById("table_name");
win = window.open("");
win.document.write(print_.outerHTML);
win.print();
win.close();
}
The above function will print the data of a table which are on the current page due to the window.open("") function.

Display a Label and its value on change of dropdown value

I want to display a label and its value when a dropdown value is changed.
For eg:- when AddressType is changed then i want to display the AddressLine1 label and its respective value.
I am able to display the <td></td> part and the label also gets displayed. But the value of Address1 is not getting displayed. I tried setting in ViewBag and then using it in <td></td> but that is not working. I tried to set the value of displayFor id also. but that too doesn't work.
How can i display the value ?
Code:
<td id="Address1Label">
#Html.LabelFor(model => model.Address1)
</td>
<td id="Address">
#this.ViewBag.AddressLine1
#Html.DisplayFor(model => model.Address1, new {#id = "Address1" })
</td>
$(document).ready(function () {
$('#Address1Label').hide();
$('#Address').hide();
});
$(function () {
$('#AddressType').change(function (e) {
// i call an Action and get the result as json
if (data.HomeAddress != null) {
$('#Address1Label').show();
$('#Address').show();
// $('#Address1').val(data.HomeAddress.Address1);
$('#Address1').html(data.HomeAddress.Address1);
});
As far As I know
#Html.DisplayFor<TModel, TValue>
by default, ignore your overload html attributes which means
<td> #Html.DisplayFor(model => model.Address1, new {#id = "Address1" }) </td>
only produce an text like
<td> Address </td>
instead of what you may think like
<td><xxx id="Address1"> Address </xxx></td>
So if you want to change this value, you can do
$('#Address').html(data.HomeAddress.Address1);

Using $index for ng-model

I am building a SPA where one can add a table-row on button-click:
<!-- Table -->
<table>
<tr>
<th>Lieferscheinnummer</th>
<th>Stück</th>
</tr>
<tr ng-repeat="position in positions">
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</table>
<!-- button -->
<span ng-click="addPosition()"></span>
Controller
$scope.positions = ['1'];
$scope.addPosition = function(){
$scope.positions.push( $scope.positions.length + 1 );
}
Now I have to apply an unique ng-model to each <td> of every row in order to send the given input to my database.
I searched for a solution and stumbled over ng-repeat's $index.
Unfortunately, $index seems to be not available for element attributes:
<tr ng-repeat="position in positions">
<td><input type="text" ng-model="{{$index +1}}"></td> <!-- does not work -->
<td><input type="text"></td>
</tr>
How would I apply an unique ng-model to each row while using ng-repeat?
You could change your model. Currently, you are using the ng-repeat like a counter. You have a model that stores the elements - you are not using the elements in anyway, just making use of the number of elements in the list and looping that many times.
What you could instead do is have a list of unique models itself.
Considering that you are using it inside a table, each entry could have an ID field to uniquely identify each row.
Thus, your model would look something like this:
//Will contain the data entered in the table
$scope.tableData = [
{
id: 1,
data: ""
},
{
id: 2,
data: ""
}
];
//Will keep track of the last used ID
$scope.currentId = 2;
//Will add a record to the table each time it is called
$scope.addRecord = function () {
var newRecord = {
id: $scope.currentId++;
data: ""
};
$scope.tableData.push(newRecord);
};
In your view, you can now use tableData to loop over the actual data itself rather than the count of the records:
<tr ng-repeat="entry in tableData">
<td>
<input type="text" ng-model="entry.data">
</td>
</tr>
For another input, you could simply add another attribute to each record. ng-repeat will create a scope for each record so entry.data will always point to the data attribute for the record located at that row.
Note: For an ID, you may have to use another approach of generating unique Ids for large amounts of records. Simply increment a counter will not be the best approach.

Categories

Resources