Display a Label and its value on change of dropdown value - javascript

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

Related

How to compare changed values and actual values from table using Jquery

I have a table using foreach I'm filling the td values. There is a check box when user is changed that value i need to get username.
For example while loading time checkbox value is true. Then user will do uncheck immedetaily i should get the value. Same user same row if user check again(i.e old postion(value)) i shouldn't the values.
My Code:
<table>
.......
<tr>Heading 1</tr>
........
#foreach (var getData in Model.DBValue)
{
<tr>
<td>
#Html.CheckBoxFor(model => getData.AffectedItemId, new { #id =
"AffectedItemIdR" + index, #class = "RChangeEvent", #checked =
getData.AffectedItemId })
</td>
<td>
#Html.TextBoxFor(model => getData.updatedDate, "{0:MM/dd/yyyy}", new {
#disabled = "disabled", #id = "SignedDateR" + index})
</td>
</tr>
}
</table>
Question:
If there 100 rows how to get the changed rows values?
Could you please help to solve this?

How do I get specific values from checked rows in MVC razor view?

Ok, so I have this partial view (part of an MVC application) which just displays data from a view in the database.
#model IEnumerable<TransportPlanner.Models.TRANSPORT_PLANNER_VIEW>
<table>
<tr>
<th>#Html.CheckBox("HeaderCheck")</th>
<th>#Html.DisplayNameFor(model => model.Status)</th>
....
<th>#Html.DisplayNameFor(model => model.Volume)</th>
<th>#Html.DisplayNameFor(model => model.Weight)</th>
....
</tr>
#foreach (var item in Model) {
<tr>
<th>#Html.CheckBox("RowCheck")</th>
<td>#Html.DisplayFor(modelItem => item.Status)</td>
....
<td>#Html.DisplayFor(modelItem => item.Volume)</td>
<td>#Html.DisplayFor(modelItem => item.Weight)</td>
....
</tr>
}
</table>
I want to be able to find a way in which I can get the values for the Volume and Weight fields of only the checked rows (after checking them), and add them to get the total (which is displayed but not stored).
For example, once I get the results displayed on screen, and I check 3 rows (having the values of 'weight' as 5, 10 and 15), then value displayed should be '30' (sum of the weights). Similarly, if I remove the checkbox for the row having weight as '5', then the value displayed should be '25'.
My front end skills are almost non-existent, and I have scourged over the internet for nearly 12 hours but not found a way to do it. I know that I need to either use JavaScript (or some flavour of it like JQuery) or Ajax (if I need the values updates dynamically as I check/uncheck them).
What is the best way to achieve this, without updating my model? I don't have the luxury of time because I am the only developer at my workplace, and this is the first step of a huge task I need to complete in 3 weeks.
Your #Html.CheckBox("RowCheck") is generating invalid html (duplicate id attributes). Replace it with
<input type="checkbox" class="checkbox" />
Then add class names to the <td> elements for Volume and Weight
<td class="volume">#Html.DisplayFor(modelItem => item.Volume)</td>
<td class="weight">#Html.DisplayFor(modelItem => item.Weight)</td>
And assuming you want to display the totals in the table footer, add the following html to the <table> element (note you should also use the <thead> and <tbody> in your table
<table>
....
<tfoot>
<tr>
<td></td>
....
<td id="totalvolume"><td>
<td id="totalweight"><td>
....
</tr>
</tfoot>
</table>
Then you can use javascript/jquery to handle the change event of the checkboxes, and sum the values in each row. Using jquery:
$('.checkbox').change(function() {
var totalVolume = 0;
var totalWeight = 0;
var selected = $('.checkbox:checked'); // get the selected checkboxes
$.each(selected, function(index, item) { // loop through the selected checkboxes
var row = $(this).closest('tr'); // get the containing tr element
totalVolume += Number(row.find('.volume').text());
totalWeight += Number(row.find('.weight').text());
})
// display the totals
$('#totalvolume').text(totalVolume);
$('#totalweight').text(totalWeight);
});
Note, the above code assumes the values of properties Volume and Weight are numeric (without any formatting)

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 to get html table values from multiple columns with single checkbox and submit to servlet?

I have html data table. I want to get values from multiple columns with single checkbox and when click on submit button values should go to servlet. Please help how to do this?
function refile(){
$('#resend').click(function() {
$("input:checked").each(function () {
var id = $(this).attr("id");
var messagePayload = $('#'+id).val();
var messageType = $('#msgType'+id).val();
alert("Payload Alert:"+ messagePayload);
alert("MessageType Alert:"+ messageType);
$.ajax({
type: "POST",
url: "http://localhost:8080/InterfaceMonitoring/ResendServlet",
data: {
messagePayload:messagePayload,
messageType:messageType
}
});
});
});
}
<c:otherwise>
<c:forEach items="${msgs}" var="msg" varStatus="count">
<tr id="check">
<td>
<input type="checkbox" id ="payloadMsg${count.index}" name="payload" value="${msg.messagePayload}">
</td>
<td></td>
<td>${msg.dob}</td>
<td></td>
<td>${msg.name}</td>
<td></td>
<td>
<div class="accordion">
<h3>Payload</h3>
<div id="payloadMsg${count.index}">${msg.messagePayload}</div>
</div>
</td>
<td></td>
<td>
<div id="msgType${count.index}">${msg.messageType}</div>
</td>
</tr>
</c:forEach>
</c:otherwise>
The problem is the way you try to get messageType.
Since you're using the ID of the input element, and prefixing it with #msgType it results in #msgTypepayloadMsgX so that element will never be found.
And since it's a DIV you're looking for you should use .html() to get the content.
Try adding data-index="${count.index}" to each input[checkbox] and get it in the script using $(selector).data('index') so that you can query for $('#msgType' + index)
And you should not make an ajax request for each row. Instead store the payloadMessage and messageType in an object and send it all to the backend at once, after iterating all rows.
An example could be:
Javascript
function refile(){
$('#resend').click(function() {
var payloads = [];
$('input:checked').each(function () {
var $this = $(this),
index = $this.data('index'),
$type = $('#msgType' + index);
payloads.push({
messageType: $type.html(),
messagePayload: $this.val()
});
});
if (payloads.length === 0) {
return;
}
$.ajax({
type: 'POST',
url: 'http://localhost:8080/InterfaceMonitoring/ResendServlet',
data: {
'payload': payloads
}
});
});
}
HTML
<tr id="check">
<td><input type="checkbox" id="payloadMsg${count.index}" data-index="${count.index}" name="payload" value="${msg.messagePayload}"></td>
<td></td>
<td>${msg.dob}</td>
<td></td>
<td>${msg.name}</td>
<td></td>
<td>
<div class="accordion">
<h3>Payload</h3>
<!-- Note that this ID is conflicting with the input#payloadMsg${count.index} -->
<div id="payloadMsg${count.index}">${msg.messagePayload}</div>
</div>
</td>
<td></td>
<td>
<div id="msgType${count.index}">${msg.messageType}</div>
</td>
</tr>
So, from what I've seen, on the front-end, at least, your code SHOULD work, but you've made it REALLY complex. . . . more complicated than you need it to be, I think. Again, while it should work, simplifying it will mean that there are much fewer places in the code where something could go wrong.
I think the best way to do this is make it easy on yourself:
flag the <div> elements that you want to retrieve with a class value that you can use to get their values (rather than relying on the unique IDs)
make the "unique" identifier of the message at the highest level in the table as you can (in this case, the <tr>
simplify your HTML attributes . . . you've got a lot of duplicate data and excess identifiers in your table structure. Try something like this:
HTML
<c:otherwise>
<c:forEach items="${msgs}" var="msg" varStatus="count">
<tr id="payloadMsg${count.index}">
<td>
<input type="checkbox" name="payload">
</td>
<td></td>
<td class="msg-dob">${msg.dob}</td>
<td></td>
<td class="msg-name">${msg.name}</td>
<td></td>
<td>
<div class="accordion">
<h3>Payload</h3>
<div class="msg-payload">${msg.messagePayload}</div>
</div>
</td>
<td></td>
<td>
<div class="msg-type">${msg.messageType}</div>
</td>
</tr>
</c:forEach>
</c:otherwise>
Once you've set that up, you have a much more simple structure, with all of the values that you could ever need, clearly identified. Now, you can pretty easily you can pretty easily get to the values that you need, using jQuery . . . just update your existing code to be something like this:
$(document).ready(function() {
$('#resend').click(function() {
$("input:checked").each(function () {
var currRow = $(this).closest("tr");
var currPayload = currRow.find(".msg-payload").text();
var currType = currRow.find(".msg-type").text();
alert("Payload Alert:"+ currPayload );
alert("MessageType Alert:"+ currType );
$.ajax({
type: "POST",
url: "http://localhost:8080/InterfaceMonitoring/ResendServlet",
data: {
messagePayload: currPayload,
messageType: currType
}
});
});
});
});
NOTE: You were using .val() instead of .text() to retrieve the text in the "type" <div> . . . .val() is only used with input elements.
Not knowing what you are doing on the back-end with this data, I can't really help you make sure that it is storing it correctly, but removing the reliance on the indexes to find the data that you want, should help simplify your logic a lot.
Also, if you ever want any other data from the row, you can capture it pretty easily now . . . for example:
var currMsg = currRow.attr("id");
var currDOB = currRow.find(".msg-dob").text();
var currName = currRow.find(".msg-name").text();
. . . after you have set the currRow value in your code, of course. :)
So, give that a try and see how things go. On the front-end, you should be good with this, at that point, you would need to just focus on the back-end and make sure that everything is working there.

How to validate the Two Date fields on my view using jquery or javascript

I have two fileds in my View one is Effective data and one is Cancel date
<td>
Effective date:
</td>
<td>
<%= Html.TextBoxFor( x => Model.SelectedAccountGroup.GroupEffectiveDate, new { #class="datepicker"} )%>
<%= Html.ValidationMessageFor( x => x.SelectedAccountGroup.GroupEffectiveDate )%>
</td>
</tr>
<tr>
<td>
Cancel date:
</td>
<td>
<%= Html.TextBoxFor( x => Model.SelectedAccountGroup.GroupCancelDate, new { #class = "datepicker" } )%>
<%= Html.ValidationMessageFor( x => x.SelectedAccountGroup.GroupCancelDate )%>
</td>
On Save button I should not allow user to Enter the Cancel date Before Effective data? can any body tell me how to do this?
get the two date field value as a single integer value . For eg 20101006 .
if time is also there add that too,
if you use jquery
var dateval= $("#dateid").val();
for javascript
var dateval = document.getElementById("dateid").value;
I assume the text box where you show date is having an id. let it be dateid
Now you can compare two fields just as integer.
if(date1>date2)
do something
return false

Categories

Resources