I have some table & i need to calculate Column values.In my scenario i need to calculate Total Item Price 99 + 55 = 154 to Sub Total Row.In here my SubTotal Calculation not working.
My Code(part of my Table Creation)
$option.each(function () {
if ($(this).prop('selected')) {
var txtId = 'txtQty' + i;
var lblId = 'lblQty' + i;
var row = $('<tr><td>' + $(this).text() + '</td><td>' + $(this).attr('RetailPrice') + '</td><td>' + $(this).attr('WholesalePrice') + '</td><td>' + '<input type="text" id="' + txtId + '">' + '</td><td> <button type="button" class="btn btn-warning btn-xs btncalc">Calculate</button></td><td class="tot"><label for="tempprice" id="' + lblId + '"></label></td><td><img id="imgdel" src="../../Images/delete.png" alt="" onclick="deleteclick(this)" title="Delete" /></td></tr>');
table.append(row);
i++;
}
});
var row2 = $('<tr><td>' + "SubTotal" + '</td><td></td><td></td><td></td><td></td></tr>');
table.append(row2);
$('#product-load-tbl').append(table);
});
Calculation Part
$('.btncalc').live('click', function () {
debugger;
var row = $(this).parents("tr:first");
var rowval = $(row).find("td:eq(1)").html();
var inpval = $(row).find("td:eq(3) input").val();
if (inpval != null || inpval != 0) {
var result = (rowval * inpval);
}
else {
var result = 0;
}
$(row).find("td:eq(5)").html(result);
var lstrow = $(this).parents("tr:last"); // this sub total calculation not working
$.each($('.tot'), function (element) {
$(lastrow).find("td:eq(5)").html(element);
});
})
You can change this:
$.each($('.tot'), function (element) {
$(lastrow).find("td:eq(5)").html(element);
});
to this:
var total = 0; // intialise a var with value 0
$('.tot').each(function (i, element) { // loop the selected item in each row
total += +$(this).text(); // cast the string to integer and add it to total
});
$(lastrow).find("td:eq(5)").text(total); // then at last place the total
Short demo
And for a short note:
.live() is now removed from the latest jQuery versions, so if you are using version 1.7+ then you can move your code to .on() method to delegate the event. Syntax is something like this for event delegation:
$(static_parent).on(event, selector, callback);
$(static_parent) is the element which was available when the relative dom is ready and it was available at that time before appending any dynamic dom element in the page.
so in your case:
$('table_ID/Class').on('click', '.btncalc', function(){
//...all the stuff with .live goes here
});
Related
Am using an editable HTML datatable on my asp.net web page .Which look like this,
How to add validation on column Target, to receive only float values.?
Function (For enable edit):
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
jqTds[0].innerHTML = aData[0];
jqTds[1].innerHTML = aData[1];
jqTds[2].innerHTML = '<input type="text" id="Float" class="form-control" value="' + aData[2] + '">';
jqTds[3].innerHTML = '<a class="save-row" href="">Save</a>';
jqTds[4].innerHTML = '<a class="cancel-row" href="">Cancel</a>';
}
I tried to add keypress event on the textbox , but its not working.!
$('#Float').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && (event.which != 8)) {
event.preventDefault();
}
});
Am new to jquery so please help me solve this ?
Try:
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
Note: Above code doesn't work for -ve values.
I am working on online Q/A system,i have to show countdown for each candidate like 3 min,on expiring user will be redirect to Result.aspx page.
I am facing following
1.how to set counter for each candidate.
2.on page refresh counter set to default value.
i have following code
<div id="timer">
</div>
<script type="text/javascript">
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
if (getCookie("minutes") && getCookie("seconds")) {
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes", mins, 10)
setCookie("seconds", seconds, 10)
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
//minutesSpan.innerHTML = current_minutes.toString();
//secondsSpan.innerHTML = (seconds < 10 ? "0" : "") + String(seconds);
if (seconds > 0) {
setTimeout(tick, 1000);
}
else {
if (mins > 1) {
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
countdown(3);
</script>
because multiple user will doing these test so i have handle each one differently,i have following code to assign to assign test for each candidate
private void NewCandidate()
{
var ClistCount = (from cl in ef.Candidate_Table where cl.Name == btnname.Text && cl.Status_Id==2 select cl).FirstOrDefault();
if (ClistCount != null)
{
string cnic = ClistCount.Cnic;
Session["token"] = cnic;
Response.Redirect("MainTestForm.aspx?id=" + cnic);
}
else
{
MsgLitteral.ShowNotification("No Candidate Is Here", true);
btnbrowse.Visible = false;
btnname.Visible = false;
}
}
There are two things which you need to do in order to make things working
1) Create perfectly working count down timer method
2) Solve the reload dependency
for reload thing just before reload/refresh, trigger a function that would store the current time elapsed from the predefined count down.
$(window).bind('beforeunload', function(){
//below function stores current elapsed time in cookie/local storage
callFunction();
return true;
});
for e.g if 3min countdown is set and the user refreshes or moves to
next question at 2min 40 secs then store 2min 40 sec in cookies or
html5 local storage
On every document ready event check the cookie value
if value present then
take this value and set countdown
else
with predefined value (for the first time case)
A simple countdown timer for reference
Hopefully someone can help. I have a list of objects that i get from the DB.
I would like to on load, only add the first ten in the list to a CheckBoxlist. Then with the Next_click I would like to add the next ten and so on. If the user clicks Prev, I would like to add the previous 10. So essentially it is paging through a CheckBoxlist.
This is how i have tried it and didn't succeed, it doesn't throw any errors. Just doesn't do what i want it to do. I hope its possible.
On page load these are declared:
QuestionHandler quest = null;
protected List<QuestionView> questions = null;
int countP1 = 0;
int countP2 = 10;
This is the binddata method:
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
List<string> display = new List<string>();
int c = 0;
foreach (QuestionView qsD in questions)
{
if (countP1.ToString().All(char.IsDigit) && countP2.ToString().All(char.IsDigit))
{
if (c >= countP1 && c <= countP2)
{
display.Add(qsD.QuestionID.ToString());
}
c++;
}
}
questions = null;
questions = new List<QuestionView>();
foreach(string s in display)
{
QuestionView q = new QuestionView();
q = quest.GetSelectQ(s);
questions.Add(q);
}
Then to add it to the checkboxlist(dont worry about the long string, its a premade table):
foreach (QuestionView qs in questions)
{
ListItem item1 = new ListItem();
item1.Text = "<table class=\"table\" style=\"border: 3px solid #8AC007;\"><tr><td>Title: </td><td width=\"300px\">" + qs.Title + "</td><td>|</td><td>Marks: </td><td width=\"300px\">" + qs.Mark + "</td><td>|</td><td>Type: </td><td width=\"300px\">" + qs.TypeID + "</td></tr><tr><td>Subject:</td><td>" + qs.SubjectID + "</td><td>|</td><td>Topic: </td><td>" + qs.TopicID + "</td><td>|</td><td>Rating: </td><td></td></tr></table>";
item1.Value = qs.QuestionID.ToString();
CheckBoxList1.Items.Add(item1);
}
The next click:
protected void btnNext_Click(object sender, EventArgs e)
{
countP1 = countP1 + 10;
countP2 = countP2 + 10;
BindData();
}
The prev click:
protected void btnPrev_Click(object sender, EventArgs e)
{
countP1 = countP1 - 10;
countP2 = countP2 - 10;
BindData();
}
Hopefully someone understands what i mean and can help, thank you in advance, feel free to ask me questions about this if you need to.
This is all in an update-panel.
Finally, this is how the checkboxlist looks when displayed:
You can use LINQ and the methods Take and Skip
const int size = 10; // How many questions you want to be returned.
public IEnumerable<QuestionView> GetQuestions(int page)
{
return questions.Skip(size * page).Take(size);
}
This will look at your QuestionView list, skip over 10 records * the page count, and then take the next 10 elements.
You may want to add some additional logic to ensure that the next set of elements requested does not exceed the QuestionView list limit.
From your comments:
For simplicity, you can put the method inside the class you're working with and can invoke it in the DataBinding method (Where you have the following code):
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
var pagedQuestions = GetQuestions(1); // Make use of the new method.
For best practice, you should separate this out and put it somewhere that is related to the QuestionView. You could also put it as an extension to Question View (Extension method).
After the help from Darren this is the final code to make it work:
The bind data method to load up the page:
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
int count = 0;
foreach (QuestionView qs in questions)
{
if(count<10) //stop it from displaying more than 10 on the first page
{
ListItem item1 = new ListItem();
item1.Text = "<table class=\"table\" style=\"border: 3px solid #8AC007;\"><tr><td>Title: </td><td width=\"300px\">" + qs.Title + "</td><td>|</td><td>Marks: </td><td width=\"300px\">" + qs.Mark + "</td><td>|</td><td>Type: </td><td width=\"300px\">" + qs.TypeID + "</td></tr><tr><td>Subject:</td><td>" + qs.SubjectID + "</td><td>|</td><td>Topic: </td><td>" + qs.TopicID + "</td><td>|</td><td>Rating: </td><td></td></tr></table>";
item1.Value = qs.QuestionID.ToString();
CheckBoxList1.Items.Add(item1);
}
count++;
}
The next click:
countP1++;
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
var pagedQuestions = GetQuestions(countP1);
foreach (QuestionView qs in pagedQuestions)
{
ListItem item1 = new ListItem();
item1.Text = "<table class=\"table\" style=\"border: 3px solid #8AC007;\"><tr><td>Title: </td><td width=\"300px\">" + qs.Title + "</td><td>|</td><td>Marks: </td><td width=\"300px\">" + qs.Mark + "</td><td>|</td><td>Type: </td><td width=\"300px\">" + qs.TypeID + "</td></tr><tr><td>Subject:</td><td>" + qs.SubjectID + "</td><td>|</td><td>Topic: </td><td>" + qs.TopicID + "</td><td>|</td><td>Rating: </td><td></td></tr></table>";
item1.Value = qs.QuestionID.ToString();
CheckBoxList1.Items.Add(item1);
}
The prev click:
countP1--;
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
var pagedQuestions = GetQuestions(countP1);
foreach (QuestionView qs in pagedQuestions)
{
ListItem item1 = new ListItem();
item1.Text = "<table class=\"table\" style=\"border: 3px solid #8AC007;\"><tr><td>Title: </td><td width=\"300px\">" + qs.Title + "</td><td>|</td><td>Marks: </td><td width=\"300px\">" + qs.Mark + "</td><td>|</td><td>Type: </td><td width=\"300px\">" + qs.TypeID + "</td></tr><tr><td>Subject:</td><td>" + qs.SubjectID + "</td><td>|</td><td>Topic: </td><td>" + qs.TopicID + "</td><td>|</td><td>Rating: </td><td></td></tr></table>";
item1.Value = qs.QuestionID.ToString();
CheckBoxList1.Items.Add(item1);
}
The count variable is initiated as 0 when the page loads.
I'm trying to display a bunch of divs that are rendered to look like vertical and horizontal lines. While the code technically works, it doesn't work consistently. On the first page load, only one line may show, and on the next an entirely different one may show, or they'll all show. I'm testing this on IE8 and IE9 with the same problem, and am a bit lost at this point.
I'm using ScriptManager.RegisterStartupScript(this, GetType(), "linesCode", script, false); to register the script, but it does the same thing using the old RegisterStartupScript(key, string) method.
Code that is being registered, pulled from the browsers' "View Source":
<script type="text/javascript">
$(document).ready(function () {
drawLineVertical('MainContent_1_ClauseRowDefaultTable', 'MainContent_3_AddRowTable', 2, 30);
drawLineHorizontal('MainContent_1_ClauseRowDefaultTable', 'MainContent_2_ConditionRowTable', 2, 40);
drawLineHorizontal('MainContent_1_ClauseRowDefaultTable', 'MainContent_3_AddRowTable', 2, 30);
});
</script>
Code that is being processed (most of this was found in an old blog post):
function drawLineVertical(id1, id2, wid, offset) {
var obj1 = document.getElementById(id1);
var obj2 = document.getElementById(id2);
var obj1Pos = GetCoordinates(obj1);
var obj2Pos = GetCoordinates(obj2);
var id = 'line_' + new Date().getTime();
var line = "<div id=\"" + id + "\" class=\"line\"></div>";
$('body').append(line);
$('#' + id).css({
left: obj1Pos.x,
top: obj1Pos.y,
height: ((obj2Pos.y - obj1Pos.y) + offset),
width: wid,
position: 'absolute',
background: '#c2c5d1',
backgroundcolor: '#c2c5d1'
});
}
function drawLineHorizontal(id1, id2, h, offset) {
var obj1 = document.getElementById(id1);
var obj2 = document.getElementById(id2);
var obj1Pos = GetCoordinates(obj1);
var obj2Pos = GetCoordinates(obj2);
var id = 'line_' + new Date().getTime();
var line = "<div id=\"" + id + "\" class=\"line\"></div>";
$('body').append(line);
$('#' + id).css({
left: obj1Pos.x,
top: (obj2Pos.y + offset),
height: h,
width: obj2Pos.x - obj1Pos.x,
position: 'absolute',
background: '#c2c5d1',
backgroundcolor: '#c2c5d1'
});
}
function GetCoordinates(obj) {
var pos = {};
pos.x = obj.offsetLeft;
pos.y = obj.offsetTop;
while (obj.offsetParent) {
pos.x = pos.x + obj.offsetParent.offsetLeft;
pos.y = pos.y + obj.offsetParent.offsetTop;
if (obj == document.getElementsByTagName("body")[0]) {
break;
}
else {
obj = obj.offsetParent;
}
}
return pos;
}
Any input is greatly appreciated.
I'm trying to do this and it is a bit confusing for me.
Basically the scenario is like this, I'm getting an XML from a 3rd party application with available dates for booking, for each day there are types of rooms the person can choose, single, double, etc.
Each hostel will return me an unknown number of room types. But dont get too confused with this.
The thing is simple I just need to add an unknown number of dropdownlists (or HTML Select) with the numbers of persons to book for. Now because I don't know how many of those dropdowns I will have I need to add them programatically inside a "for int i=0; i
How can I add an unknownn number of dropdownlists programatically to a page and retrieve the selected values with c# on submit?
The last column on the screenshot
http://i.stack.imgur.com/37chw.png
Update:
I'm creating the code from the xml results as a string that will print as html code:
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc.LoadXml(getPrices());
XmlNodeList prices = xmlDoc.GetElementsByTagName("RoomType");
string[] bookingDates = new string[Convert.ToInt32(Request.QueryString["nights"])];
string[] bookingDays = new string[Convert.ToInt32(Request.QueryString["nights"])];
bookingDates[0] = Request.QueryString["date"].ToString();
string[] dateArray = Request.QueryString["date"].ToString().Split('-');
DateTime initialDate = new DateTime(Convert.ToInt32(dateArray[0]), Convert.ToInt32(dateArray[1]), Convert.ToInt32(dateArray[2]));
bookingDays[0] = initialDate.DayOfWeek.ToString();
for (int z = 1; z < bookingDates.Length; z++)
{
DateTime nextDay = initialDate.AddDays(z);
string month = nextDay.Month.ToString();
string day = nextDay.Day.ToString();
if (day.Length == 1)
{
day = "0" + day;
}
if (month.Length == 1)
{
month = "0" + month;
}
bookingDates[z] = nextDay.Year + "-" + month + "-" + day;
bookingDays[z] = nextDay.DayOfWeek.ToString();
}
string pricesHeader = "<table width='100%'>";
pricesHeader += "<tr><td>Room Type</td>";
for (int x = 0; x < bookingDates.Length; x++)
{
string[] bookingDay = bookingDates[x].Split('-');
pricesHeader += "<td align='center'>" + bookingDays[x].Substring(0, 3) + "<br>" + bookingDay[2] + "</td>";
}
pricesHeader += "<td>Persons</td></tr>";
string pricesContent = "<tr>";
int dropNumber = 1;
foreach (XmlElement node in prices)
{
XmlNodeList roomTypeDescriptionN = node.GetElementsByTagName("roomTypeDescription");
string roomTypeDescriptionS = roomTypeDescriptionN[0].InnerText;
pricesContent += "<td>" + roomTypeDescriptionS + "</td>";
XmlNodeList priceN = node.GetElementsByTagName("price");
string priceS = priceN[0].InnerText;
XmlNodeList currencyN = node.GetElementsByTagName("currency");
string currencyS = currencyN[0].InnerText;
if (currencyS == "EUR")
{
currencyS = "&euro";
}
string avDates = "";
XmlNodeList availableDatesN = node.GetElementsByTagName("date");
int dateNumber = 0;
foreach (XmlElement avDate in availableDatesN)
{
avDates += availableDatesN[dateNumber].InnerText + ",";
dateNumber++;
}
for (int c = 0; c < bookingDates.Length; c++)
{
if (avDates.Contains(bookingDates[c]))
{
pricesContent += "<td>" + priceS + currencyS + "</td>";
}
else
{
pricesContent += "<td><center>X</center></td>";
}
}
pricesContent += "<td><select runat=server name='pers" + dropNumber + "' id='pers" + dropNumber + "'>" +
"<option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option></select></td></tr>";
dropNumber++;
}
pricesLabel.Text = pricesHeader + pricesContent + "</table>";
I know that doing that and adding the runat=server won't help on my control, there is where my main problem is now, how to add the code on the html to be able to get the dropdownlist selected value later with c#. Can I do that with Request.Form ? was trying but so far I couldnt do it.
You can use the Repeater Class for generation of controls
You can also use the Request.Form Collection for obtaining of user's choice
You can use List for saving your created dropdownlists. On submit, you can read the data from your list.
List<DropDownList> ddlList = new List<DropDownList>{};
for(int i=0;i<count;i++)
{
//add control to page
ddlList.items.add(YourNewlyCreatedDdl);
}
for (int i = 0; i < 5; i++)
{
DropDownList ddl = new DropDownList();
ddl.ID=string.Format("ddl_{0}",i);
this.form1.Controls.Add(ddl);
}
This creates 5 empty DropDownLists.
You will need to rebuild and repopulate the controls on each postback in order for ASP to recognise their values.