this is the razor code of the elements that will be generated
#{ k = 0; };
#foreach (var item in Model.Where(q=>q.isOrginal==true))
{
<tr>
<td>Starting Time</td>
<td>
#Html.Hidden("[" + i + "].isOrginal", true)
#Html.DropDownList("[" + i + "].StartingTime", new SelectList(ViewBag.StartingTime, "Value", "Text", item.StartingTime.ToString()), new { #class = "no-select dropdown", data_id= #k,id="starting-true" + #k, data_val="true" })
</td>
<td>Ending Time</td>
<td>
#Html.DropDownList("[" + i + "].EndingTime", new SelectList(ViewBag.EndingTime, "Value", "Text", item.EndingTime.ToString()), new { #class = "no-select dropdown", data_id = #k,id = "ending-true" + #k, data_val = "true" })
</td>
<td>Charges</td>
<td>
#Html.TextBox("[" + i + "].Charges", item.Charges, new { #class = "original", data_id = #k, id = "original-false" + #k })
</td>
</tr>
i++;
k++;
}
this is the jquery code so far
$(document).on('change', '.dropdown', function (e)
{
$('.dropdown').each(function (i, obj) {
var ii = $(obj).attr("data-val");
if (ii == "true") {
console.log(ii);
}
});
});
suppose there are 8 dropdown generated on the page
st en
st en
st en
st en
whichever dropdown i onchanges i want to start loop from the next dropdown to the last. if it is the last i don't want to loop through anything. how can i achieve this?
Try below code (not tested as per your scenario but should work)
$(".dropdown").on("change",function(e){
var nextdps = $(this).nextAll(".dropdown");
if(!nextdps){
nextdps = [];
}
var nextTrs = $(this).parents("tr").nextAll("tr");
$.each(nextTrs,function(i,elm){
var trDps= $(elm).find(".dropdown");
if(trDps){
nextdps.push(trDps);
}
});
$.each(nextdps,function(i,elm){
var ii = $(elm).attr("data-val");
if (ii == "true") {
console.log(ii);
}
})
});
You can do this way. I changed change event to click so you can click on any word and see the following highlighted in red.
This way you can have dropdowns anywhere in your code, as long as the have their id set.
var id;
$(document).on('click', '.dropdown', function(e)
{
id = $(this).attr('id').split('dropdown').pop();
id = parseInt( id );
$('.dropdown').removeClass('red');
$('.dropdown').each( check );
});
function check( index )
{
if ( id == $('.dropdown').length -1 ) { return }
if ( index <= id ) { return }
$('.dropdown').get(index).classList.add('red');
// Do whatever you want here with `index`
}
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown" id="dropdown0">Zero</div>
<div class="dropdown" id="dropdown1">One</div>
<div class="dropdown" id="dropdown2">Two</div>
<div class="dropdown" id="dropdown3">Three</div>
<div class="dropdown" id="dropdown4">Four</div>
Related
I'm trying to create an aggregated table in which the subordinate elements would sum up to their parent elements. Each element contains a class that is equal to the id of its parent element. I have added event listener to every element of the table, so that the summation would go upwards the tree.
The code looks roughly as follows:
var x = document.getElementsByName("item.AmountY0");
for (i = 1; i < (x.length - 3); i++) {
x[i].addEventListener("change", function(e) {
if (x[i].tagName == "TD") {
document.getElementById("y0_" + x[i].className).innerHTML =
String(parseInt(document.getElementById("y0_" + x[i].className).innerHTML) + parseInt(x[i].innerHTML));
}
if (x[i].tagName == "INPUT") {
document.getElementById("y0_" + x[i].className).innerHTML =
String(parseInt(document.getElementById("y0_" + x[i].className).innerHTML) + parseInt(x[i].value));
}
}, false);
};
When I check the individual table elements in console, the direct parent element gets updated, but not the other grand-parents. However, when I run the page, nothing happens (and no errors are reported).
The corresponding HTML code is as follows:
#foreach (var item in Model)
{
string y0_id = "y0_" + item.AlphaCode;
string class_parent = item.ParentCode;
string class_parent_right = item.ParentCode + " " + item.CssClassAmt;
<tr class="#item.CssClassRow">
<td hidden="true">#Html.DisplayFor(modelItem => item.FullSymbol)</td>
<td hidden="true">#Html.DisplayFor(modelItem => item.AlphaCode)</td>
<td hidden="true">#Html.DisplayFor(modelItem => item.ParentCode)</td>
<td>#Html.DisplayFor(modelItem => item.Symbol)</td>
<td class="#item.CssClassCell">#Html.DisplayFor(modelItem => item.PositionName)</td>
#if (item.IsFinal[0].Equals('0')) {
<td id=#y0_id class=#class_parent style="text-align: right; width: 120px;" name="item.AmountY0">#Html.DisplayFor(modelItem => item.AmountY0)</td> }
else
{
<td>#Html.TextBoxFor(modelItem => item.AmountY0, new { #id = y0_id, #class = class_parent, #style = "text-align: right; width: 120px;"})</td>
}
<td>#Html.TextBoxFor(modelItem => item.FinNote, new { #class = item.CssClassNote })</td>
<td><a id="js-modal-prompt" class="uk-button uk-button-default uk-button-small" style="line-height: 19px" href="#">+</a></td>
</tr>
Any hints, please?
This issue seems to be related to closures. You can fix it using:
var x = document.getElementsByName("item.AmountY0");
for (i = 1; i < (x.length - 3); i++) {
(function() {
var elm = document.getElementById("y0_" + x[i].className);
x[i].addEventListener("change", function(e) {
if (x[i].tagName == "TD") {
elm.innerHTML = String(parseInt(elm.innerHTML) + parseInt(x[i].innerHTML));
}
if (x[i].tagName == "INPUT") {
elm.innerHTML = String(parseInt(elm.innerHTML) + parseInt(x[i].value));
}
}, false);
}());
};
I want to do something like this within my view (razor)
if(index == #:{<script>{getPosition(#geResult.assessmentId);}</script>}){
geResult.ResultValue;
}
What will be the proper syntax?
Full HTML
<tr>
#{
var index = 4;
foreach(Assessment geAssessment in Model.assessments)
{
<td>
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
if(index == #:{<script>{getPosition(#geResult.assessmentId);}</script>} ){
geResult.ResultValue;
}
}
}
</td>
index++;
}
}
</tr>
UPDATE
I am trying the other way round now can anyone guide me please
SCRIPT
function getPosition(id, colIndex) {
var element = '#' + id;
$(this).closest('tr').find('td').eq(colIndex).html("A");
alert($(this).closest('tr').find('td').eq(colIndex).html());
return $(element).index();
}
HTML
<td>
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
<script>{ getPosition(#geResult.assessmentId, #index); }</script>
}
}
</td>
now the alert returns undefined although i am setting its value (text) just before!!
Finally, after wasting a whole 1.5 days i am able to solve this! hope it helps someone.
SCRIPT
function getPosition(id, colIndex, resultValue) {
var element = '#' + id;
var cell = $('.test').closest('tr').children('td').get(colIndex);
if($(element).index() == colIndex){
cell.innerHTML = resultValue;
}
}
HTML
<tr>
#{
var index = 4;
foreach(Assessment geAssessment in Model.assessments)
{
<td class="test">
#foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
if (geResult.ResultValue != null) {
<script>{ getPosition(#geResult.assessmentId, #index, '#geResult.ResultValue'); }</script>
}
}
}
</td>
index++;
}
}
</tr>
I have these functions:
$(".Read-Showing-Comment-Cancel").live('click', function (e) {
var guid = $(this).data("guid");
e.preventDefault();
var f = $('#comments-form-' + guid).slideUp();
$('comments-text-' + guid).empty();
$('comments-text-' + guid).value = "";
$(this).find('.comments-form-' + guid).hide();
$('comments-sendlink-' + guid).show();
});
$('.showComments').unbind('click').click(function (event) {
$('.ListingDisplayOptions').hide();
$(this).find('.comments-form-' + showGuid).show();
var showGuid = $(this).attr('rel');
loadShowingsComments(showGuid);
$(this).attr('id', 'comments-sendlink-' + showGuid);
event.preventDefault();
});
function loadShowingsComments(guid) {
var commentTextArea = "#comments-form-" + guid;
var commentDisplay = ".spanComments" + guid;
var curComment = $(commentDisplay).text();
var element = "#comments-form-" + guid;
$(element).slideDown();
}
<script>
function showComments() {
var comments = document.querySelectorAll(".spanComments");
for (var i = 0; i < comments.length; i++) {
comments[i].innerHTML = "This is comment #" + i;
}
}
</script>
View Comments
Those functions should grab the information from my controller (it's hooked up correctly. I've stepped through that and it has populated the right information) and place them in my span:
<tr class="p_la" id="comments-form-#currentShowing.ShowingGUID" style="display:none;">
<td colspan="4" style="border-right:5px solid #DDDDDD;">
<form action="" method="post">
<span class="spanComments" cols="100" rows="5">#string.Format("{0} / {1}", #currentShowing.Comments.DateAdded, #currentShowing.Comments.CommentsValue)</span>
<br />
Close
</form>
</td>
</tr>
Unfortunately, when I click on my hyperlink, it only populates the first span with the first span's information. Works great for the first span but when you click on the hyperlink in the second, third, fourth, etc item, they will only open up the first span with the first span's information.
The code should populate each successive span with its own information.
My JQuery was off. It needed this to be changed:
$(".Read-Showing-Comment-Cancel").live('click', function (e) {
var guid = $(this).data("guid");
e.preventDefault();
var f = $('#comments-form-' + guid).slideUp();
$('comments-text-' + guid).empty();
$('comments-text-' + guid).value = "";
$(this).parent("form").parent("td").parent("tr").hide();
$('comments-sendlink-' + guid).show();
});
$('.showComments').unbind('click').click(function (event) {
$('.ListingDisplayOptions').hide();
var showGuid = $(this).attr('rel');
$(this).parent("td").parent("tr").next('#comments-form-' + showGuid).show();
$(this).attr('id', 'comments-sendlink-' + showGuid);
event.preventDefault();
});
I have a table with some dynamic data, and columns as Name,Location, Salary. Problem i am facing in Step 2 i.e multiple condition check. Heres the step by step code.
JS Fiddle Demo
Step 1-
Auto generate Filters i.e dynamically add Checkboxes, depend on table row values
autoFilterItem("filterDiv");
Above function generate dynamic checkboxes, logic is it loop over table, read values row by row and return unique value array and generate checkbox respectively, currently am doing for 2 cols having class loc,sal.
Step 2-
Checkbox change event, depend on status (checked/unchekced) table rows will be hide/show .
The problem i am facing is, if user checked 100 ( class as sal), and Kerala ( class as loc) is unchecked then row having kerala should be hide.
For hide and show am adding/removing class .hideRow
///STEP TWO
// On any checkbox clicked returns desired out
$("body").on('change', '.chk', function () {
var arrObj = [],
arrCheckedValueCLass = [];
var objCheckedData = {};
$("#filterDiv .chk").each(function (index, val) {
var sf = $(this);
if (sf.is(":checked")) {
var sf = $(this);
arrObj.push({
dataValue: $(sf).attr('data-value'),
dataClass: $(sf).attr('data-class')
});
}
});
var self = $(this);
var getClassName = self.attr("data-class");
var matchTextValue = $.trim(self.attr("data-value"));
if (self.is(":checked")) {
if (matchTextValue == "All") {
$(".chk").prop('checked', true);
}
$("." + getClassName).each(function () {
var innerSelf = $(this);
var gVal = $.trim(innerSelf.html());
if (matchTextValue == "All") {
innerSelf.closest("tr").removeClass("hideRow");
} else {
if (matchTextValue === gVal) {
console.log("checked and matchTextValue");
var i = 0,
lg = arrObj.length;
var flagSet = false;
for (i; i < lg; ++i) {
var objValue = arrObj[i].dataValue;
var objClass = arrObj[i].dataClass;
if (getClassName != objClass) {
var prevDataCheck = $.trim(innerSelf.closest("tr").find("." + objClass).html());
if (prevDataCheck == objValue) {
flagSet = true;
return true;
}
}
}
if (!flagSet) {
innerSelf.closest("tr").removeClass("hideRow");
innerSelf.closest("tr").addClass(getClassName + "_X");
}
}
}
});
} else {
if (matchTextValue == "All") {
$(".chk").prop('checked', false);
}
$("." + getClassName).each(function () {
var innerSelf = $(this);
var gVal = $.trim(innerSelf.html());
if (matchTextValue === gVal) {
innerSelf.closest("tr").addClass("hideRow");
innerSelf.closest("tr").removeClass(getClassName + "_X");
}
});
}
});
<div id="filterDiv"></div>
<button>Click</button>
<br>
<div id="tableContainer">
<table id="myTable">
<thead>
<tr>
<th data-name='name'>Name</th>
<th data-loc='Location'>Location</th>
<th data-sal='salary'>Salary</th>
<th data-sts='Active'>Active</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">James</td>
<td class="loc">Mumbai</td>
<td class="sal">500</td>
<td class="sts">Yes</td>
</tr>
<tr>
<td class="name">Joseph</td>
<td class="loc">Kerala</td>
<td class="sal">100</td>
<td class="sts">No</td>
</tr>
<tr>
<td class="name">Jack</td>
<td class="loc">Delhi</td>
<td class="sal">500</td>
<td class="sts">Yes</td>
</tr>
<tr>
<td class="name">Andrea</td>
<td class="loc">Mumbai</td>
<td class="sal">1000</td>
<td class="sts">No</td>
</tr>
<tr>
<td class="name">David</td>
<td class="loc">Delhi</td>
<td class="sal">100</td>
<td class="sts">No</td>
</tr>
<tr>
<td class="name">David</td>
<td class="loc">Delhi</td>
<td class="sal">99900</td>
<td class="sts">No</td>
</tr>
</tbody>
</table>
</div>
I have created the fiddle from the things that you noted and able to produce the result( that is, if user checked 100 ( class as sal), and Kerala ( class as loc) is unchecked then row having kerala should be hide.)
I do not how efficient the solution is.There may be more efficient way to acheive that but anyway below is the js code.
$(document).ready(function () {
//STEP ONE STARTS
// This function generate checkbox from table data, which will be used for filteration
autoFilterItem("filterDiv");
function autoFilterItem(idOfHolderDiv) {
$("#" + idOfHolderDiv).empty();
var arr1 = [];
$(".sal").each(function () {
arr1.push($.trim($(this).html()));
});
var arrNew = unique(arr1).sort(function (a, b) {
return a - b
});
$.each(arrNew, function (i, val) {
$("<input/>", {
"type": "checkbox",
"class": "chk",
"data-class": "sal",
"data-value": val,
"id": "chk" + val,
"checked": "checked"
}).appendTo("#" + idOfHolderDiv).wrap("<div></div>").after(val);
});
$("#" + idOfHolderDiv).append("<hr>");
var arr2 = [];
$(".loc").each(function () {
arr2.push($.trim($(this).html()));
});
var arr2New = unique(arr2).sort();
$.each(arr2New, function (i, val) {
$("<input/>", {
"type": "checkbox",
"class": "chk",
"data-class": "loc",
"data-value": val,
"id": "chk" + val,
"checked": "checked"
}).appendTo("#" + idOfHolderDiv).wrap("<div></div>").after(val);
});
$("#" + idOfHolderDiv).append("<hr>");
function unique(array) {
return $.grep(array, function (el, index) {
return index == $.inArray(el, array);
});
}
}
// STEP ONE ENDS
///STEP TWO
// On any checkbox clicked returns desired out
var selectedSalaryArr = [];
var selectedLocationArr = [];
$("body").on('change', '.chk', function () {
var selectedVal = $(this).attr('data-value');
$('#filterDiv div').each(function () {
var checkedval = $(this).find('input.chk').attr('data-value');
var isChecked = $(this).find('input.chk').is(':checked');
var dataClass = $(this).find('input.chk').attr('data-class');
if (selectedVal === checkedval) {
if (dataClass === 'sal') {
var isExists = $.inArray(checkedval, selectedSalaryArr);
if (isExists === -1) {
selectedSalaryArr.push(checkedval);
} else {
selectedSalaryArr.splice($.inArray(checkedval, selectedSalaryArr), 1);
}
} else {
var isExists = $.inArray(checkedval, selectedLocationArr);
if (isExists === -1) {
selectedLocationArr.push(checkedval);
} else {
selectedLocationArr.splice($.inArray(checkedval, selectedLocationArr), 1);
}
}
}
});
$('#myTable tbody tr').each(function () {
var currentSalary = $(this).find('.sal').text();
var currentLocation = $(this).find('.loc').text();
var matchedSalaryValueExists = $.inArray(currentSalary, selectedSalaryArr);
var matchedLocationValueExists = $.inArray(currentLocation, selectedLocationArr);
if (selectedSalaryArr.length > 0 && selectedLocationArr.length > 0) {
if (matchedSalaryValueExists !== -1 && matchedLocationValueExists !== -1) {
if (!($(this).hasClass('hiderow'))) {
$(this).addClass('hiderow');
}
} else {
if ($(this).hasClass('hiderow')) {
$(this).removeClass('hiderow');
$(this).show();
}
}
}
else {
if (matchedSalaryValueExists !== -1 || matchedLocationValueExists !== -1) {
if (!($(this).hasClass('hiderow'))) {
$(this).addClass('hiderow');
}
} else {
if ($(this).hasClass('hiderow')) {
$(this).removeClass('hiderow');
$(this).show();
}
}
}
});
$('#myTable tbody tr.hiderow').hide();
});
});
Below is the jsfiddle link:
https://jsfiddle.net/shrawanlakhe/v8gyde77/
I've written this javascript to get the Id of a table then to loop through the tr's first then the td's. I am not sue what logic to write to get the selected value of the dropdown in a td. Not all tds, have a dropdown.
This is my javascript
function submitPanel(value) {
$('#' + value + '> tbody > tr').each(function () {
alert($(this).html());
$(this).find('td').each(function () {
alert($(this).html());
})
});
}
Which output this:
The table is made in MVC 4 razor
#model IMEModels.InterviewManagement.InterviewManagement
<hr />
#using (Html.BeginForm("SubmittedInterviews", "InterviewManagement", FormMethod.Post))
{
if (Model.InterviewSchedules.Count > 0)
{
<table>
<tr>
<td>#Html.Label("Show dates without Chair or Co-panelist") </td>
<td>#Html.RadioButton("Show dates without Chair or Co-panelist", new {Id = "rdoShow" })</td>
</tr>
</table>
for (int i = 0; i < Model.Centres.Count; i++)
{
#Html.Label(Model.Centres[i].CentreName)
for (int ii = 0; ii < Model.Centres[i].Locations.Count; ii++)
{
#Html.Label(Model.Centres[i].Locations[ii].LocationName)
for (int iii = 0; iii < Model.Centres[i].Locations[ii].InterviewDates.Count; iii++)
{
var ChairList = Model.Interviewers.Join(Model.DatePreferences, m => m.InterviewerId, d => d.InterviewersInterviewerId, (m, d) => new
{
Interviewer = m,
DatePreferences = d
})
.Where(d => d.DatePreferences.LocKey == Convert.ToString(Model.Centres[i].Locations[ii].LocationKey) && d.Interviewer.IsChair && d.DatePreferences.Date == Model.Centres[i].Locations[ii].InterviewDates[iii].Date)
.GroupBy(x => new { x.Interviewer.InterviewerId, x.Interviewer.Name })
.ToDictionary(a => a.Key.InterviewerId, b => b.Key.Name);
var NonChairList = Model.Interviewers.Join(Model.DatePreferences, m => m.InterviewerId, d => d.InterviewersInterviewerId, (m, d) => new
{
Interviewer = m,
DatePreferences = d
})
.Where(d => d.DatePreferences.LocKey == Convert.ToString(Model.Centres[i].Locations[ii].LocationKey) && d.DatePreferences.Date == Model.Centres[i].Locations[ii].InterviewDates[iii].Date)
.GroupBy(x => new { x.Interviewer.InterviewerId, x.Interviewer.Name })
.ToDictionary(a => a.Key.InterviewerId, b => b.Key.Name);
#:<div class="date-wrap #(ChairList.Count == 0 || NonChairList.Count == 0 ? "nochairspanelists" : "chairspanelists") >
if (NonChairList.Count == 0)
{
NonChairList.Add(new Guid(), "No panelists available.");
}
if (ChairList.Count == 0)
{
ChairList.Add(new Guid(), "No panelists available.");
}
#Html.Label(Model.Centres[i].Locations[ii].InterviewDates[iii].Date.ToLongDateString())
<table id="tbl#(Model.Centres[i].Code + "-" + Model.Centres[i].Locations[ii].LocationKey + "-" + Model.Centres[i].Locations[ii].InterviewDates[iii].Date.Ticks)" class="tblInterviewManager">
<tr>
<td>
Chair
</td>
<td>
Co-panelist
</td>
<td></td>
</tr>
<tr>
<td>
#Html.DropDownListFor(m => m.InterviewSchedules[iii].ChairId, new SelectList(ChairList, "Key", "Value"))
<br />
</td>
<td>
#Html.DropDownListFor(m => m.InterviewSchedules[iii].CofacilitatorId, new SelectList(NonChairList, "Key", "Value"))
</td>
#if (ChairList.ElementAt(0).Value == "No panelists available." || NonChairList.ElementAt(0).Value == "No panelists available.")
{
<td>
<input type="submit" value="Save panel" disabled="disabled" />
</td>
}
else
{
<td>
<input type="button" value="Save panel" id="btnSubmit" onclick="return submitPanel('tbl#(Model.Centres[i].Code + "-" + Model.Centres[i].Locations[ii].LocationKey + "-" + Model.Centres[i].Locations[ii].InterviewDates[iii].Date.Ticks)');"/>
</td>
}
</tr>
</table>
#:</div>
}
}
<br />
}
<div class="clear"></div>
<hr />
}
}
Anyone know a good way to get the values I want.
Use Descendant Selector (“ancestor descendant”) to directly get the selects within the table.
function submitPanel(value) {
$('#' + value + ' select').each(function () {
alert($(this).val());
});
}
Selects all elements that are descendants of a given ancestor, A
descendant of an element could be a child, grandchild,
great-grandchild, and so on, of that element, jQuery docs.