Get/Set asp:textbox values from javascript - javascript

I'm not super familiar with javascript but I'm working on it, I'm trying to do a "same as billing address" type checkbox to fill some textboxes on the same form with data from other textboxes. I found a few solutions online but they weren't working for me. I'm probably overlooking something simple, but I've tried quite a few. Here's what I currently have:
function AutoFillBilling()
{
var text = document.getElementById("CustContact").Value;
alert(text);
}
The alert pops up, but just says undefined, I also tried $("#CustContact").Value to no avail. Below is the textbox I'm trying to access
<asp:Textbox runat="server" ID="CustContact" ClientIDMode="Static" type="text" placeholder="Contact" class="required"/>
What am I missing?

Properties begin with lowercase letters in JavaScript:
var text = document.getElementById("CustContact").value;
Additionally, while the ClientIDMode="Static" certainly should be explicitly setting the client-side id property, when debugging you may want to examine the HTML just to make sure. When using JavaScript, looking only at your server-side markup leaves you unnecessarily blind.

You can use it as such
<asp:CheckBox ID="Postal_Same_As_PermCheckBox" runat="server" onclick="copyPermAddress(this);" />
And JavaScript as
<script type="text/javascript">
function copyPermAddress(e) {
if (e.checked) {
document.getElementById('Postal_Adrs_Line_1TextBox').value = document.getElementById('Perm_Adrs_Line_1TextBox').value;
document.getElementById('Postal_City_VillageTextBox').value = document.getElementById('Perm_City_VillageTextBox').value;
} else {
document.getElementById("Postal_Adrs_Line_1TextBox").removeAttribute('readonly', 'readonly');
document.getElementById("Postal_City_VillageTextBox").removeAttribute('readonly', 'readonly');
}
}
In this example I am assuming that you are using client id mode as static on the controls mentioned in the JavaScript, if it is not then you may use <%# xxxx.ClientID%> blocks to access their IDs

Related

Create a checkbox when checked it should show certain input fields & hide other input fields, within a Modal

<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal" onclick=" if ($(this).is(':checked')) { console.log('Worky'); $('#ShowIfChecked').show(); $('#HideIfChecked').hide(); } else { $('#HideIfChecked').show(); console.log("No Worky"); }" />
I've been attempting to do this with jQuery, but it hasn't been functioning properly, I have also done a thorough amount of research for ways to condense this code. I was trying to condense the statement with a ternary operator. If you could please assist me with a possible solution that would be great! Thanks (Ternary Solution would be amazing)
The issue with your code is that you have mis-matched quotes in the HTML due to the console.log("X") calls in your code that is messing up the attributes of the input element. If you check the console you'll most likely see some errors relating to this.
It's for this reason, amongst many others, that it's considered bad practice to use inline script (or CSS styling for that matter). The other issues are that it's bad for separation of concerns and makes the code harder to read an edit. It's far better practice to attach your event handlers using unobtrusive Javascript, like this:
$('.seasonal-checkbox').change(function() {
$('#ShowIfChecked').toggle(this.checked);
$('#HideIfChecked').toggle(!this.checked);
});
#ShowIfChecked {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal" class="seasonal-checkbox" />
<div id="ShowIfChecked">Checked!</div>
<div id="HideIfChecked">Not Checked!</div>
Note the use of the change event over click, so that the event is still fired for user who navigate the web using the keyboard. Also note the simplified logic using toggle() to hide and show the relevant content in a single call to each method which negates the need for an if statement - and by proxy a ternary expression too.
You can change your onclick to a function, because at least for me, it is easier to see whats really going on.
So change
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal"
onclick=" if ($(this).is(':checked')) { console.log('Worky'); $('#ShowIfChecked').show(); $('#HideIfChecked').hide(); }
else { $('#HideIfChecked').show(); console.log("No Worky"); }" />
to
<input type="checkbox" runat="server"
name="Seasonal" value="Seasonal" id="isASeasonal" onclick="myFuncton(this)" />
Within your view:
<script>
myFunction(myCheckBox)
{
if(myCheckBox.Checked)
{
console.log('Worky');
$('#ShowIfChecked').show();
$('#HideIfChecked').hide();
}
else
{
$('#HideIfChecked').show(); console.log("No Worky");
}
}
</script>
Now to get the expression/Ternary Solution you want, you can change this script to look like this:
<script>
myFunction(myCheckBox)
{
myCheckBox.Checked ? (console.log('Worky'), $('#ShowIfChecked').show(),
$('#HideIfChecked').hide()); : ($('#HideIfChecked').show(), console.log("No Worky"));
}
</script>
You can find more Info about Ternary Solutions here
We dont write code like this. It fails on every code review.
Do this:
$('#isASeasonal').click(function() { ...});
https://api.jquery.com/click/
Seasonal Address:&nbsp <input type="checkbox" runat="server" clientidmode="Static" name="Seasonal" value="Seasonal" id="isASeasonal"/>
$('#ShowIfChecked').hide(); //Hid What needs to be shown if checked.
$("#isASeasonal").click(function () { //Used Click event on checkBox
($("#isASeasonal").is(':checked')) ? (console.log('worky'), $('#ShowIfChecked').show(), $('#HideIfChecked').hide()) : (console.log('no worky'), $('#HideIfChecked').show(), $('#ShowIfChecked').hide());
What fixed my issue was that in ASP.net I needed to add clientidmode="static" to the div's that I was trying to hide & show. I still don't understand the reason why, I'm currently looking more into it but this is what worked for me but above you can see the majority of the final product with the ternary operator!! Yay.

setting asp:RadioButton Text from javascript

I am having the following Radio butttons in my aspx file.
<asp:RadioButton ID="rdoOption1" runat="server" GroupName="grpAnswers"/>
<asp:RadioButton ID="rdoOption2" runat="server" GroupName="grpAnswers"/>
<asp:RadioButton ID="rdoOption3" runat="server" GroupName="grpAnswers"/>
<asp:RadioButton ID="rdoOption4" runat="server" GroupName="grpAnswers"/>
I want to set the text from javascript on a button's click.
Javascript code is as follows.
document.getElementById("rdoOption1").innerHTML = "sometext";
I've also tried with Text,nodevalue instead of innerHTML, no use. Plz help.
You need to use ClientID in javascript instead of using the server side id. As the server side id is changed when html is generated by asp.net. You also have : instead of semi colon at the end of javascript statement. Use value instead of innerHTML as that is not for input html elements.
document.getElementById("<%= rdoOption1.ClientID %>").value = "sometext";
If you have .Net Framework 4 and above then you can use Control.ClientIDMode="static" to keep the server id on the client side.
Edit The second thing you have to take care is to make sure the html element you are trying to access is already added to DOM. You can do this by putting the script after the html elements you are trying to access. The best place would be just before the ending body tag </body>
<script type="text/javascript>
document.getElementById("rdoOption1").innerHTML = "sometext";
</script>
</body>
Atlast I've found the solution for this.
Actually the asp:RadioButton is rendering in the browser as follows,
<input name="grpAnswers" id="rdoOption1" type="radio" value="rdoOption1"/>
<label for="rdoOption1">
Note: It'll generate label only if you specify some value for Text property of the asp:RadioButton.
So ,I have changed my code as follows,
<asp:RadioButton ID="rdoOption1" runat="server" GroupName="grpAnswers" Text=" "/>
My Javascript code to set Text for that asp:RadioButton is as follows,
document.getElementById("rdoOption1").nextSibling.innerHTML = "someText";
This one worked for me.Thanks to all those who spent their valuable time in answering my question. :)
ASP.Net controls are server side controls and not client side controls like HTML.
Their actual ID's get generated during the run time not before hand.
So, your syntax should be some thing like:
document.getElementById("<%= rdoOption1.ClientID %>").innerHTML = "sometext";
Check out this post: how-to-change-the-text-of-a-radio-button.
I don't think you can change the text using innerText of a radio button.

Javascript returns undefined with asp.net master pages

I'm running into a bit of an issue. My JavaScript function returns "undefined" when using master pages. However, when I'm not using master pages, it works fine. Here is my code:
HTML:
<input id="txtPhoneNumberAreaCode" class="TextBox" runat="server" type="text" onkeyup="GoToNextTextBox(this.id, 3, 'cphMainArea_txtPhoneNumberFirstThree')" />
The Javascript:
function GoToNextTextBox(CurrentTextBox, MaxCharLength, NextTextBox) {
alert(CurrentTextBox.value);//pops up "undefined"
if (CurrentTextBox.value.length == MaxCharLength) {
NextTextBox.focus();
NextTextBox.style.backgroundColor = '#FFFFFF';
}
Again, this works fine when not using master pages. So I'm completely confused.
This is because, you are doing it wrong.
In GoToNextTextBox(), you are expecting a DOM element, but you are passing only its id.
DO this:
<input id="txtPhoneNumberAreaCode" class="TextBox" runat="server" type="text"
onkeyup="GoToNextTextBox(this, 3, 'cphMainArea_txtPhoneNumberFirstThree')" />
When using master pages and user controls the rendered ID of your controls change, but there is a way to stop it.
Let's say you have a Textbox
<asp:Textbox id="txtName" runat="server"></asp:Textbox>
on a standard asp page, it's id will be as you expect, txtName
Now you add a master page, called Site.Master. In your rendered html, the controls name is now different.
cntl1_Site_txtName
I might have the syntax of the new name a bit off, but you can view source and find it for yourself.
There is a way to control that though. There is a property on your page, ClientIDMode.
If i remember correctly it has 3 or 4 options. Auto ID is default I believe.
If you set it to static for that page, then you will no longer get the verbose control IDs, they will be as you expect.
This can be a downfall when using things like Repeaters though. You will not have easy access to specific fields if they do not have the verbose ID

How Do I Pass ASP.NET Control Name to Javascript Function?

I have Googled this to death and found lots of 'answers', but none of them will work for me, so maybe you clever people could give me a 'definitive' answer?
I have a Javascript function:
function enableSaveLink() {
document.getElementById('<%= btnSaveLink.ClientID %>').removeAttribute('disabled');
}
This works fine, but obviously it is hard-coded to enable a particular control on my page. What I'd like is to be able to call this function from any control on the page, passing the name of the control I'd like to enable as a variable. So, in an ideal world, my Javascript function would look like this:
function enableControl(ctl) {
document.getElementById(ctl).removeAttribute('disabled');
}
And I'd call it like this:
<asp:button id="btnTestButton" runat="server" Text="Click Me" onclientclick="enableControl('txtTestTextbox') />
<asp:button id="txtTestTextbox" runat="server" enabled="false />
I know the way I've passed the control name would never work, but I've tried passing it in all different ways and none work, so this is just for the purposes of illustration. Can anyone tell me how to actually make this work?
You need to use the ClientID property of the control.
This will help:
<asp:button id="btnTest" runat="server" Text="Click Me"
onclientclick="enableControl('<%= lblTest.ClientID %>') />
Use the this reference (more info here):
<asp:button id="btnTest" runat="server" Text="Click Me" onclientclick="enableControl(this);" />
Then in your script:
function enableSaveLink(elem) {
elem.removeAttribute('disabled');
}
Here you are passing a reference to the object calling the function to the function, you can then just set the attribute on the element rather than finding it in the DOM.
EDIT - Just realised what your intended usage is. If you're looking to fire an event from a disabled element when clicked, then you can't do this from the element. It would need to be handled from some other enabled element. The above method works fine if you intend to disable the element when clicked - but not enable the element when clicked.
EDIT - Just to accompany my comment, if you have a uniform structure like this (i.e. where all inputs have a corresponding label - or even button) then:
<div>
<label onclick="activateSibling(this);">Input One:</label>
<input type="text" />
</div>
You could try this:
function activateSibling(label) {
label.nextSibling.removeAttribute("disabled");
}
I've made a jsFiddle demonstrating my concept in jQuery which seems to work fine.
EDIT - OK, last idea. What about custom attributes. You could add a target attribute to your clickable element which contains the Id you're going to enable, like so:
<label target="active_me" onclick="activate(this);">Click to activate</label>
<input type="text" id="active_me" disabled="disabled" />
And your script:
function activate(label) {
var inputId = this.getAttribute("target");
var input = document.getElementById(inputId);
input.removeAttribute("disabled");
}
Although, it's starting to feel like we're fighting against the technology a little and we're not too far removed from ctrlInput.ClientID. But I suppose this makes your markup a little cleaner and gives you a function that's bindable en masse.
Ok, I've cracked it. There are probably more ways than one to do this, but this is fairly elegant.
My Javascript function:
function enableControl(ctl) {
document.getElementById(ctl).removeAttribute('disabled');
}
My ASP.NET markup:
<asp:Button ID="btnTestButton" runat="server" Text="Click to enable" OnClientClick="enableControl('txtTestTextbox');" />
<asp:TextBox ID="txtTestTextBox" runat="server" enabled="false" ClientIDMode="Static" />
The key is the ClientIDMode property, which, when set to static, means that the control's client-side ID when it is rendered will match the ID you give it in markup. If it's within a naming container you may need to include that in the variable passed in the function call. See here for more info about ClientIDMode.
Anyway, this works for me! Thanks for your input, everyone.
ClientID is used for getting server side control on javascript.
var element=document.getElementById('<%=lblTest.ClientID%>');

Editing a labels text value through JavaScript

I have a simple in VB/ASP.NET form containing two text boxes, I am attempting to apply some validation to the first text box using JavaScript. This is the first time I have attempted this and am having some trouble.
I have a label beside the text box stating an error, this labels visibility property is set to False. I wish the labels visibility to turn true if the text box is empty when the user loses focus.
For this I have used the onBlur option within the tags of the text box. It then calls the JavaScript function and should set the label to Visible but it does not. I have tested to see if it is entering the function by using an alert instead and that works. The problem seems to be trying to alter the visibility property of the label.
Here is the portion of my code:
The JavaScript:
function myRegEx(frm) {
if ( boxUsername.value == "" ) {
invalidUser.visible = True;
return false;
}
}
The form:
<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>
<asp:Label id="invalidUser" runat="server" visible="False" forecolor="Red" text="* Username must be alphanumeric with no special characters"></asp:Label>
Any help would be brilliant.
Here's another StackOverflow question that has the answer for you:
Change visibility of ASP.NET label with JavaScript
I suggest you use and ASP.Net Validation control, specifically the RequiredFieldValidator.
This will take care of the label for you, plus make certain the correct validation happens both client side (javascript) and server-side (vb).
You're using the deprecated IE-only feature that turns elements with IDs into global variables.
You should call document.getElemenntById instead.
Also, you need to use ASP.Net's generated client IDs.
Finally, to hide an element, you need to use CSS; HTML doesn't have a visible property.
For example:
document.getElementById("<%=invalidUser.ClientID %>").style.display = "none";
However, you should use ASP.Net's built-in validation feature instead.
Why not use an ASP.NET RequiredFieldValidator like so:
<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="boxUsername" Display="Dynamic" ErrorMessage="Please enter a value" />
If that is too simplistic then you can use a RegularExpressionValidator:
<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please enter alpha numeric characters." ValidationExpression="[my reg ex]" ControlToValidate="boxUsername" Display="Dynamic" />

Categories

Resources