How to pass value from javascript to label in asp.net? - javascript

I need to pass a javascript value to label in asp.net. The javascript function was inside JScript1.js. I pass the value to a hidden field. I already added the script to the source of the content page as below, but doesn't work whenever I called the function value to the vb.net code behind.
<script src="JScript1.js" type="text/javascript"></script>
Here's the javascript function inside a JScript1.js
function dateTimeToday()
{
var month=new Array();
month[0]="1";
month[1]="2";
month[2]="3";
month[3]="4";
month[4]="5";
month[5]="6";
month[6]="7";
month[7]="8";
month[8]="9";
month[9]="10";
month[10]="11";
month[11]="12";
var d = new Date();
var mt=month[d.getMonth()];
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
mt=checkMonth(mt);
m=checkTime(m);
s=checkTime(s);
var x = document.getElementById("HiddenField1");
x.innerHTML=d.getFullYear()+"-"+mt+"-"+d.getDate()+" " +h+":"+m+":"+s;;
t=setTimeout(function(){myFunction()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
function checkMonth(j)
{
if (j<10)
{
j="0" + j;
}
return j;
}
Below is my code of calling the javascript value.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
lbl.Text = HiddenField1.Value
End If
End Sub
Am I missing something on my code?
Please help.
Thanks in advance.

You need to set the value of the input field, not the innerHtml:
var x = document.getElementById("HiddenField1");
x.value =d.getFullYear()+"-"+mt+"-"+d.getDate()+" " +h+":"+m+":"+s;
And consider that the ID of asp.net control can change when the page is rendered, you could use:
var x = document.getElementById('<%= HiddenField1.ClientId %>');
x.value =d.getFullYear()+"-"+mt+"-"+d.getDate()+" " +h+":"+m+":"+s;

I hope you want to set value in Hiddenfield in javascript..You can do..
document.getElementById("HiddenField1").value=d.getFullYear()+"-"+mt+"-"+d.getDate()+" " +h+":"+m+":"+s;
In code behind..
lbl.Text = HiddenField1.Value;
Hidden input markup..
<input id="HiddenField1" type="hidden" runat="server" clientidmode="Static" value=""/>

Related

How to get value from GridView cell with Javascript

I'm trying to get a value from a GridView cell to change the source of an embed PDF. I execute a function when a button that is placed on each row of the GridView is clicked.
This is the code I have so far:
<script>
function changepdf(pdf) {
var value = document.getElementById('<%= GridView1.ClientID %>').rows[pdf.rowIndex].cells[3].innerText;
var file = document.getElementById('pdf');
file.src = 'pdf/catalogosh.pdf#page=' + value + '&#toolbar=0&#view=fit';
return false;
}
</script>
The Javascript function works fine when I write exactly the new source like this:
<script>
function changepdf(pdf) {
var file = document.getElementById('pdf');
file.src = 'pdf/catalogosh.pdf#page=4&#toolbar=0&#view=fit';
return false;
}
</script>
The main idea is to change the PDF page taking the value from de GridView.
Thanks in advance for any help.
I've just solved it. I'm pasting the code here for anyone that's trying to solve the same problem:
function changepdf(pdf) {
var row = pdf.parentNode.parentNode;
var rowIndex = row.rowIndex;
var value = document.getElementById('<%= GridView1.ClientID %>').rows[rowIndex].cells[2].innerText;
var file = document.getElementById('pdf');
file.src = 'pdf/catalogosh.pdf#page=' + value + '&#toolbar=0&#view=fit';
return false;
}
My problem was the rowIndex. The code was bad and I was getting the wrong value.
I added this two lines to get it well:
var row = pdf.parentNode.parentNode;
var rowIndex = row.rowIndex;
And then I got the cell value with this line:
var value = document.getElementById('<%= GridView1.ClientID %>').rows[rowIndex].cells[3].innerText;

Updating certain Primefaces Diagram Element

I am trying since 2 days to solve a issue I got with my primefaces diagram implementation.
I want on "mouseover" the diagram elements, highlight other elements that are connected with that element.
I have it working, but ONLY if I update the whole diagram/form when I update the elements.
I have two problems with that approach.
First with the constant updates on mouseover all the binding on mouseenter and other stuff, gets reset so I have the event fire all the time although I just entered. Also 80% of the time I dont catch the mouseleave / hover leave event because of the constant calls.
Also I cant scroll the diagram anymore as the constant updates on mouseover would reset the scroll. ;-)
So I tried to only update the diagram elements I actually changed on mouseover, but I could not find a way that worked for me...
I tried just updateing the element via primefaces RequestContect.update
I used all variations on the Id like:
1-0201
diagram-1-0201
diagram:diagram-1-0201
I tried a javascript query from primefaces execute. I got a ui cant be resolved error on that one. Although the same query works on the xhtml. I also couldnt figure out that error. Although I dont think it would help, as the same code doesnt work when executed in the html file aswell.
I tried just saving the connections in a diagram element value and then accessing this value via hidden input on the elements. I got the ids for the connected elements in my javascript but I could not update the elements via javascript aswell. "inside" (leftover commented code) was the variable I had for the hidden inputs that were referenced on the Element variable that stored the connections)
I got both the list and the single connected ids in javascript but couldnt manage to update the elements.
I am not that experienced in javascript. I used it for the first time a few days ago.
So how do I update the style of certain elements in the primefaces diagram without reloading the hole diagram?
There must be a very easy way to do it or an easy way to fix my approaches I just cant see.
It is working if I update the whole diagram as I said, but I cant do that on mouseover for obvious reasons.
I am using primefaces 6.0 with a apache tomcat 8.5
Picture of the setup with ids: http://i.imgur.com/9yTEabE.png
Picture of the javascript log for the events: http://imgur.com/mCgf0BU
my xhtml file:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<p:panelGrid columns="2" styleClass="borderless">
<h:graphicImage name="images/logo.gif" />
<h:outputLabel styleClass="h1" value="Diagram Viewer" />
</p:panelGrid>
<f:metadata>
<f:viewAction action="#{dataManager.onLoad}" />
</f:metadata>
</h:head>
<h:body>
<h:form id="tabMenuForm">
<p:menubar styleClass=".ui-menu .ui-menuitem-link"
model="#{dataManager.menuModel}" />
</h:form>
<h:form id="diagramForm">
<p:dialog widgetVar="statusDialog" modal="true" draggable="false"
closable="false" resizable="false" showHeader="false">
<p:graphicImage value="#{resource['images/defaultLoader.gif']}" />
</p:dialog>
<p:tooltip />
<p:diagram id="diagram" value="#{dataManager.model}"
styleClass="borderless" style="#{dataManager.diagramStyle}" var="el">
<f:facet name="element" id="diagramElement" widgetVar="element">
<h:outputLabel>
<p:commandLink
actionListener="#{tooltipManager.onElementClickedTwo()}"
styleClass="commandRemover">
<f:param name="selected" value="#{el.id}" />
<div class="elID">
<h:outputText value="#{el.id}" />
</div>
<div class="elName">
<h:outputText value="#{el.name}" sytleCLass="elName" />
</div>
</p:commandLink>
</h:outputLabel>
<!-- <h:outputText value="#{el.role}" style="display: inline; align-items: right; margin-top:0em;"/> -->
</f:facet>
</p:diagram>
<p:remoteCommand name="elementMouseOver"
actionListener="#{dataManager.onElementMouseOver}" />
<p:remoteCommand name="elementMouseOut"
actionListener="#{dataManager.onElementMouseOut}" />
<h:inputHidden id="someId" value="#{dataManager.selectedId}" />
<script type='text/javascript'>
$('.ui-diagram-element').hover(function(ev) {
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
//var inputs = $(this).find('input');
//console.log('INSIDE!' + inputs);
//var input = inputs[0].val();
//var val = $(input).val();
//console.log('VAL: ' + val);
//console.log('INSIDE!' + input);
//var string = '#diagramForm\\:diagram-' + input;
//$(string).addClass('ui-diagram-element-predecessor');
//+ val[i]));
elementMouseOver([ {
name : 'elementId',
value : id
} ]);
//console.log(val);
}, function(ev) {
//***leave***//
var id = $(this).attr('id');
});
</script>
Important part of the Bean:
private DiagramNode selected;
private String selectedId = "x";
private List<String> selectedList = new ArrayList<String>();
public String getSelectedId() {
return selectedId;
}
public void setSelectedId(String selectedId) {
this.selectedId = selectedId;
}
public List<String> getSelectedList() {
return selectedList;
}
public void setSelectedList(ArrayList<String> selectedList) {
this.selectedList = selectedList;
}
public void onElementMouseOver() {
String input = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("elementId");
System.out.println("DataManager: Input: " + input);
String[] mouseoverIdSplit = input.split("-", 2);
if (mouseoverIdSplit.length < 2)
return;
System.out.println("DataManager: Mouseover:" + mouseoverIdSplit[1]);
selected = DataLoader.WPCPTaskRows.get(mouseoverIdSplit[1]);
selectedId = mouseoverIdSplit[1];
selectedList = selected.connections;
for (String id : selected.connections) {
System.out.println("Setting StyleClass for " + id);
String elementToUpdate = "diagramForm:diagram-" + id;
System.out.println(elementToUpdate);
RequestContext.getCurrentInstance().update(elementToUpdate);
RequestContext.getCurrentInstance()
.execute("$('#" + elementToUpdate + "').addClass(ui-diagram-element-predecessor);");
}
// RequestContext.getCurrentInstance().update("scriptBean");
// RequestContext.getCurrentInstance().update("someId");
RequestContext.getCurrentInstance().update("diagramForm");
RequestContext.getCurrentInstance().update("diagram");
}
public class DiagramElement implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String id;
private String role;
private String predecessor;
private List<String> predecessorList;
public DiagramElement() {
}
public DiagramElement(String name, String id, String role, String predecessor, List<String> predecessorList) {
this.name = name;
this.id = id;
this.role = role;
this.predecessor = predecessor;
this.predecessorList = predecessorList;
}
+getter and setter
After more then 10 hours of insanity I FINALLY got it working.
I connected the strings for the ID in javascript not correctly.
Also I had to add 3 \\ to the string, because 1 was swallowed as a escape and I needed 2 for a javascript function to find the element with a ":" inside it.
Here is how I did it in the end:
<h:inputHidden value="#{el.predecessorList}" />
$('.ui-diagram-element').hover(
function(ev) {
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
var inputs = $(this).find('input');
console.log(inputs);
var input = inputs[1];
//var val = $(input).val();
//console.log('VAL: ' + val);
var array = input.value;
console.log(array);
var parsedArray = array.replace("[", "").replace("]",
"").replace(/\s/g, "").split(',');
for ( var pos in parsedArray) {
var str1 = '#diagramForm\\\:diagram-';
var str2 = parsedArray[pos];
console.log(str2);
var con = str1.concat(str2);
console.log(con);
$(con).addClass('ui-diagram-element-predecessor');
}
},
function(ev) {
//***leave***//
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
var inputs = $(this).find('input');
console.log(inputs);
var input = inputs[1];
//var val = $(input).val();
//console.log('VAL: ' + val);
var array = input.value;
console.log(array);
var parsedArray = array.replace("[", "").replace("]",
"").replace(/\s/g, "").split(',');
for ( var pos in parsedArray) {
var str1 = '#diagramForm\\\:diagram-';
var str2 = parsedArray[pos];
console.log(str2);
var con = str1.concat(str2);
console.log(con);
$(con).removeClass('ui-diagram-element-predecessor');
}
});

Get ASP.NET label's text or value in JavaScript

I want to transfer a string of data from C# to JavaScript in ASP web forms. My approach is to set the data as a text for an ASP label in C# and then grab the label's text by ID in JS.
C# code (ascx.cs file):
List<Event> eventList;
protected void Page_Load(object sender, EventArgs e)
{
string message = string.Empty;
SPSite franasabank = new SPSite("http://lbshrptweb/sites/fransabank/");
SPWeb calendar = franasabank.OpenWeb();
SPList list = calendar.Lists["Fransabank Calendar"];
eventList = new List<Event>();
foreach (SPListItem oItem in list.Items)
{
// Access each item in the list...
DateTime startTime = (DateTime)oItem["Start Time"];
DateTime endTime = (DateTime)oItem["End Time"];
string status = (String)oItem["Status"];
string title = oItem.Title;
string description = (String)oItem["Description"];
Event calendar_event = new Event(startTime, endTime, status, title, description);
eventList.Add(calendar_event);
}
foreach (Event item in eventList)
{
message += item.Title + " " + item.Description + item.StartDate + "-" + item.EndDate + "-" + item.Status + "\n";
}
Label1.Text = message;
}
HTML snippet showing the Label (ascx file):
<div data-ng-app="Calendar">
<div data-ng-controller="CalendarController" id="mycontroller">
<div class="row " data-ng-init="Initialize()">
<asp:Label ID="Label1" runat="server" Text="Label" ></asp:Label>
JavaScript code:
<script>
var a = document.getElementById('<%= Label1.ClientID %>');
console.log(a);
</script>
I'm receiving the data as null in variable 'a'. I've tried
var a = document.getElementById('<%= Label1.ClientID %>').innerHTML;
but it is also null
Sounds like Javascript runs before the label is loaded
Place the js after the <asp:Label> on the page. Preferably before </body>:
<script>
var a = document.getElementById('<%= Label1.ClientID %>');
console.log(a);
</script>
</body>
Alternatively you can surround the code block with jQuery $(document).ready():
<script>
$(document).ready(function () {
var a = document.getElementById('<%= Label1.ClientID %>');
console.log(a);
});
</script>

How to get value from dynamic control in gridview using javascript

I have one dynamic gridview contains one textbox.when user lost focus from the textbox, i want to get the value using javascript.for that i am using onblur() event in the textbox.but i'm not able to get the value .please find the code below
function validateintforDWOnblur(input) {
var row = input.parentNode.parentNode;
var rowindex = row.rowIndex;
var totaldw = document.getElementById('<%=gdvaddmsrcrt.ClientID%>').rows[rowindex].cells[2].innerHTML;
var totaldw1 = document.getElementById(totaldw.id).value;
var dw = document.getElementById('<%=gdvaddmsrcrt.ClientID%>').rows[rowindex].cells[3].innerHTML;
return true;
}
textbox inside the gridview
<asp:TextBox ID="txtdiswei" runat="server" onblur="javascript:return validateintforDWOnblur(this)" Width="100px" Text='<%# Bind("DW") %>' Height="40" CssClass="form-control"></asp:TextBox>
Please help me to sort this out.
I'm not sure that it is what you want but why don't you try
var value = document.getElementById('<%=yourTextBox.ClientID%>').value;
so for your table you can pass the ClietnId property from eachRow and use it in the javascript function
function doSomething(idOfTheTextBox){
var value = document.getElementById(idOfTheTextBox).value;
}
in html
onblur="doSomething('<%# this.ClientID %>')
if you build server side your rows you can do the following
TextBox txt = new TextBox();
txt.ID = "something1";
txt.Text = "text";
txt.Attributes.Add("onBlur","doSomething('" & txt.ClientID & "')");
CellOfTheGrid.Controls.Add(txt);

How to get custom attribute value from a radcomboboxitem when an item is selected with javascript

Here is my code:
<telerik:RadComboBox ID="ddlServicesRequested" runat="server" DataValueField="Value" DataTextField="Text" Skin="Vista" OnClientSelectedIndexChanging="setQtyReq"></telerik:RadComboBox>
function setQtyReq(combo, eventArgs) {
var Combo = $find("<%= ddlServicesRequested.ClientID %>");
var index= eventArgs.get_item().get_index();
}
Me.ddlServicesRequested.Items.Insert(0, New RadComboBoxItem("-- Select One --", "0"))
Dim dt1 As DataTable = GetDataTable("myStoredProcedure")
For Each dr As DataRow In dt1.Rows
Dim rcbi As New RadComboBoxItem()
rcbi.Text = dr("Text")
rcbi.Value = dr("Value")
rcbi.Attributes("Min") = dr("MinQty")
rcbi.Attributes("Max") = dr("MaxQty")
Me.ddlServicesRequested.Items.Add(rcbi)
Next
Here I have the radcombobox that is being populated with two custom attributes, Min and Max. When the user selects an item the setQtyReq javascript function get called and I am able to get the radcombobox and the index of the selected item. My problem I am having is that I can't figure out a way to get the values of the custom attributes. How can I get the values of the custom attributes?
Finally figured out how to do it:
function setQtyReq(combo, eventArgs) {
var item = eventArgs.get_item();
var min = item.get_attributes().getAttribute("Min");
var max = item.get_attributes().getAttribute("Max");
}
http://www.telerik.com/help/aspnet-ajax/combobox-custom-attributes.html
<script language="javascript">
function setQtyReq(combo, eventArgs) {
var Combo = $find("<%= ddlServicesRequested.ClientID %>");
var index= eventArgs.get_item().get_index();
alert(Combo.Items[index].Attributes.Max);
alert(Combo.Items[index].Attributes.Min);
}
</script>
Looks like the above will work.

Categories

Resources