I have an asp hidden Value field:
<asp:HiddenField Value="" ID="TitleViewerHiddenValue" OnValueChanged="TitleViewerHiddenValue_ValueChanged" />
I have a javascript event:
function setHiddenValue()
{
var x = document.getElementById('<%=TitleViewerHiddenValue.ClientID %>');
x.textcontent = "HELLO WORLD"; // I feel this is wrong
}
How do I fix the javascript function so i can set the value of the hidden field and trigger the OnValueChanged event on the server?
x.value
It's a form element, not a display element.
For triggering the change event, see How can I trigger an onchange event manually?
Though I think if you're doing all of this to trigger ASP's built in stuff, you're trying to build a house out of duct tape.
Related
HI so my JS skills are a little rusty but I'm trying to create a few functions so they work on the client side, rather than running server code, here's what I'm trying to do:
I have a drop down control, and a textbox. The textbox is depended on the value from down down and is disabled on page load.
i'm trying to call a function so if YES is selected from dropdown, the textbox will be enabled for text entry. Here's what I'm doing:
function DependentControlByDropDown(sender, Control, DependentControlID) {
try {
var senderControl = sender.selectedOptions[0].text;
var controlEnable = (senderControl == Control);
console.log(controlEnable);
var control = document.getElementById(DependentControlID); this gives me NULL if i do console.log(control)
DependentControlID.disabled = controlEnable; //controlEnable has a value of either TRUE or FALSE but it doesn't work on DependentControlID
}
catch (e) {
alert("DependentControlByDropDown : " + e.message);
}
}
I'm calling this in dropdown like so:
onchange="DependentControlByDropDown(this,'Yes','txtbox1')"
So what's happening here is I get the right value 'Yes', or 'No' I tested it with console.log. The problem is with the dependednt control. If I do console.log(DependentControlID) it is showing me the correct control, but when I try to disabled=false it doesn't work. I also tried document.getElementByID(DependentControlID).disabled=false but that doesn't work either. Any help?!
As we've deduced in the comments of your question, you're using ASP.NET.
This is extremely important to note, because ASP.NET overrides assigned IDs to ensure that they are unique. For example, if you were to do...
<asp:Textbox runat="server" id="txtbox1"></asp:Textbox>
...the rendered HTML may look something like (example)...
<input id="ctl00$MainContent$txtbox1">
Because of this, getElementById("txtbox1") doesn't find anything.
To prevent this from happening, you can add ClientIdMode="static" to your textbox:
<asp:Textbox runat="server" ClientIdMode="static" id="txtbox1"></asp:Textbox>
The rendered HTML will now be the following...
<input id="txtbox1">
NOTE: If you have more than one of these textboxes on the page, for example if you're using it in a GridView or a Repeater, do not use ClientIdMode="static"! It will create duplicate IDs, which are not valid.
The problem is that you were trying to access the textbox via it's ID as text. You need set the disabled attribute on it's node value, which you already have, i.e. control.
Additionally you were trying to set the textbox's disabled attribute to the same value as controlEnable. I've set it to the OPPOSITE of controlEnable
function DependentControlByDropDown(sender, Control, DependentControlID) {
try {
var senderControl = sender.selectedOptions[0].text;
var controlEnable = (senderControl == Control);
console.log('controlEnable',controlEnable);
console.log('DependentControlID', DependentControlID);
var control = document.getElementById(DependentControlID);
console.log('control', control);
control.disabled = !controlEnable;
} catch (e) {
alert("DependentControlByDropDown : " + e.message);
}
}
<input id="txtbox1" />
<select onchange="DependentControlByDropDown(this,'Yes','txtbox1')">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
I am trying to do what seems to be simple but am unable to accomplish
I am trying to set the value of a column after a row focus change in a grid to a hidden value in java script.
My imbedded javascript code:
function OnGridFocusedRowChanged() {
grdA.GetRowValues(grdA.GetFocusedRowIndex(), 'ClientID', OnGetRowValues);
}
function OnGetRowValues(values) {
//Set hidden value
document.getElementById('<%=hdnClientID.ClientID%>').value = values[0];
//Fire button click
btnPopulateGrids_Click();
}
where hdnClientID is the name of my hidden field
In GridA I have the setting as such that OnGridFocusedRowChanged gets executed each time a row focus change takes place.
To this point, it works fine, the values[0] in OnGetRowValues() contains the correct value from the corresponding row in GridA.
But in the corresponding code behind, I cannot access the value from hidden field hdnClientID. Always comes up null when accessing
Current_Client_ID = CInt(hdnClientID.Value);
cannot access or convert any value from
hdnClientID.ClientID.
either.
I'm missing something simple.
I had to complete a similar task recently and I too was unable to access the value from codebehind. I researched and found out that it is not that simple and that you can't do it with javascript. What I would recommend is to check if you have jQuery installed and if you do, change your function to this:
function OnGetRowValues(values) {
//Set hidden value
$('#<%=hdnClientID.ClientID%>').val(values[0]);
//Fire button click
btnPopulateGrids_Click();
//If you change your HiddenField to have OnValueChange event, you can trigger it with this
//__doPostBack('<%= CompanyCode.ClientID %>', '');
}
Also, I guess you are firing some function from code behind with btnPopulateGrids_Click();.
I would recommend adding OnValueChanged="hdnClientID_OnValueChanged"/> to your <asp:HiddenField/> and using my supplied function triggering method.
If the view (e.g the value in a text input) is changed by an external javascript, it will not be reflected in the model.
How can I trigger a model update (to read back all binding values from the view).
P.S: for some reasons, manually setting the model value is not an option for me, I just need to call the same function that is called when user is typing in the text box.
If you are changing the value of an element, for example input, that uses ng-model it should suffice to trigger the element's 'change' event.
jQuery:
$('#input').val('new value').trigger('change');
No jQuery:
var input = document.querySelector('#input');
input.value = 'new value';
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
input.dispatchEvent(event);
Demo: http://plnkr.co/edit/IFb8OmegaGAAniy9ttn5?p=preview
I have several different scenarios, all with different longitudes and latitudes (and other data, but that's beside the point) in JSON. I am parsing the JSON ok, and have been able to get the desired values. What I would like to do is transfer these values to the CodeBehind.
What I am doing so far is something like this:
This is the responsible script:
function getScenarioDetails(json) {
$("#Welcome").text("Welcome user " + json.user);
$("#longitude").val(json.current_loc.lon).change();
$("#latitude").val(json.current_loc.lat).change();
}
And these are the hidden fields:
<form runat="server">
<asp:HiddenField runat="server" id="longitude" OnValueChanged="valueChanged" />
<asp:HiddenField runat="server" id="latitude" OnValueChanged="valueChanged" />
</form>
I realise that the value is being changed. But something is going wrong with the OnValueChanged as it is not firing. What exactly am I doing wrong?
I will try to explain this, First the client id is generated based on the NamingContainer parents so if your hidden fields are nested in a container you should use the property ClientIDMode and set the value to Static to ensure the client id is the same in your script.
The ValueChange event is fired when a control cause a postback so if you put a button that has the onclick event it cause a postack and the ASP.Net lifecycle starts executing the ValueChange event for your hidden inputs, Some controls as DropDownList has a property AutoPostBack when it set to true it makes a postback as soon the javascript change event happens, so it not wait until a postback occurs. The HiddeField doesn't have a AutoPostBack property so if you really need to postack after you change the values you could make a postback so:
function getScenarioDetails(json) {
$("#Welcome").text("Welcome user " + json.user);
$("#longitude").val(json.current_loc.lon);
__doPostBack('longitude', '');
.....
}
I have a series of textboxes on a form. When the user inserts numbers into these textboxes, calculations are made and <asp:Label> controls are updated via JavaScript to reflect these calculations:
document.getElementById('<%=TotalLoans.ClientID %>').innerHTML = TotalLoans;
This correctly updates the UI. However, when I try to access the value in the codebehind, the Text property is empty. This makes sense I guess, since I was updating the innerHTML property via the JavaScript.
//TotalLoans.Text will always be equal to "" in this scenario
double bTotalLoans = string.IsNullOrEmpty(TotalLoans.Text)
? 0.00
: Convert.ToDouble(TotalLoans.Text);
How do I update the Text property of the <asp:Label> via JavaScript in such a way that I can read the property in the codebehind?
Update
This is a small problem on a large form that contains 41 labels, each of which displays the results of some calculation for the user. Taking the advice of FishBasketGordo I converted my <asp:Label> to a disabled <asp:TextBox>. I'm setting the value of the new textbox as such:
document.getElementById('<%=TotalLoans.ClientID %>').value = TotalLoans;
Again, in the codebehind, the value of TotalLoans.Text is always equal to "".
I don't mind changing how I approach this, but here's the crux of the matter.
I am using JavaScript to manipulate the property values of some controls. I need to be able to access these manipulated values from the code behind when 'Submit' is clicked.
Any advice how I can go about this?
Update 2
Regarding the answer by #James Johnson, I am not able to retrieve the value using .innerText property as suggested. I have EnableViewState set to true on the <asp:Label>. Is there something else I am missing?
I don't understand why, when I type in a textbox and submit the form, I can access the value in the codebehind, but when I programmatically change the text of a textbox or label by way of JavaScript, I cannot access the new value.
Place HiddenField Control in your Form.
<asp:HiddenField ID="hidden" runat="server" />
Create a Property in the Form
protected String LabelProperty
{
get
{
return hidden.Value;
}
set
{
hidden.Value = value;
}
}
Update the Hidden Field value from JavaScript
<script>
function UpdateControl() {
document.getElementById('<%=hidden.ClientID %>').value = '12';
}
</script>
Now you can access the Property directly across the Postback. The Label Control updated value will be Lost across PostBack in case it is being used directly in code behind .
This one Works for me with asp label control.
function changeEmaillbl() {
if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
}
}
Use the following code
<span id="sptext" runat="server"></span>
Java Script
document.getElementById('<%=sptext'%>).innerHTML='change text';
C#
sptext.innerHTML
Instead of using a Label use a text input:
<script type="text/javascript">
onChange = function(ctrl) {
var txt = document.getElementById("<%= txtResult.ClientID %>");
if (txt){
txt.value = ctrl.value;
}
}
</script>
<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />
<!-- pseudo label that will survive postback -->
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />
<asp:Button ID="btnTest" runat="server" Text="Test" />
Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.
So, either use ajax and sent value of label to code behind. You can use PageMethods , or simply post the page to server where codebehind lives, so codebehind can know the updated value :)
Since you have updated your label client side, you'll need a post-back in order for you're server side code to reflect the changes.
If you do not know how to do this, here is how I've gone about it in the past.
Create a hidden field:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
Create a button that has both client side and server side functions attached to it. You're client side function will populate your hidden field, and the server side will read it. Be sure you're client side is being called first.
<asp:Button ID="_Submit" runat="server" Text="Submit Button" OnClientClick="TestSubmit();" OnClick="_Submit_Click" />
Javascript Client Side Function:
function TestSubmit() {
try {
var message = "Message to Pass";
document.getElementById('__EVENTTARGET').value = message;
} catch (err) {
alert(err.message);
}
}
C# Server Side Function
protected void _Submit_Click(object sender, EventArgs e)
{
// Hidden Value after postback
string hiddenVal= Request.Form["__EVENTTARGET"];
}
Hope this helps!
The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.
I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:
You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.