How to pass values from selected checkboxes - javascript

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);

Related

HTML input fields contents keep disappearing

I am building a webpage to monitor my stocks and mark some comments for each stock.
I got the volume and the price of each of the stocks from an api I built and wrote some code to put them into a table.
The table has some other fields as well:
Name, Price, Volume, Comments, Target Price
The comments and target prices contain input fields which I can type in some notes for each stock.
However, my code builds a new table every 10s to update the stock prices and volume, and after each sort action which is triggered by pressing the corresponding heading I want to sort by. After this, my inputs fields contents will disappear. Is there a way to keep these contents intact after an update or a sorting is triggered?
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<table class="table table-striped" style="float: left; width: 60%">
<tr class="bg-primary">
<th data-column="name" data-order="dsc">Name &#9650</th>
<th data-column="price" data-order="dsc">price &#9650</th>
<th data-column="volume" data-order="dsc">Volume &#9650</th>
<th data-column="targetPrice" data-order="dsc">Target Price &#9650</th>
<th data-column="comments" data-order="dsc">Comments &#9650</th>
<th data-column="submit" data-order="dsc">Send &#9650</th>
</tr>
<tbody id="myTable">
</tbody>
</table>
<script>
var myArray = []
var sortOrder = 'name'
var sortColumn = 'dsc'
setInterval(function() {
$.ajax({
method:'GET',
url:'http://127.0.0.1:5000',
success:function(response){
myArray = response.data
if(sortOrder == 'dsc'){
myArray = myArray.sort((a,b) => a[sortColumn] > b[sortColumn] ? 1 : -1)
}else{
myArray = myArray.sort((a,b) => a[sortColumn] < b[sortColumn] ? 1 : -1)
}
buildTable(searchTable(myArray))
}
})
}, 10000)
function buildTable(data){
var table = document.getElementById('myTable')
table.innerHTML = ""
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].name}</td>
<td>${data[i].price}</td>
<td>${data[i].volume}</td>
<td><input type="number" name="${data[i].symbol}_targetPrice" style='width:60px;'></td>
<td><input type="number" name="${data[i].symbol}_comments" style='width:60px;'></td>
<td><input type="submit"></td>
</tr>`
table.innerHTML += row
}
}
</script>
The submit button is to send back the name, target price and comments as a dictionary back to the server, which I'm still figuring out how to do, however, the problem of the field contents disappearing is a much larger problem. Thanks in advance.
I think that your problem is in the UX more than in the code.
Re-building the HTML containing input elements every 10 seconds is a bad idea because:
You're going to lose focus of the input that you're typing in.
It's going to be overridden with the new data. (the problem you're facing)
It's confusing that inputs that you don't change get updated automatically.
To me it makes more sense to have a table with all the data (but no inputs), that can be updated every 10s. And an edit button that when is clicked shows a form with the inputs that won't update while you're typing.

Jquery to compare the value of dynamically generated control

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');
}

How pick up checkbox result in post method angularjs

I have a table that sets out a list of rules. When the checkboxes are clicked, I need them to take this "true" value and post to an API endpoint. This has been set up, but what I am getting back is that "associated_rule" is undefined.
I have tried setting $scope.associated_rule.selected = true; in my controller, but this still doesn't define the variable and throws up the same error in the console.
Here is my HTML form:
<form name="rules_form" method="post" ng-submit="attach()">
<table class="table table-striped table-hover" ng-model="associated_rules">
<thead>
<th>Rule Types:</th>
<th>Description:</th>
<th>Start Time:</th>
<th>End Time:</th>
<th>Apply Rule to Vehicle:</th>
</thead>
<tr ng-repeat="associated_rule in associated_rules">
<td>#{{ associated_rule.resource_ids.accounts }}</td>
<td>#{{ associated_rule.description }}</td>
<td>#{{ associated_rule.start_time }}</td>
<td>#{{ associated_rule.end_time }}</td>
<td><input type="checkbox" ng-model="associated_rule.selected" aria-label="rule"></td>
</tr>
</table>
<button class="btn btn-primary" ng-click="attach()">Attach</button>
</form>
My Controller event:
$scope.attach = function () {
$scope.associated_rule.selected = true;
var i;
for (i = 0; i < $scope.associated_rule.selected.length; i++) {
//need to create a loop where the true value is picked up and then I can send the data using a POST method. But I'm stuck on this.
}
console.log(the result of the event);
};
For now, I just want the results to console.log, so I can see that the event is creating the loop and displaying the results. After that, I should be OK.
Any help would be much appreciated.
I have fixed this by defining the $scope.rule as an empty array and setting the $scope.rule.selected to "false" by default.
Great! step one! But the checkboxes are ALL selecting when you click A checkbox - think this may be the ng-repeat causing me a pain in the backside.
$scope.rule = [];
$scope.rule.selected = false;
So, how do I ensure that only the checkboxes set that I select and not all at once?
Fixed this too; as the above was just making the entire array selected; as i wasn't drilling down into the array. This did it:
ng-model="rules.selected[associated_rule.id]"
by modelling the a rule within that defined array, it shows up when testing. Brill. :)
By mistake you are changing the value of your check box on clicking the button:
$scope.associated_rule.selected = true;
This will give the current value, selected or not selected
$log.log($scope.associated_rule.selected);

knockout observable array is not updating view on removing elements from array

Here is my view model code
var TopicsViewModel = function() {
var self = this;
var fakeTopicData =
[
];
self.createProfile = function () {
alert("came to create profile");
};
self.editProfile = function () {
alert("came to edit profile");
};
self.removeProfile = function (profile) {
alert("came to remove profile");
fakeTopicData.pop();
self.topicsArr(fakeTopicData);
};
var refresh = function() {
self.topicsArr = fakeTopicData;
};
self.topicsArr = ko.observableArray([]);
refresh();
};
ko.applyBindings(new TopicsViewModel());
Here is my html for the view:
<hr />
<hr />
<table class="table table-striped table-bordered table-condensed">
<tr >
<th>Area</th>
<th>Name</th>
<th>Link</th>
<th>Description</th>
<th>Why</th>
</tr>
<tbody data-bind="foreach : topicsArr">
<tr>
<td data-bind="text :area"> </td>
<td class=""><a data-bind="text:name, click:$parent.editProfile"></a></td>
<td data-bind="text:link"> </td>
<td data-bind="text:desc"> </td>
<td data-bind="text:why" ></td>
<td><button class="btn btn-mini btn-danger" data-bind="click:$parent.removeProfile">remove</button></td>
</tr>
</tbody>
</table>
<script src="~/Scripts/Topic.js"></script>
The view initially display all the Topics in my fakeData Array.
On clicking the remove Button, I am trying to remove an element from the array, and expected the view to refresh and not show the removed item any more. However the view still shows all the 3 topics.
Could someone please point to what I might be doing wrong.
I spend a long time researching the other similar queries on stackoverflow, but am still stuck. Thanks so much for any insight into this issue.
You are replacing your observable array called topicsarr with one which isn't observable in your refresh method...
Change
var refresh = function() {
self.topicsArr = fakeTopicData;
};
to
var refresh = function() {
self.topicsArr(fakeTopicData);
};
you have 2 issues in your code.
First, you are setting your observableArray topicsArr with non observableArray or normal array in refresh function. Instead use self.topicsArr(fakeTopicData)
Second, in function removeProfile you are using pop() to remove profile element. From KnockoutJS documentation:
myObservableArray.pop() removes the last value from the array and
returns it
So, it's better to use remove(item) and pass to it your profile element or loop through your array and remove that specific item
myObservableArray.remove(someItem) removes all values that equal
someItem and returns them as an array

How to select a row from dynamic table on mouseclick event

How can get a row's value on mouse click or checking the checkbox preferably from the below given html table?
Here is the js for getting values for my table from a xml using spry
var ds1 = new Spry.Data.XMLDataSet("xml/data.xml", "rows/row");
var pv1 = new Spry.Data.PagedView( ds1 ,{ pageSize: 10 , forceFullPages:true, useZeroBasedIndexes:true});
var pvInfo = pv1.getPagingInfo();
Here is the Div with spry region containing the table that gets populated from pv1 (see js part)
<div id="configDiv" name="config" style="width:100%;" spry:region="pv1">
<div spry:state="loading">Loading - Please stand by...</div>
<div spry:state="error">Oh crap, something went wrong!</div>
<div spry:state="ready">
<table id="tableDg" onclick="runEffect('Highlight', 'trEven', {duration: 1000, from: '#000000', to: '#805600', restoreColor: '#805600', toggle:true}, 'Flashes a color as the background of an HTML element.')"
style="border:#2F5882 1px solid;width:100%;" cellspacing="1" cellpadding="1">
<thead>
<tr id="trHead" style="color :#FFFFFF;background-color: #8EA4BB">
<th width="2%"><input id="chkbHead" type='checkbox' /></th>
<th width="10%" align="center" spry:sort="name"><b>Name</b></th>
<th width="22%" align="center" spry:sort="email"><b>Email</b></th>
</tr>
</thead>
<tbody spry:repeat="pv1">
<tr class="trOdd"
spry:if="({ds_RowNumber} % 2) != 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #FFFFFF">
<td><input type="checkbox" id="chkbTest" class = "chkbCsm"></input></td>
<td width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
<tr class="trEven" name="trEven" id="trEven"
spry:if="({ds_RowNumber} % 2) == 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #EDF1F5;">
<td><input type="checkbox" class = "chkbCsm"></input></td>
<td id="tdname" width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
</tbody>
</table>
</div>
</div>
I am trying the below code but still I am not getting the alert and hence none of the answers are also not working. I know the syntax n all are everything correct, but i am not able to figure out what is the problem here!
//inside $(document).ready(function()
$("#chkbHead").click(function() {
alert("Hi");
});
My page has other tables too for aligning some contents. So when I use the below code it works perfectly on those tables except the one in the question. It might be the problem because there are only 2 tr in the table which gets populated by a spry dataset and hence not getting identified properly. May be, I am not sure, just trying to help improve my understanding
$('tr').click(function() {
alert("by");
});
The values of a Row you will get with:
$('#tableDg tbody tr').live( 'click', function (event) {
$(this).find('td').each( function( index, item ) {
if ( $(this).has(':checkbox') ) {
alert( $(this).find(':checkbox').val() );
} else {
alert( $(this).text() );
}
};
});
What exactly do you mean by value of a table row? You can get the inner html of a table row like this:
var html = '';
$('tr').click(function() {
html = $(this).html();
});
You can get attributes of the table row (e.g. it's Id) like so:
var id = '';
$('tr').click(function() {
id = $(this).attr('id');
});
Alternatively you can get the value of nested elements such as a text input like so:
var text = '';
$('tr').click(function() {
text = $(this).find('#myTextBox').val();
});
EDIT
This is how to change the checked attribute of a checkbox nested in a table row:
$('tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
EDIT
As the table rows are being loaded dynamically - the $().click() event binding method will not work, because when you are calling it - the table rows do not exist, so the click event cannot be bound to them. Instead of using $().click use the jQuery live method:
$('tr').live('click', function() {
// do stuff
});
This binds the click event to all current table rows and all table rows that may be added in the future. See the jQuery docs here
you have to use Spry Observer,
something like this:
function funcObserver(notificationState, notifier, data) {
var rgn = Spry.Data.getRegion('configDiv');
st = rgn.getState();
if (notificationState == "onPostUpdate" && st == 'ready') {
// HERE YOU CAN USE YOUR JQUERY CODE
$('#tableDg tbody tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
}
}
Spry.Data.Region.addObserver("configDiv", funcObserver);

Categories

Resources