I am assigning a value to asp textbox in javascript as follows:
var tempStorytxt = document.getElementById("<%=txtStory.ClientID%>");
tempStorytxt.Value = TempValue;
alert(tempStorytxt.Value);
but when I access in codebehind as follows there is nothing in txtStory
int StoryId = int.Parse(txtStory.Text);
Use small V as txtStorytxt.value not txtStorytxt.Value
Try this one:
document.getElementById("<%= txtStory.ClientID%>").value = TempValue;
try this;
<asp:Button ID="btnTest" runat="server" OnClientClick="setVal()" OnClick="btnTest_Click" Text="Test" />
your js function;
function setVal()
{
var tempStorytxt = document.getElementById("<%=txtStory.ClientID%>");
tempStorytxt.setAttribute("value", tempValue);
alert(tempStorytxt.getAttribute("value"));
}
and in button click event;
int StoryId = int.Parse(txtStory.Text);
Related
I have an issue in getting the hidden field values, which is been set in page load at code behind. Problem is when i try to get that set values in javascript its giving undefined or null. Not able to get the values which was set in page load at code behind.
//cs code is like this
protected async void Page_Load(object sender, EventArgs e)
{
HiddenField_alt_edit.Value = "[{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]";
ClientScriptManager script = Page.ClientScript;
script.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type=text/javascript>addAlternativeRowWithData();</script>");
}
//aspx page declaration goes like this. Also i am using a master page.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on."/>
</asp:Content>
// javascript file code goes like this
function addAlternativeRowWithData(mode)
{
alert("test");
var idvalue = $("#HiddenField_alt_edit").val();
alert(idvalue);
alert($nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val());
var myHidden = document.getElementById('<%= HiddenField_alt_edit.ClientID %>').value;
alert(myHidden);
var json_string = $nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val();
var arr_from_json = JSON.parse(json_string);
alert("test 2");
alert(arr_from_json);
}
The id generated at client side can differ as the Hidden field is server side control in your code as you have set runat="server".
There are two ways normally. Either make the ClientIDMode static or use the instance in form to get client side id.
Like:
<asp:HiddenField ID="HiddenField_alt_edit" ClientIDMode="static" runat="server"
Value="i am on."/>
and then following should work:
var idvalue = $("#HiddenField_alt_edit.ClientID").val();
or in client side code you need to get id like below:
var idvalue = $("#<%= HiddenField_alt_edit.ClientID %>").val();
Change:
HiddenField_alt_edit.Value = [{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]
To this:
HiddenField_alt_edit.Value = "
[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]"
Then, add this:
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on." ClientIDMode="Static" />
In you js, you have to put this:
const value = document.getElementById('HiddenField_alt_edit').value
const jsonString = JSON.stringify(value)
const json = JSON.parse(jsonString)
console.log(json)
<input hidden id="HiddenField_alt_edit" value="[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]">
I'm using ASP to look for the selected value in a dropdown box. The dropdown box choices are generated at load time. Here is the JavaScript for that:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
}
And it looks like this:
Looks fine to me. Then I checked the HTML out too just to be sure:
That looks great too. Now here is where the issue comes up. When I press submit this delegate fires in C# (still only testing while making this):
void Activity_Submit_Click(object sender, EventArgs e)
{
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
And when I debug this it stops at department saying that it's malformed. Looking at department_dropdown.Value in the immediate window turns up an empty string and the dropdown itself has 0 children.
Why would this return an empty response when the list is clearly there? How would I go about fixing this?
The client-side items won't get posted back to the server like this.
The easiest way is to Serialize the array as Json, put it in a hidden input element's value :
In your markup:
<asp:HiddenField runat="Server" ID="department_dropdown_items" cssclass="department_dropdown_items" />
<asp:HiddenField runat="Server" ID="department_dropdown_selected" cssclass="department_dropdown_selected" />
Your Javascript:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
$(".department_dropdown_items").text(JSON.Stringify(data));
}
$(document).ready(function() {
$("form").submit(function(e) {
$(".department_dropdown_selected").text( $("#department_dropdown").value);
});
});
then use it in the code behind:
void Activity_Submit_Click(object sender, EventArgs e)
{
string[] data = new JavascriptSerializer().Deserialize<string[]>(department_dropdown_items.Value);
string selectedValue = department_dropdown_selected.Value;
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
The code is not tested. Tell me if it's not working :)
So I ended up doing the following:
Make a Hidden asp element called department_dropdown_selected_value
Then in a Script tag I made the following function:
.
function GetDepartmentDropdownValue(sel) {
var hidden_field = document.getElementById('department_dropdown_selected_value');
hidden_field.value = sel.value;
}
Then in my HTML I did this: <select class="form-control" id="department_dropdown" onchange="GetDepartmentDropdownValue(this)">
Then I can just simply do this in C#: int department = Int32.Parse(department_dropdown_selected_value.Value);
Please help! i have been trying to call this function on my Asp.net textbox to format users input while typing.
function format(number) {
var decimalSeparator = ".";
var thousandSeparator = ",";
var result = String(number);
var parts = result.split(decimalSeparator);
if (!parts[1]) {
parts[1] = "00";
}
result = parts[0].split("").reverse().join("");
result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);
parts[0] = result.split("").reverse().join("");
return parts.join(decimalSeparator);
}
// i tried using onkeyup, it didnt work
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onKeyup="javaScript: format(this);"></asp:TextBox>
// also i tried using onChange, it didnt work.
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onChange="javaScript:format(this);"></asp:TextBox>
protected void Page_Load(object sender, EventArgs e)
{
txtTransport.Attributes.Add("onKeyup", "javaScript: format(this);");
}
You can do it directly from javascript, not in codebehind !
var el = document.getElementById("<%= txtTransport.ClientID %>");
el.onkeyup = function(e) {
// Do stuff
};
But I think your function is logicaly wrong. Try it anyway. Your ID of a server side control is not exactly the same you write in the code, for get the real ID you can use <%= txtTransport.ClientID %>.
Can't get value from getValue in JS and can't show value in showValue field.
Thanks in advance
ASPX PAGE CODE
<script>
var x = document.getElementById("<%=getValue.ClientID %>").innerHTML;
document.getElementById('showValue').innerHTML = x;
</script>
<asp:Label runat="server" ID="getValue" />
<asp:Label runat="server" ID="showValue" />
C# CODE
getValue.Text = "value from code";
You need to call javascript once all the controls are rendered, then only you can get the proper id of the <asp:label> control, so you need to write that javascript code under window.onload().
Also for showValue, you need to use ClientID.
window.onload= function(){
var x = document.getElementById("<%=getValue.ClientID%>").innerHTML;
document.getElementById('<%=showValue.ClientID %>').innerHTML = x;
};
I have an Asp server control button for which I have onClick for processing code in code behind and onClientClick to process javascript code. The codes are:
Update: As per Icarus solution, updated codes :
Button source:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
style="z-index: 1; left: 648px; top: 202px; position: absolute"
Text="Show route" OnClientClick="droute(); return false" />
<asp:HiddenField ID="hdncroute" runat="server" />
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
using (con = new MySqlConnection("server=localhost; uid=root;password=as64ws;database=Gmaps"))
da = new MySqlDataAdapter("select * from routes where uid='" + Session["uname"].ToString() + "'", con);
da.Fill(ds, "mroute");
foreach (DataRow r in ds.Tables[0].Rows)
{
uroute.Add(r["latlng"].ToString());
}
croute = new string[uroute.Count];
croute = uroute.ToArray();
hdncroute.Value = string.Join("&", croute);
}
Javascript function:
function droute()
{
var route=[];
var temp;
temp = eval(document.getElementById('<%= hdncroute.ClientID %>').value);
route= temp.split('&');
//Polyline icon n line settings
var iconsetngs= {path:google.maps.SymbolPath.FORWARD_CLOSED_ARROW, fillColor:'#FF0000'};
var polylineoptns= {strokeColor:'#3333FF',strokeOpacity:0.8,strokeWeight:3,map:map,icons:[{icon:iconsetngs,offset:'100%'}]};
polyline= new google.maps.Polyline(polylineoptns);
//Loop to add locations and draw line
var path= polyline.getPath();
for(var i=0;i<route.length;i++)
{
var marker= new google.maps.Marker({position:route[i],map:map});
path.push(route[i]);
google.maps.event.addListener(marker,'click',showiwindow);
}
//Event Listener's
function showiwindow(event)
{
iwindow.setContent("<b>Coordinates are:</b><br/>Latitude:"+event.latLng.lat()+"<br/>Longitude:"+event.latLng.lng());
iwindow.open(map,this);
}
}
I know that writing return false for javascript function will avoid refresh, and also onClick has void return type. But still my page reloads on button click.
You have an error here:
route = document.getElementById('<%= croute %>').value;
It should be:
route = document.getElementById('<%= croute.ClientID %>').value;
Update:
Markup - declare a hidden element in the page
<asp:hiddenfield id="hdnCroute" runat="server" />
//code behind
int [] croute = ...
hdnCroute.Value = "["+string.Join(",",croute)+"]";
Now Javascipt:
//now you have an array back in javascript
var route= eval(document.getElementById('<%= hdnCroute.ClientID %>').value);
why the page reload?
OnClientClick="droute(); return false"
at inner of browser like this:
button.onclick = function(){
droute();
return false
};
while droute is going wrong,so,return false doesn't work.