I have this htmlInput in an ASP:Repeater that I want to be formatted in time format (e.g: 13:39) on its keypress. So far I have this code in repeater databound:
Protected Sub rpt_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rpt.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim txt As HtmlInputText = DirectCast(e.Item.FindControl("txtKmRun"), HtmlInputText)
If txt IsNot Nothing Then
txt.Attributes.Add("onkeypress", "return kmRun('" & txt.Value & "');")
End If
End If
End Sub
..and this is in the JavaScript:
<script>
function kmRun(myValue) {
String x = myValue;
x = x.substring(0, 2) + ":" + x.substring(2, x.length());
alert(x); //alert to test display but is not working
//HOW TO PASS x VALUE TO BACK TO THE TEXTBOX?
}
</script>
Tested the onkeypress attribute with a simple javascriptalert message and it worked but when modified with value passing, there's no return value. So I guess, the error starts there.
Additional question is when the javascriptpart works, how to return the "converted" string value back to the htmlInput? Is there any other solution for this problem that will not use a PostBack?
Thanks.
===================
This is the working code:
Protected Sub rpt_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rpt.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim txt As HtmlInputText = DirectCast(e.Item.FindControl("txtKmRun"), HtmlInputText)
If txt IsNot Nothing Then
txt.Attributes.Add("onkeypress", "return kmRun(this);")
End If
End If
End Sub
<script>
function kmRun(x) {
if (x.value.length > 2) {
x.value = x.value.substring(0, 2) + ":" + x.value.substring(2, x.value.length);
}
}
</script>
You don't need to declare another variable, you can use the myValue parameter.
I'd recommend to use onchange="kmRun(this)" instead onkeypress="kmRun(this)", because you got to change the content, to finally be formatted by the code.
By using this, you can get all attributes of the textBox control.
You might try something like this, in your javascript code:
function kmRun(control) {
control.value = control.value.substring(0, 2) + ":" + control.value.substring(2, control.value.length);
}
<input id="txt" type="text" onchange="kmRun(this)" value="" />
There are some problems with your logic.
You're sending txt.Value inside your ItemDataBound, but it will be a fixed value when rendered in your HTML, since it will not get updated when the user types. You must change that:
txt.Attributes.Add("onkeypress", "return kmRun(this.value);")
The keyword this above refers to your input, and whenever the user types, it will get updated.
Javascript is not a typed language, there is no String x = declaration. You must use:
var x = myValue;
You shouldn't use .substring(0, 2) directly without validating if the field has more than two characters, because if it doesn't, the browser will throw an error.
You're using .length as it was a method, but it's a property. Don't use the parenthesis ().
Finally, to pass the value back to your TextBox, you can do:
this.value = x;
Related
I made a simple function that depending on the text of the item selected from a dropdownlist, a textbox will change its maxlength property.
function cambiarLength(drop, textbox) {
var option = document.getElementById(drop);
var texto = option.options[option.selectedIndex].text;
var field = document.getElementById(textbox);
if (texto == 'RUC') {
field.maxLength = 3;
}
else {
field.maxLength = 6;
}
};
Codebehind:
TipoDoc.Attributes.Add("onChange", "javascript: cambiarLength(this, txtDoc);");
Error:
0x800a1391 - JavaScript runtime error: 'txtDoc' is undefined
Image
If txtDoc is the literal id of the field, then it needs to be treated as a string. You should also remove the javascript: prefix as that will disallow this to be recognized in your routine.
TipoDoc.Attributes.Add("onChange", "cambiarLength(this, 'txtDoc');");
See here regarding the use of the javascript: prefix:
When is the 'javascript:' prefix valid syntax?
UPDATE
If you're using WebForms then you will want to use the ClientID, for example, if txtDoc is literally your code-behind control, you should do:
TipoDoc.Attributes.Add("onChange", "cambiarLength(this, '" + txtDoc.ClientID +"');");
How can I get the array value from a hidden input field and be able to grab the elements I need?
<input type="hidden" name="digital_object[prdcls][0][prdcl_links][0][_resolved]" id="digital_object[prdcls][0][prdcl_links][0][_resolved]" value="{"id":"/prdcl_titles/1","title":"test (test)","primary_type":"prdcl_title","types":["prdcl_title"],"json":"{\"lock_version\":0,\"title\":\"test (test)\",\"publication\":\"test\",\"publisher\":\"test\",\"created_by\":\"admin\",\"last_modified_by\":\"admin\",\"create_time\":\"2016-06-07T13:20:46Z\",\"system_mtime\":\"2016-06-07T13:20:46Z\",\"user_mtime\":\"2016-06-07T13:20:46Z\",\"jsonmodel_type\":\"prdcl_title\",\"uri\":\"/prdcl_titles/1\"}","suppressed":false,"publish":false,"system_generated":false,"repository":"global","created_by":"admin","last_modified_by":"admin","user_mtime":"2016-06-07T13:20:46Z","system_mtime":"2016-06-07T13:20:46Z","create_time":"2016-06-07T13:20:46Z","uri":"/prdcl_titles/1","jsonmodel_type":"prdcl_title"}">
When I run this I get 'undefined' for valp.
I also have the issue where the function prdcl_link is not executing on the hidden field being created or changed.
$( document ).ready(function() {
$("#digital_object[prdcls][0][prdcl_links][0][_resolved]").on('keyup change', prdcl_link);
$("#digital_object_prdcls__0__volume_num_").on('keyup change', prdcl_link);
$("#digital_object_prdcls__0__issue_num_").on('keyup change', prdcl_link);
function prdcl_link(){
var valp = {};
valp = $("#digital_object[prdcls][0][prdcl_links][0][_resolved]").val();
console.log(valp);
var valv = $("#digital_object_prdcls__0__volume_num_").val();
var vali = $("#digital_object_prdcls__0__issue_num_").val();
var res;
var pub;
var vol;
var iss;
if (valp!=""){
pub = valp['json']['publication'];
res = pub;
if (valv!=""){
vol = " - Volume " + valv;
res = res.concat(vol);
}
if (vali!=""){
if (valv!=""){
iss = ", Issue " + vali;
}
else {
iss = " - Issue " + vali;
}
res = res.concat(iss);
}
}
$("#digital_object_title_").val(res);
};
});
The value of the input seems to be JSON format, but HTML encoded. First you need to decode the string. Underscore have en unescape function, or you can search to find other ways to do it.
Then you can use JSON.parse to convert it to a javaScript object. But you have an error, so it can't be parsed. There are some extra quotes around an object named 'json'
...,"json":"{...}",...
If you didn't have the quotes around the brackets, it would be valid. What I think happened here is the 'json' object got converted to JSON format (a string) first. Then this string was part of another object, which also got converted to JSON. Now it's impossible to distinguish which quotes is part of what.
In my code below , my ("OnClick") is not firing. Does anyone know why?
e.Row.Cells(1).Attributes("OnClick") = "window.location.href='MachineSweepLite.aspx?AreaID='" _
+ GridView1.DataKeys(e.Row.RowIndex).Values("ID").ToString()
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(1).Attributes("onmouseover") = "this.style.cursor='hand';this.style.textDecoration='underline';"
e.Row.Cells(1).Attributes("onmouseout") = "this.style.textDecoration='none';"
Dim Index As Integer = e.Row.RowIndex
e.Row.Cells(1).Attributes("OnClick") = "window.location.href='MachineSweepLite.aspx?AreaID='" + GridView1.DataKeys(e.Row.RowIndex).Values("ID").ToString
End If
End Sub
Edit above.
You have a error in your attribute, as you are adding the value of the ID after the closing single quote...
For example, if the ID was 12, you're sending this to the browser...
window.location.href='MachineSweepLite.aspx?AreaID='12
Note that the 12 is not part of the URL.
You should have the following instead...
e.Row.Cells(1).Attributes("onclick") =
string.Format("window.location.href='MachineSweepLite.aspx?AreaID={0}';",
GridView1.DataKeys(e.Row.RowIndex).Values("ID").ToString())
Also note, as of .NET 4.0 it is unnecessary to have the _ character when spanning over multiple lines.
e.Row.Attributes("onClick") = "CallFunction('" & Convert.ToString(GridView1.DataKeys(e.Row.RowIndex).Values("ID")) & "');"
JS code:
function CallFunction(val)
{
// do your login here
}
I've been trying to get the value of input text box from Client Side like this:
var CKQtyToDate = XSP.getElementById("#{id:CKQtyToDate}");
var CKQtyToDate = XSP.getElementById("#{id:CKQtyToDate}");
var SLQtyToDate = XSP.getElementById("#{id:SLQtyToDate}");
var FinishingQtyToDate = XSP.getElementById("#{id:FinishingQtyToDate}");
var PackingQtyToDate = XSP.getElementById("#{id:PackingQtyToDate}");
if ((parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value))>parseInt(hContractQty.value))
{
alert("Total qty more than contract qty! =" + parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value));
return false;
}
But I'm still having the result which is only string concatenation,how can i get through this thing???
First of all, in Javascript parseInt returns NaN when parsing an empty string. So make sure to test for empty strings before doing the calculation. You can test if the string can be parsed by using !isNaN(string).
I believe that your problem is that you concatenate strings in your alert box. I will suggest that you move the calculation to a seperate variable and then concatenate the message string with this variable in the alert box:
var result = parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value);
if (result>parseInt(hContractQty.value))
{
alert("Total qty more than contract qty! =" + result);
return false;
}
In my project, there are 3 user controls; BasicContact, BasicDetail and ActionTime. They are in EditOrder.aspx page.
There is "ReportDate" property (Date type) in BasicContact, RadioButtonList "rdl_Priority" (with integer value from "prio_id" field) in BasicDetail and "CheckDate" property in ActionTime. The ReportDate value is derived from txt_ReportDate and txt_ReportTime and CheckDate value is derived from txt_CheckDate and txt_CheckTime.
My objective is to calculate Checkdate after I add date into ReportDate and click on radiobuttonlist. Checkdate will be calculated from ReportDate (date) + SLAHour (hour, get from "GetSLAHour" method where input is prio_id) and then set text in txt_CheckDate and txt_CheckTime.
Right now, I was be able to complete this task using Postback. I create custom event and raise it in RadioButtonList selectedIndexchanged method. After that, event is handled in code behind of EditOrder page. Here are my code.
BasicDetail - RadioButtonList
<asp:RadioButtonList ID="rdl_Priority" runat="server" RepeatDirection="Horizontal" AutoPostBack="true" />
BasicDetail - codeBehind
Public Event priorityClicked As System.EventHandler
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
If Not IsPostBack Then SetupList()
End Sub
Private Sub SetupList()
Dim ctx As New StsDataContext
With rdl_Priority
Dim Result = (From r In ctx.Priorities Order By r.display_order)
If Result.Count > 0 Then
.DataTextField = "prio_name"
.DataValueField = "prio_id"
.DataSource = Result
.DataBind()
Else
lbl_Priority.Visible = False
rdl_Priority.Visible = False
End If
End With
End Sub
Protected Sub rdl_Priority_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdl_Priority.SelectedIndexChanged
RaiseEvent priorityClicked(sender, e)
End Sub
EditOrder - codeBehind
Private Sub BasicDetail_priorityClicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles BasicDetail.priorityClicked
Dim reportDate As Date? = BasicContact.ReportDate
Dim SLAHour As Integer? = GetSLAHour(BasicDetail.PriorityId)
If reportDate.HasValue AndAlso SLAHour.HasValue Then
ActionTime.CheckDate = CDate(reportDate).AddHours(CDbl(SLAHour))
End If
End Sub
However, I don't want the page to be refreshed (no postback). I don't know how to call the function or sub from javascript. I have tried PageMethod but it cause error in runtime saying that the method is not supported. Anyway, if there is a better way than calling code-behind from javascript, please let me know.
Thanks in advance
Ok Sorry, here is my solution
Since for now I used PageMethod to solve this problem, I don't need raise event function from code behind anymore so I deleted all the codes I have posted to ask my own question.
First, I added javascript function to each item in RadioButtonList in BasicDetail code behind
BasicDetail - Code behind
Private Sub rdl_Priority_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdl_Priority.DataBound
For Each li As ListItem In rdl_Priority.Items
Dim slaHour As Integer? = GetSLAHour(li.Value)
li.Attributes.Add("onclick", "return CalCheckDate(" & If(slaHour.HasValue, CStr(slaHour), "null") & ");")
Next
End Sub
This "CalCheckDate" function added to each button is implemented in EditOrder page (user control's parent page)
EditOrder.aspx
<script type="text/javascript">
function CalCheckDate(hour) {
var hid_ServId = document.getElementById('<%=hid_ServId.ClientID%>');
var txt_reportDate = document.getElementById('<%=BasicContact.ReportDateTextName%>');
var txt_reportTime = document.getElementById('<%=BasicContact.ReportTimeTextName%>');
PageMethods.GetCheckDateTime(hid_ServId.value, txt_reportDate.value, txt_reportTime.value, hour, OnGetCheckDateComplete, OnGetCheckDateError);
}
function OnGetCheckDateComplete(result) {
var txt_checkDate = document.getElementById('<%=ActionTime.CheckDateTextName%>');
var txt_checkTime = document.getElementById('<%=ActionTime.CheckTimeTextName%>');
var chkDateTime = result.split(" ");
txt_checkDate.value = chkDateTime[0];
txt_checkTime.value = chkDateTime[1];
}
function OnGetCheckDateError(e)
{
alert(e._message);
}
</script>
Child control within user control, such as txt_ReportDate in BasicContact, can be derived by creating property in BasicContact as follows:
BasicContact - Code Behind
Public ReadOnly Property ReportDateTextName() As String
Get
Return txt_ReportDate.ClientID
End Get
End Property
This property is used in "CalCheckDate" function to get its value and pass it to PageMethod function. Other controls can be derived in the same way.
Last step is coding PageMethods function, "GetCheckDateTime", in EditOrder code behind
EditOrder - Code Behind
<System.Web.Services.WebMethod()> _
Public Shared Function GetCheckDateTime(ByVal servId As String, ByVal ReportDate As String, ByVal ReportTime As String, ByVal hour As String) As String
Dim checkDate As String, checkTime As String
'************************************************************************
'Calculate check and time date from input ReportDate, ReportTime and hour
'************************************************************************
Return checkDate & " " & checkTime
End Function
The result is returned to "OnGetCheckDateComplete" function in javascript (or "OnGetCheckDateError" if there is an exception). Here, I split the String and use its value to set text in textbox.