Unable to get value Textbox by id in javascript - c#

I have text boxes and it has values let say. I am calling my javascript method on one of textbox 'onblur'. my function is:
function CalculateExpectedProductPrice() {
alert("hi i called");
var originalPrice = document.getElementById('hdnSelectedProductPrice').value;
var numberOfLicenses = document.getElementById('txtNumberOfLicense').value;
var enteredAmount = document.getElementById('txtAmount').value;
alert(originalPrice);
alert(numberOfLicenses);
alert(enteredAmount);
}
i am getting alert message as ""hi i called". but not further.
But some i am not getting values of these controls.
*Edited:* My HTML is :
<asp:HiddenField ID="hdnSelectedProductPrice" runat="server" />
<asp:TextBox ID="txtAmount" runat="server" Width="250px"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtNumberOfLicense" runat="server" Width="35px" ></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtNumberOfLicense" EventName="" />
</Triggers>
</asp:UpdatePanel>
Will there any impact master-content page . because script is in content page and html also on same content page.Also let me know you, I am using wizard control where as all these controls are resides on second step of wizard. will that make any impact ?
Edited:
I think wizard control making here matter. As i started my firebug and review the generated html it assign the Id dynamically to those controls which are inside the wizard. thats why javascript unable to find the expected control .
eg for txtAmount text box which is inside the wizard control getting name as :
ctl00_ContentPlaceHolder1_Wizard1_txtAmount
but certainly i would not prefer to use this generated Id. So is there any remedy to find control inside the wizard control and get - set values ?

get id of the control as shown below
var enteredAmount = document.getElementById('<%=txtAmount.ClientId%>').value;

It's impossible to say for certain with your not having quoted your HTML (!), but the usual reason for this is confusion between the id and name attributes. document.getElementById works with the id attribute, but people tend to think it works with the name on input fields, which it doesn't (except for on IE, where getElementById is broken).
(The other thing to remember is that id values must be unique on the entire page, but looking at the IDs you quoted, I suspect you're okay on that front.)
Update: It works if you use ids:
HTML:
<form>
<input type='hidden' id='hdnSelectedProductPrice' value='10'>
<input type='text' id='txtNumberOfLicense' value='2'>
<input type='text' id='txtAmount' value='3'>
<br><input type='button' id='theButton' value='Click Me'>
</form>
Live copy

As T.J. mentioned we really need to see your html code, without seeing it it could be that you are looking for an elements attributes.
So lookup the element as you are already with
var element = document.getElementById('product');
Once you have the element you can query its attributes
var price = element.getAttribute('price');

If its "ASP.net server control" then you will have to do it like this:
var originalPrice = document.getElementById('<%=hdnSelectedProductPrice.ClientID %>').value;

if you use Asp.Net 4.0 and your textbox is unique on the entirepage you can add ClientIDMode="Static" in attribute of your textbox
<asp:TextBox ID="txtAmount" runat="server" Width="250px" ClientIDMode="Static"></asp:TextBox>

Related

Can't get text with text box when it is readonly?

I have a text box
<asp:textbox runat="server" id="checkIn" ClientIDMode="Static" ReadOnly="true">
</asp:textbox>
The text in the text box is inputted through a Jquery DatePicker. In some code behind I am getting the text from this text box like so.
string x=checkIn.Text;
Why can I not pull the inputted date from the text box? I am guessing it is to do with the fact that it is readonly as when I remove this it works?
Can anyone help me?
In ASP.Net, if the readonly value is changed, it will revert to the original value on the postback.
You can use a wrokaround however, instead of specifying readonly declaratively, assign it as an attribute in code-behind. i.e.
instead of
<asp:textbox runat="server" id="checkIn" ReadOnly="true"...
apply this is code-behind
checkIn.Attributes.Add("readonly", "readonly");
But, the viewstate still may not work with this.
More info:
There is a subtle difference between readonly and disabled controls in HTML. The disabled ones will not be submitted with the form, however the readonly ones will. Literally, readonly is just readonly, but disabled is actually disabled.
From W3C: http://www.w3.org/TR/html401/interact/forms.html#h-17.12
(Get down to section 17.13.2 Successful controls under 17.13 Form submission)
ASP.Net however, reverts to the original value on postback if a control is declared like that i.e. if the attribute is set during init. Which is why setting the attribute later (in page load) will not affect this behavior.
Use HTML input tag instead of asp:textbox
Use this:-
<input type="text" readonly="readonly" runat="server" id="checkIn" clientidmode="Static"/>
Instead of this:-
<asp:textbox runat="server" id="checkIn" ClientIDMode="Static" ReadOnly="true"></asp:textbox>
Write the following code in your code behind file, for asp.net .cs or class file and for vb in .vb file.
You will have to write it on page load event, depending on if you want it before postback or after or irrespective of both...
textbox.Attributes.Add("readonly", "readonly");
Try to make readonly to false before posting the values through jQuery or Java-Script. It should work.
$('#tbox').removeAttr('readonly');
Suppose I have a asp:button then on client click I need to call a function which remove the read-only attribute from the text-box.
<asp:Button ID="MessageButton" runat="server" Text="Hellow"
OnClientClick="return changeAttribute()" />
<asp:textbox runat="server" id="checkIn" ClientIDMode="Static" ReadOnly="true">
</asp:textbox>
and change attribute function in javascript as follows
function changeAttribute()
{
$('#checkIn').removeAttr('readonly');
return true;
}
You can also leave the readOnly attribute off in the asp:TextBox control and use jquery $('#textbox').attr('readOnly','readOnly').
You can actually get the value of a readonly textbox if it is within the form.
var text = Page.Request.Form[TextBox.UniqueID];
Sorry this response is a few years late!
Apply in asp.cs Page : AttrName.Attributes.Add("readonly", "readonly");
Please use:
Request.Form[txtText.UniqueID]
I had the same issue with jQuery, however fixed with a trick:
$('#txtBoxID').removeAttr('readonly');
/// Do your stuff here..
$('#txtBoxID').add('readonly');
;)

How to reference code behind variable in ASPX?

I'm not sure why when referencing a code behind variable in an asp.net control, I get the text of the reference:
<%=this.Person.Contact.Emails[0].EmailAddress%>
This outputs the literal reference text:
<asp:TextBox ID="EmailAddress" runat="server" Text="<%=this.Person.Contact.Emails[0].EmailAddress%>"></asp:TextBox>
This renders the variable value:
<input id="testfield" type="text" value="<%=this.Person.Contact.Emails[0].EmailAddress%>" />
Any ideas how I can get the variable value in the asp.net control?
You could say:
EmailAddress.Text = this.Person.Contact.Emails[0].EmailAddress
in your code behind
I prefer the solution in Code Behind in hunter's solution but another option would be to use data binding with #:
<asp:TextBox ID="EmailAddress" runat="server" Text="<%# this.Person.Contact.Emails[0].EmailAddress%>" />
But then you have to bind the server control in code-behind:
EmailAdress.DataBind();
The = sign is like a call to Response.Write() at this place and just outputs whatever follows as text.

Show confirmation textbox after entry with JavaScript

Before we begin, I would like to convey that I have limited to no knowledge on the JavaScript language. The only things I've used is JQueryUI - and even that is copy paste.
Currently, I have a user registration page, with all the standard TextBox inputs. I would like to, however, slide down a secondary 'Confirm email' and 'confirm password' whenever a user enters text into the original text box.
I understand the community likes to help those who can prove they helped themselves, but the only thing I currently have to show is me trying to lookup solutions for this and failing.
Could someone please show me a way to do this?
Edit: Code of the password box
<div class="ctrlHolder">
<asp:Label ID="Label9" runat="server" Font-Bold="True" Text="Password"></asp:Label>
<asp:Label ID="Label11" runat="server" CssClass="styleLabelWatermarkWashout" Text="**********"></asp:Label>
<br />
<%--data-default-value="Placeholder text"--%>
<asp:TextBox ID="txtRegisterPassword" runat="server" CssClass="textInput styleTextBoxCenter required"
TextMode="Password" MaxLength="20"></asp:TextBox>
</div>
So, assuming you can create markup similar to this:
<div class="ctrlHolder">
<asp:Label ID="PasswordLabel" runat="server" Font-Bold="True" Text="Password"></asp:Label>
<asp:Label ID="Label11" runat="server" CssClass="styleLabelWatermarkWashout" Text="**********"></asp:Label>
<br />
<%--data-default-value="Placeholder text"--%>
<asp:TextBox ID="txtRegisterPassword" runat="server" CssClass="textInput styleTextBoxCenter required" TextMode="Password" MaxLength="20"></asp:TextBox>
</div>
<div id="confirm-password-box" class="ctrlHolder">
<asp:Label ID="ConfirmPasswordLabel" runat="server" Font-Bold="True" Text="Confirm Password"></asp:Label>
<asp:Label ID="Label12" runat="server" CssClass="styleLabelWatermarkWashout" Text="**********"></asp:Label>
<br />
<%--data-default-value="Placeholder text"--%>
<asp:TextBox ID="txtConfirmRegisterPassword" runat="server" CssClass="textInput styleTextBoxCenter required" TextMode="Password" MaxLength="20"></asp:TextBox>
</div>
You'd want to add some CSS rules to make #confirm-password-box hidden by default. Then, add this script code somewhere on the page (preferably as close to closing </body> tag as possible):
<script>
$(function(){
$('#<%: txtRegisterPassword.ClientID %>').on('blur', function(event){
$('#confirm-password-box').slideToggle('slow');
});
});
</script>
The blur event occurs when the control loses focus. You don't really want to listen for keyup, since that would require this code being called every time a user entered a character into the password box...
Note that this particular chunk of jQuery code requires jQuery 1.7 or higher, so use NuGet to update your script reference (if you're not using anything else that requires an older version of jQuery).
I would add a reference to jquery to the page you are working on.
Then make a new script (on the page or in a separate .js file) which attaches a new function to the onkeyup event for the textboxes. Something like this.
$(document).ready(function()
{
$('mytextbox').bind('keyup', function() {
$('myCOnfirmationTextbox').slideDown();
};
});
This will attach this function to all elements corresponding to the "mytextbox" class or ID. So if you have an input <input type="text" id="email" class="emailInput"/> then you would use $('#email') to bind the event to this particular element. Or you use $('.Emailinput') to bind to all input elements for emails.
By the way, I haven't tested the code, but this or something very similar should work.
If you use a separate .js file, then don't forget to reference it in your page as well.
You can use innerHTML to have a new textbox beneath the email textbox once that box is filled. I could give you the code if you can post the code over here
Replace the controls ids in this answer as per your html.
You can show the confirm controls in the following way.
$('#password').onfocusout(function() {
// This will show once you complete entering Email and Password.
$('#confirmEmail').attr('display', 'inline');
$('#confirmPassword').attr('display', 'inline');
});
Let me tell how you can achieve confirm Email. Same thing can be used to achieve confirm password.
When you focus out of confirm email textbox compare the emails entered by the user in Email and Confirm Email textboxex.
This can be done in following way
$('#confirmEmail').onfocusout(function() {
if($('#confirmEmail').val() == $('#Email').val())
{
// Emails entered are same
}
else
{
alert('Emails entered are not matching. Please reenter emails.');
}
});
Similarly you can check for confirm password.

HTML Select items count in asp.net

Hi I've an HTML select control in my ASP.NET page and I made it as runat = "server" and now I tried to add some list items to it dynamically. something like below code
var list = document.getElementById('<%=list1.ClientID%>');
var newListItem = document.createElement('OPTION');
newListItem.text = "Emp1";
newListItem.value = "e101";
list.add(newListItem);
<asp:Panel ID="pnlemp" runat="server"
Style="display: none;"
CssClass="modalPopup"
width="700px" Height="350px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<select id="list1" multiple="true" name="list1" runat="server">
</select>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
and now when I try to access this from my code like list1.Items.Count it is showing 0.
Anything wrong in this?
Thanks in advance
When you modify the html in a client side script, the viewstate (which keeps track of all the controls) doesn't update . That results in that when you make a postback the new items isn't "there" .
Sometimes there's a __doPostBack() javascript which forces a postback, but I'm not sure it'll work .
For solution to this problem either add items dynamically through server side code or
dont bring server side into the picture and handle everything via javascript.
Items added via javascript will not be persisted by asp.net. further more you may recieve a "Invalid Callback or PostBack Argument" Exception for the same because it will not understand from where these listitems(options) have been added in the Select.

Adding Hyperlinks to ValidationSummary

I have a long form for my users to fill out. Is there a way to hyperlink the error message in ValidationSummary to the specific text field?
The easiest way to do this is with straightforward HTML anchor tags <a>, you can include the HTML in the ErrorMessage property of your validation control which will be displayed in your ValidationSummary control. For examples
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Button ID="Button5" runat="server" Text="Submit" />
<br />
<div style="height:800px"></div>
<a name="TextBox1"></a>
Required Field
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Required Field is Required <a href='#TextBox1'>Click Here To Go To</a>"
Text="***"
ControlToValidate="TextBox1" />
A more elegant approach would be to combine the above approach with jQuery using the scrollTo function and perhaps highlighting the field. You can include this jQuery/Javascript code in the onclick property of the anchor tag.
I've implemented this before in the same way #jdmonty had suggested - by adding the anchor tags to each RFV's ErrorMessage attribute. Eventually I found this too tedious so I drummed up some jQuery to do the work for me. This snippet will wrap your validation messages in anchor tags with the href=#targetControl, which of course when clicked scrolls to the target input.
Add this to the $(document).ready(); portion of your script code.
var validators = Page_Validators; // returns collection of validators on page
$(validators).each(function () {
//get target control and current error validation message from each validator
var errorMsg = $(this).context.errormessage;
var targetControl = $(this).context.controltovalidate;
var errorMsgWithLink = "<a href='#" + targetControl + "'> " + errorMsg + "</a>";
//update error message with anchor tag
$(this).context.errormessage = errorMsgWithLink;
});
You could add some additional jQuery as #jdmonty suggested to smooth the scrolling. You can also use the css pseudo class ':focus' in your style sheet to add styles for 'active' input textboxes, something like input[type=text]:focus{background-color:red;} to really accentuate when they are focused.
P.S. I know this question is old but I just found it today while seeing if anyone had come up with a more elegant solution, so for anyone else in my shoes, here ya go.

Categories

Resources