I have written one JavaScript to Calculate the TotalWeight based on two TextBox integer values. I multiplied these two values and displayed in the 3rd TextBox Using JavaScript. But the problem is, I have one radiobuttonlist, in its selectedindexchanged event, the value I got in the 3rd TextBox gets disappeared. How to solve this?
My JavaScript is
<script type="text/javascript">
function TotalWeight()
{
var D1 = document.getElementById('<%=txtD1.ClientID%>');
var SectionWgt = document.getElementById('<%=txtSectionWeight.ClientID%>');
var TotalWgt = 0*1;
TotalWgt = parseFloat(D1.value) * parseFloat(SectionWgt.value);
if(isNaN(TotalWgt))
document.getElementById('<%=txtTotalWgt.ClientID%>').innerText = "0.000";
else
document.getElementById('<%=txtTotalWgt.ClientID%>').innerText = TotalWgt.toFixed(3);
}
</script>
<asp:TextBox ID="txtD1" runat="server" Width="136px" onkeyup="return TotalWeight();"></asp:TextBox>
After you calculate and assign the value to your Total Textbox, then put that value in a hidden field as well, and then on postback reassign that value to the textbox from the hidden Field.
Read the value of the textbox in when the radio button event fires and posts back - and then write it back to the textbox afterwards.
I would imagine that when the event fires and the page posts back, the third text box reverts to its original value - capture the new value and write it back to the box during the event.
use hidden field to store values. just use
[intput type="hidden" id="someid">]
after that you can use the value using $("#someid").val()
Try, this helped me.
Related
I have a gridview looks like below.
Name Attended_Exam
Raj English
Hindi
Das Korea
Rahul Spanish
English
And the query used to bind datatable to this gridview contains a submission_id. Which is unique for each student and his subject.
Each attended exam name is shown as a linkbutton. Now, when clicking on it, I want to get the Submission_id of each subject. What is the best way to achieve this?
<asp:GridView ID="gvSubmissionHeaders" runat="server" AutoGenerateColumns="true"
Width="80%" OnRowDataBound="gvSubmissionHeaders_RowDataBound"
Font-Bold="false" RowStyle-Height="30px" >
</asp:GridView>
protected void gvSubmissionHeaders_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ //for adding linkbutton to Attended_Exam
//loop through the cell.
for (int j=1;j< e.Row.Cells.Count;j++)
string[] arrLinks =null;
if (!string.IsNullOrEmpty(e.Row.Cells[j].Text.ToString()) && e.Row.Cells[j].Text.ToString()!= " ")
{
arrLinks = e.Row.Cells[j].Text.Split(',');
}
if(arrLinks!=null)
{
for (int i = 0; i < arrLinks.Length; i++)
{
LinkButton btnLink = new LinkButton();
btnLink.ID = "Id" + arrLinks[i] + i;
btnLink.Text = arrLinks[i] + "<br>";
e.Row.Cells[j].Controls.Add(btnLink);
}
}
}
Ok, the detail here is that you could have simply noted that you have cell/colum in the grid, and you might add 1 or maybe 4 link buttons into that cell. So you have "N" buttons that you add, and you need/want particular information from that button.
If the button was static (a single link button), then you can add custom attributes to that button, and even additional columns data (ones not displayed in the grid) like this:
<td align="center" >
<asp:LinkButton ID="pUploadFiles" runat="server"
CommandArgument='<%# Eval("ID")%>' CommandName='cmdView'
Width="120px" align="center"
ContactNameID = '<%# Eval("ContactNameID")%>'
QuoteNum = '<%# Eval("QuoteNum")%>'
ProjectHeaderID = '<%# Eval("ID")%>'
>
</asp:LinkButton>
</td>
So now when you get the sender, or do a findcontrol, you can do this in code:
Dim btn As LinkButton ' we get required data from btn on row.
btn = lvd.FindControl("pUploadFiles")
With btn.Attributes
Session("ContactID") = .Item("ContactNameID")
Session("ContactGeneralID") = .Item("ContactGeneralID")
Session("QuoteNum") = .Item("QuoteNum")
End With
So linkbtn.Attributes.Item("my custom value") will get you any extra values (columns) that you attached to that link button. And with the above eval(), you can even pull any column from the data source as long as those column exist in the datatable/datasource that drives the listview or gridview. (the great part here is that you don't need actual columns in the gridview/listview to try and store and "hide" these values. The extra values are simply part of that given control as custom attributes.
Now you are adding the link btn in code, but you can do the same thing.
eg:
LinkButton btnLink = new LinkButton();
btnLink.ID = "Id" + arrLinks[i] + i;
btnLink.Text = arrLinks[i] + "<br>";
btnLink.Attributes.Add("Submission_id","100");
e.Row.Cells[j].Controls.Add(btnLink);
Now of course you would replace the hard coded "100" in above with the value you are pulling or want to store as a custom attribute. So you can add 1 or "many" custom attributes to that link button. When the click on that link button, then you grab/get the additional attributes that are associated with that link button by using Mybtn.Attributes.Item("Submission_id").
So be it one link button that is part of the grid, you can add those extra attributes (without even extra code), and even rows from the databind that are not in the grid.
So I can have several buttons, and when they click, then additional information such as PK row, or even several other values can be part of (or added) to that one button. And in your case this should work fine if you dynamic adding 1 or 5 buttons as you are. So, those additonal values you want can simply become additonal attributes of that button.
Edit:
Ok, the problem is that controls that require events that are created "after" the page has been rendered cannot really be wired up. You would have to move the code to a earlier event. So you are free to add controls, but they will in "most" cases be rendered TOO LATE to have events attached. Thus when you click on the link button, nothing fires.
So there are two solutions I can think of that will work.
First, set the control to have a a post back URL, and include a parameter on that post back.
eg this:
Dim lnkBtn As New LinkButton
lnkBtn.Text = "<br/>L" & I
lnkBtn.ID = "cL" & I
lnkBtn.PostBackUrl = "~/GridTest.aspx?r=" & bv.RowIndex
If you put a PostbackUrl, then when you click on the button, the page will post back. However, the grid row events such as rowindex change, or row click event etc. will NOT fire. So, if you willing to have a parameter passed back to the same page as per above, then you can pass the 1-3 (or 1-N) values you have for each control.
Of course that means you now have a parameter on the web page URL (and users will see this). You of course simply pick up the parameter value on page load with the standard
Request.QueryString["ID"] or whatever.
However, another way - which I think is better is to simple wire up a OnClickClick() event in js, and thus do this:
I = 1 to N
Dim lnkBtn As New LinkButton
lnkBtn.Text = "<br/>L" & I
lnkBtn.ID = "cL" & I
lnkBtn.OnClientClick = "mycellclick(" & I & ");return false;"
Now in above note how I am passing "I" to the js routine. You would pass your 200, 300 or whatever value you want.
then you script will look like this:
<script>
function mycellclick(e) {
__doPostBack("MySelect", e);
}
</script>
So above simply takes the value passed from the cell click (and linkbutn), and then does the postback with a dopostback. I used "MySelect", and you can give that any name you want.
Now, in the on-load event, you can simply go like this:
If Request("__EVENTTARGET") = "MySelect" Then
Dim mypassvalue As String = Request("__EVENTARGUMENT").ToString
Debug.Print("row sel for MySelect = " & mypassvalue)
End If
So, you are 100% correct - clicking on those controls does NOT fire server side event, and they are wired up too late for this to occur. so you can and often do say add some columns or controls to a gridview, but they are created and rendered TOO LATE for the events to be wired up (and thus they don't fire when clicked on).
But, you can add a postback to the lnkbutton, and you can also add a OnClickClick() event (JavaScript function call) and they will both work. I don't like parameters in the URL appearing when you click, so I think the js script call as per above works rather nice.
So while in the comments I noted (and suggested) that you have to set the CommandName="Select". This suggesting still holds true (without CommandName = select, then the rowindex will not fire. You can't use just ANY name - it MUST be select. However this ONLY works if the control is part of the grid and not added on the fly. As noted, it might be possible to move the grid event to "earlier" event (page initialize) but it going to be a challenge and will require you to re-organize the page. The most clean, and one that does not require parameters in the URL is adding that js OnClientClick() event. You can however set the controls postbackurl and along with a parameter in the URL, and that also can work well if you open to URL with parameters (I don't like them).
First you declare your table column ID on the DataKeyNames on GridView eg:
<asp:GridView DataKeyNames="cTableColumnID" ID="gvSubmissionHeaders" runat="server" ...
Then you can get this ID per Row using this line
gvSubmissionHeaders.DataKeys[CurrectRowNum]["cTableColumnID"]
I have a WebForm ASP label and button. I am setting the label's value on page load. For example, the label text on page load is 2 items selected. This comes from the database. Then if the user changes the selection then it counts the selected values by jQuery and sets the text as 5 items selected.
When I click on the submit button to save changes, again it resets to 2 items selected. I didn't use an update panel. I don't know what is going on here. Can anyone please explain this scenario?
$("#lblCount").text($('#grdProducts').find('input#chkSelect:checked').length + ' Complementary Products added');
C# on page load:
lblCount.Text = ComplementaryproductCount.ToString() + " Complementary Products added";
I do not understand why the label text is changed on button click. I couldn't find anything while debugging too.
Thanks
When you set lblCount.Text in your code, that value is set into the ViewState of the page... that means when your page is posted back to the server (to handle an event, etc) ASP.Net knows what lblCount.Text was originally and can re-render the HTML with the same value.
As part of that post-back to the server, the browser will send back that ViewState along with any input control values (things like textboxes, dropdowns, hidden field).
What it does NOT do is post-back any changes you might have made to the elements on the page via things like jQuery (other than input controls I mentioned above).
The result is that although you've changed the element on the screen, the server knows absolutely nothing about that change, and it will re-send the original HTML for the label back to the browser.
Your only option is to do something as suggested by #John in his comment... you need to store the fact the element has changed in an input, and then use that.
For instance...
<asp:Label runat="server" id="lblCount" />
<asp:HiddenField runat="server" id="hdnCount" />
function updateCount(newCount) {
$("#<%=lblCount.ClientID%>").text("Count: " + newCount.toString());
$("#<%=hdnCount.ClientID%>").val(newCount.toString());
}
Then in your code-behind you can have...
if (!Page.IsPostBack)
{
var count = 1;
lblCount.Text = String.Format("Count: {0}", count);
hdnCount.Value = count.ToString();
}
else
{
lblCount.Text = String.Format("Count: {0}", hdnCount.Value);
}
I want to know what is the best way to assign a value to textbox 2 instantly as the user write this value in textbox 1 ie. Directly showing what the user is entering in textbox1 also in textbox2 at the same. I'm using MVC5 aspx pages..
Any help is highly appreciated. Thanks in advance
Add a onkeyup event listener to your first element(Whenever a key is pressed, the value in first textbox is also entered in second.). Then call the function like
function enterAmt(ev) {
document.getElementById('amt2').value = ev.value;
}
You have to use javascript or jquery for it, suppose you have two textboxes.
HTML:
<input type="text" id="txtBox1"/>
<input type="text" id="txtBox2"/>
You have to write keyup event for the textbox and copy its value in second.
JQUERY:
$("#txtBox1").on('keyup', function () {
$("#txtBox2").val($(this).val())
})
Here you can find the solution to the absolutely same question: Textbox onchange in ASP.NET
I have a ASP.NET 4.5 Page which has a dynamically created list of text boxes
I have set the default button for the asp.panel to be the Save button.
If the user is half way through filling out the text boxes and hits the enter key, the form saves, but then sets the focus back at the top of the page. How can I have it set the focus back on the last text box that was being edited?
You can add onfocus handler to all form elements via javascript/jquery which will save the id of the currently focused control to hidden field and read that id value when with javascript on document load so you can set focus on the right control.
Example:
<asp:HiddenField runat="server" ID="hfFocusedControl" />
<script>
$(document).ready(function(){
var id = $('#hfFocusedControl').val()
;
$('#'+id).focus();
$('input').focus(saveIdOnFocus);
});
var saveIdOnFocus = function(e){
var control = $(this)
, id = control.attr('id')
;
$('#hfFocusedControl').val(id);
}
</script>
Java Script
function outputtax()
{
var tamount = parseFloat(document.getElementById('<%=txtpsubtotal.ClientID%>').value);
var cash = parseFloat(document.getElementById('<%=txtpdiscount.ClientID%>').value);
if (isNaN(tamount) != true && isNaN(cash) != true && isNaN(tax) != true)
{
document.getElementById('<%=txtPtotalamout.ClientID%>').value =
Math.round(parseFloat(document.getElementById('<%=txtpsubtotal.ClientID%>').value)
- parseFloat(document.getElementById('<%=txtpdiscount.ClientID%>').value))
return false;
}
}
<asp:TextBox ID="txtPtotalamout" runat="server" ReadOnly="true">
</asp:TextBox>
.CS
objsupplyPL.totalamount = Convert.ToDouble(txtPtotalamout.Text.ToString());
Value is displaying on the textbox but when i click save button txtptotalamount is getting
null value.If I placed readonly="false" it's working fine.
From http://codecorner.galanter.net/2009/10/09/postback-disabled-textbox/
Let’s say in your ASP.NET application you set a TextBox control’s property ReadOnly to True (or Enabled to False) to prevent user from entering data directly. But you still want to update that text box’s value via client-side JavaScript. Which is happening, the value can be updated. But during postback to the server – surprise, surprise! – the new value doesn’t persist. This is due to security precaution – if the value wasn’t meant to be changed – the change is not allowed. But there is a way around this.
The trick is - to keep ReadOnly = False and Enabled = True and simulate their behavior. Add following line of to your server-side code:
TextBox1.Attributes["onclick"] = "this.blur();"
where TextBox1 is your textbox control. What this line does is adds client-side behavior to the textbox. As soon as user tries to click the textbox, focus immediately gets lost, preventing user from entering data, making the textbox essentially read-only. For further effect you can set the texbox’s background to something like “LightGray” making it appear disabled.
You want to be able to save the result from the "txtPtotalamout" but you don't want it to be editable.
You could just use
<div id="PTotalAmount"><asp:Label id="PTotalAmount" runat="server" /></div>
<asp:HiddenField ID="hPTotalAmount" runat="server" />
To display it, and update the contents of that DIV and the hidden field in the javascript.
Then you could display the total amount in that DIV when you load the form (and populate the hidden field). You could even format the DIV to look like a text box if you wanted.