How can i assign value to javasctipt variable from code-behind (C#)?
<script type="text/javascript">
String.prototype.trim = function () { return this.replace(/^\s+|\s+$/, ''); };
function ConstantByCode(_Obj, _Div) {
var pl = new SOAPClientParameters();
_Obj.value = _Obj.value.trim();
pl.add("Code", _Obj.value);
pl.add("Group", _Obj.Grp);
alert(_Obj.Grp);
var _Value = SOAPClient.invoke("ConstantWS.asmx", "GetConstantByCode", pl, false, CallBackEvent);
if (_Value == null || _Obj.value == "" || _Obj.value == null || IsNumeric(_Obj.value) == false) {
_Obj.value = "";
_Div.innerHTML = "";
}
else {
_Div.innerHTML = _Value;
}
}
function CallBackEvent(r) {
}
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
BehindCode
txtCode.Attributes.Add("Grp", Me.ConstValue)
txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
txtCode.Attributes.Add("onkeyup", "ConstantByCode(this," & DivTitle.ClientID & ");")
_obj.Grp has now value.
alert said : undefined
I see that you want to retrieve value of Grp that is a custom attribute. You need to use getAttribute function - so instead of _Obj.Grp, you need to use _Obj.getAttribute("Grp").
Also, I see that you are not enclosing client id in quotes from ode-behind. So instead of
txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
you need to say
txtCode.Attributes.Add("onchange", "ConstantByCode(this,'" & DivTitle.ClientID & "');")
Note the single quote(') around the client id.
Further, ConstantByCode js function appears to be taking div element. Hence, you need to add line to it for converting from client id to actual DOM. i.e.
function ConstantByCode(_Obj, _Div) {
_Div = document.getElementById(_Div);
.... // rest of the code
Firstly you will need to have access to the value on the client. We can do this by storing the value in a hiddenfield or by adding an attribute to the control. It seems you wish to do this by using an attribute so lets do this first.
add the following to your page_load method so we have access to the C# value on the client.
protected void Page_Load(object sender, EventArgs e)
{
string requiredJSValue = "put your value here";
txtCode.Attributes.Add("CSCodeAttribute", requiredJSValue);
}
We then need to access this value through Javascript. Firstly we will need to get the client ID of the control as C# will set this value. Note. I am using Jquery to retrieve the control ID. This is not required, however I prefer it. Jquery is a framework for javascript and can be downloaded from www.jquery.com
function GetCSAttributeValue()
{
var csControlID = $('#<%= txtUOMCost.ClientID %>'); //Gets the control name.
var requiredJSValue = csControlID .attr("CSCodeAttribute"); //Value stored in variable.
}
I'm not 100% sure but I think you'll need a workaround to get this working. Because logically at the backend the javascript variable doesn't even exist. You can probably create a hidden field and make it a bridge between the javascript variable and code behind. Check this: http://forums.devx.com/showthread.php?t=164356
Try this:
1. Add a hidden field in you .aspx page:
<asp:HiddenField ID="hidden" runat="server" />
2. Change the value of this field in your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
hidden.Value = "hello";
}
3. Write the following script to access the value and put it in any variable:
<script type="text/javascript">
if (document.getElementById("MainContent_hidden") != undefined) {
var hiddenVal = document.getElementById("MainContent_hidden").value;
}
else {
var hiddenVal = null;
}
</script>
WARNING: The third part is tricky. We are not using the same ID that we provided in the 1st step when we are calling the getElementById function. This is because asp.net changes this and the temporary workaround is to run the page once and view its source. Check the id of the hidden field and put it in step 3 inside the getElementById function. You can look for better alternatives but for now use this if you want. If you're struck at step 3, let me know.
I don'see how your question is related to the code...
But to set a value of a javascript value from serverside... well you can't, because server side code runs precisely in the server and way before the HTML goes to the client and javascript gets executed.
But what you can do is make your server side code generate a piece of javascript that holds your value.
<script type="text/javascript">
var x = <%= ServerSideMethod() %>;
</script>
Related
I'm trying to populate a SELECT using jQuery and after it's populated set the value i want.
I'm working with ASP.NET MVC 5.
The problem is the value doesn't get set
Here's my code:
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(); //Populates the dropdownlist
PreviousCategory(); //Sets DropDownList value to previous state (posted value)
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategory").val(previousCategory);
}
}
$("#PreviousCategory") is a hidden input wich gets it's value server-side after a postback with the next code:
#if (ViewBag.Category!=null)
{
#Html.Hidden("PreviousCategory",(object)ViewBag.Category);
}
Both functions work separately, the DropDownList gets populated flawlessly, but the value doesn't get set.
If i trigger PreviousCategory() from another event (for example a button click), the value gets set perfectly.
I didn't think it was necessary to post ListCategories() code since it works well and you can just assume it fills the dropdownlist, though if anyone find it necessary let me know and i'll edit the post.
EDIT:
Here is ListCategories() code:
function ListCategories(){
_idOrganigrama = $("#IdOrganigrama").val()
_idTipoPedido = $("#IdTipoPedido").val()
data = { idOrganigrama: _idOrganigrama, idTipoPedido: _idTipoPedido }
$.post("ListCategories/", data, function (categoryList) {
$("#IdCategoria").empty();
$(categoryList).each(function () {
$("<option />", {
val: this.Id,
text: this.Descripcion
}).appendTo($("#IdCategory"));
});
});
}
By the way...$("#IdCategory") is the select.
The problem seems to be in the ListCategories where you might be using a async function like ajax to fetch data from server and populate the select.
So use a callback based solution like this
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(PreviousCategory); //Populates the dropdownlist
//Sets DropDownList value to previous state (posted value) after the values are loaded
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategoria").val(previousCategory);
}
}
function ListCategories(callback) {
//your ajax request to populate the select
$.ajax({}).done(function () {
//populate the select
//then at the last call the callback method which will set the value
callback()
})
};
i am nwe to jquery.how i get value of hidden field after post back in csharp. when ever post back occures value dissapear.
this is my hidden field.
<asp:HiddenField ID="Hid_BasicSalary" runat="server" />
this is jquery code where is assign data to it after succsesful execution of ajax web service.
var BasicSalary = $('Hid_BasicSalary');
BasicSalary.val(data["BasicSalary"]);
this is c sharp code when i click on button postback occurs afte this node data.
protected void Btn_PIncrementSave_Click(object sender, EventArgs e)
{
try
{
TxBx_IncrementAmount.Text = Hid_BasicSalary.Value.ToString();
}
catch (Exception ex)
{
Utility.Msg_Error(this.Master, ex.Message);
}
}
please help me
In jQuery we use the selector for select any elements, and we have to put . for the class and # to the id selector so please put # or . before your element.
In your case, $('#Hid_BasicSalary'); or $('.Hid_BasicSalary'); is your answer.
i was missing # with $.
var BasicSalary = $('Hid_BasicSalary');
i write this instead of this
var BasicSalary = $('#Hid_BasicSalary');
Try this
var BasicSalary = $('#Hid_BasicSalary');
Use This code is page load to get new value from hidden
Request.Form["hdnvalue"];
you missed the "#" and i think that you should use the hidden control's clientid.
var BasicSalary = $('#<%=Hid_BasicSalary.ClientID%>');
try this to get value of server control from javascript/jquery
var BasicSalary = document.getElementById('<%=Hid_BasicSalary.ClientID%>').value
I have a textbox with a live search function. It is working all good except one problem. If I type any characters on it, it just loses its focus. If I set textbox.Focus(), the cursor goes at the beginning of the textbox.
I have tried most of solutions on the internet. Please check my codes below.
asp:TextBox ID="searchCompany" runat="server" Text="" CssClass="searchCompany" AutoPostBack="true" Width="190px" OnTextChanged="searchCompany_TextChanged"></asp:TextBox>
In page_Load
protected void Page_Load(object sender, EventArgs e)
{
//ScriptManager1.RegisterAsyncPostBackControl(Menu1);
menuDisplay();
searchCompany.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + searchCompany.UniqueID + "\\',\\'\\')', 0);");
//searchCompany.Attributes.Add("onfocus", "javascript:setSelectionRange('" + "','')");
//searchCompany.Focus();
}
and I have tried javascript as below
<script type="text/javascript">
function setSelectionRange() {
var inputField = document.getElementById('searchCompany');
if (inputField != null && inputField.value.length > 0) {
if (inputField.createTextRange) {
var FieldRange = inputField.createTextRange();
FieldRange.moveStart('character',inputField.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
}
</script>
I have tried to put codes on a method "searchCompany_TextChanged" which is calling if user type any characters on a textbox everytime however it is not working as well.
I saw other solutions with using Textbox.Select() but System.Windows.Control is not working in asp.net i guess.
Any idea??
There's a very simple trick that's worked for me. Basically, set the text value of the of input to itself to its own text value, and that will move the cursor to the end of the text. Then just focus it. This code uses jQuery to demonstrate that, but you should be able to do that in straight JS as well.
HTML
<input type="text" id="focusText"></input>
<button id="focusButton">Set Focus</button>
JavaScript
$("#focusButton").click(function() {
var text = $("#focusText").val();
$("#focusText").val(text).focus();
})
Here's a non jQuery example of the JavaScript, HTML should be the same:
document.getElementById("focusButton").onclick = function() {
var inputElement = document.getElementById("focusText");
var text = inputElement.value;
inputElement.value = text;
inputElement.focus();
}
Here's a fiddle demonstrating the non-jQuery version of the code: http://jsfiddle.net/C3gCa/
I am using this javascript function to show different popups if location count varies. Here the txthiddenloccount value is null if the txtbox's visibility is false. If the visibility is true, it works fine. What strange is this??? Can someone help me out.
function isPageValid()
{
var validated = Page_ClientValidate('groupProfile');
var loccount = document.getElementById("ctl00_ContentPlaceHolder1_txthiddenloccount").value;
if(validated)
{
if(loccount == '1')
{
var mdlPopup = $find('<%= ModalPopupExtendersavechanges.ClientID %>');
if(mdlPopup)
{
mdlPopup.show();
}
}
else
{
var mdlPopup = $find('<%= ModalPopupExtenderMerchantUpdate.ClientID %>');
if(mdlPopup)
{
mdlPopup.show();
}
}
}
}
if txthiddenloccount is an asp:TextBox that has the Visible property set to false then it does not exist on the page that is readable by javascript. It will be stored in the ViewState.
For something like this you're probably better off using an asp:HiddenField and setting the value, that will create an input type='hidden' that will be accessible through javascript.
Here you are trying to get txthiddenloccount control's value which hasn't rendered on the page because its visibility is false.
so first you have to check if it is null i.e you can write code like this.
var loccount='';
if(document.getElementById("ctl00_ContentPlaceHolder1_txthiddenloccount") != null)
{
loccount = document.getElementById("ctl00_ContentPlaceHolder1_txthiddenloccount").value;
}
If the Visible property of the control is set as false via ASP.NET, it will be part of the control tree but will never actually get rendered to the page. If it doesn't get rendered to the page, JavaScript can't access it.
If you want to hide it using ASP.NET, you could do it this way in C#...
txthiddenloccount.Style.Add("display", "none");
That will not prevent the control from rendering on the page AND it will use CSS to hide it. Alternatively, you could do this, but it might not be what you want, visually...
txthiddenloccount.Style.Add("visibility", "hidden");
Hope that helps.
So I now have the following jquery to hide or show a textbox based on specific values selected in a DropDownList. This works except that I need the first display of the popup to always be hidden. Since no index change was made in the drop down list, the following does not work for that. If I code it as visible="false", then it always stays hidden. How can I resolve this?
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION) {
$(".statusActionAmountCssClass").attr("disabled", false);
$(".statusActionAmountCssClass").show();
}
else {
$(".statusActionAmountCssClass").attr("disabled", true);
$(".statusActionAmountCssClass").hide();
}
});
}
</script>
Thank you,
Jim in Suwanee, GA
If you set
visible=false
.Net will not render it. You can do
style="display:none;"
and .Net will render the tag properly but CSS will hide it from the user.
Add the following to pageLoad function
function pageLoad(sender, args) {
$("input.statusActionAmountCssClass").hide();
.... rest of code .....
}
By the way, I would recommend using the selector $("input.statusActionAmountCssClass") to get a jQuery object containing a reference to your input, otherwise jQuery will search all elements to match the CSS class .statusActionAmountCssClass
EDIT:
Another change that could also be made is to use jQuery's data() to store the two global variables
$.data(window, "_CASE_RESERVE_ACTION","317");
$.data(window, "_LEGAL_RESERVE_ACTION","318");
then when you need them simply cache the value in a local variable inside the function
function someFunctionThatNeedsGlobalVariableValues() {
var caseReserveAction = $.data(window, "_CASE_RESERVE_ACTION");
var legalReserveAction = $.data(window, "_LEGAL_RESERVE_ACTION");
}
this way, the global namespace is not polluted. See this answer for more on data() command