hiding an asp.net generated <span> breaks my javascript form validation - c#

so I am using javascript to validate an address field simply to pull the zip code off the end.
I have two asp:Labels that I show and hide to inform the user. It works great, the labels show when needed and the validation works how I want it, the problem comse when I try to hide them. One of the labels shows and hides just fine, but whenever I try to hide the other the script breaks
<script>
function isvalid()
{
var zip = MainContent_tbx_Appt_Address.value.slice(-5);
if (zip == "") {
MainContent_lbl_Add_validate2.hidden = true;
MainContent_lbl_Add_Validate.hidden = false;
}
else if (!zip.match('[0-9]{5}')) {
//MainContent_lbl_Add_validate.hidden = true;
MainContent_lbl_Add_validate2.hidden = false;
}
else
{
//MainContent_lbl_Add_validate.hidden = true;
MainContent_lbl_Add_validate2.hidden = true;
}
}
</script>
<asp:Label ID="lbl_Add_Validate" style="z-index:100;" Name="lbl_Add_Validate" DataPoint="dp_Add_Validate" runat="server" hidden="true" Text="Address is required"></asp:Label>
<asp:Label ID="lbl_Add_validate2" style="z-index:100;" Name="lbl_Add_Validate2" DataPoint="dp_Add_Validate2" runat="server" hidden="true" Text="Invalid address format"></asp:Label>
<br />
<asp:TextBox ID="tbx_Appt_Address" onblur="isvalid()" style="z-index:100;" Name="tbx_Appt_Address" DataPoint="dp_Appt_Address" runat="server" Rows="4" TextMode="MultiLine" Height="65px" Width="200px" value="Address" onFocus="if (this.value == this.defaultValue) { this.value = ''; }" placeholder="Address">Address</asp:TextBox>
this is my code in my asp file and when it hits the client side it spits out this
<span id="MainContent_lbl_Add_Validate" name="lbl_Add_Validate" datapoint="dp_Add_Validate" hidden="true" style="z-index:100;">Address is required</span>
<span id="MainContent_lbl_Add_validate2" name="lbl_Add_Validate2" datapoint="dp_Add_Validate2" hidden="true" style="z-index:100;">Invalid address format</span>
<br/>
<textarea name="ctl00$MainContent$tbx_Appt_Address" rows="4" cols="20" id="MainContent_tbx_Appt_Address" datapoint="dp_Appt_Address" value="Address" onfocus="if (this.value == this.defaultValue) { this.value = ''; }" placeholder="Address" onblur="return isvalid()" style="height:65px;width:200px;z-index:100;">Address</textarea>
everything else works as long as I have MainContent_lbl_Add_validate.hidden = true; commented out, but if I have ether of them run it breaks

In aspx pages if you are not using jQuery, try to get elements using document.getElementById('MainContent_tbx_Appt_Address'), and if you are using microsoft ajax frameworks you can use $get('MainContent_lbl_Add_validate'), these are the right ways to refer elements on DOM.
Editing: ok, looking your code with more accuracy I saw that you made a mistake on span ids, specifically at 'V' char. Check the case on ids and your script will run.

If you hide an element that has "runat=server", you might think that ASP will render the control styled so that it is invisible-- meaning you can later unhide it using Javascript. That's not how it work. If you set hidden=true, the element isn't rendered at all. Your Javascript is gagging on the reference to the missing element and halting execution, so your valiator code doesn't ever get a chance to run.
To render a hidden element, mark it up like this:
<asp:Label ID="lbl_Add_Validate" style="z-index:100;" Name="lbl_Add_Validate" DataPoint="dp_Add_Validate" runat="server" style="visibility: hidden" Text="Address is required"></asp:Label>

Personally I would let JQuery handle this, which you can do in .aspx:
$(function () {
$('#tbx_Appt_Address').blur(function(){
var text_input = $('tbx_Appt_Address').val();
//additional logic with conditions
if (text_input=='')
{
$('lbl_Add_Validate').show();
}
//etc etc
});
});

Related

How to implement input checkbox's checked action?

In a WebForm I have an input checkbox to which I wanna apply server side action.
For example, when the checkbox is checked, I want to change some label's text.
I have tried to use on client side:
<input id="auto" name="auto" type="checkbox" data-toggle="toggle" data-on="AUTOMAT" data-off="MANUAL" <%= string.IsNullOrEmpty(Request["auto"]) ? string.Empty : "checked" %> />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<asp:HiddenField ID="customSwitch1Change" runat="server" Value="0" />
<script>
$('#auto').click(function () {
$('#<%=customSwitch1Change.ClientID%>').val("1");
$('#form1').submit();
});
</script>
I have used this and this for the input checkbox.
On the server-side I have tried:
protected void CustomSwitch1Change(string auto)
{
if (string.IsNullOrEmpty(auto))
{
Label3.Text = $"customSwitch1 was not checked.";
}
else
{
Label3.Text = $"customSwitch1 was checked and the check value is {auto}.";
}
}
But what I've tried is not working.
What I'm doing wrong? Or is there another way to do this?
You don't need the HiddenField. If you change the jQuery to the code below it will do a form post on CheckBox change.
<script>
$('#auto').change(function () {
$('#form1').submit();
});
</script>
Then you can simply get the value in code behind with
string auto = Request.Form["auto"];

Problems with setting the background of the whole website with a DropDownList

So here's the deal, I've got this DropDownList on my Login.aspx page, using that DropDown I'd like to set the background for the whole website. Having a MasterPage I just thought I should set the color of the body.
Here's my html for the <asp:DropDownList>:
<div class="col-sm-3 col-sm-offset-4" style="margin-bottom: 10px">
<div class="input-group input-group-sm">
<asp:Label runat="server" ID="lblColor" ClientIDMode="Static" AssociatedControlID="ddlColor" class="input-group-addon"><span class="glyphicon glyphicon-star"></span></asp:Label>
<%--Update Panel за цветовете--%>
<asp:UpdatePanel runat="server" ID="updateColor" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddlColor" style="width:100%" ClientIDMode="Static" AutoPostBack="true" OnSelectedIndexChanged="ddlColor_SelectedIndexChanged" aria-describedby="lbColor" data-taggle="dropdown" data-style="DropDownListHint-datastyle" class="btn dropdown-toggle DropDownListHint-datastyle">
<asp:ListItem Text="Бял" Value="White" Selected="True" />
<asp:ListItem Text="Зелен" Value="Green" />
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
There's 2 problem I'm experiencing.
1st one being that when I set the color of the body, after clicking on the Login button the color gets removed on the next page.
2nd one being that I can't get the page not to flash even when using an update panel.
Here's my C# code-behind.
protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
{
var body = Master.FindControl("bodyMasterPage") as HtmlGenericControl;
if (ddlColor.SelectedValue == "Green")
{
body.Style.Add("background-color", "#D2F6E2!important");
}
else if (ddlColor.SelectedValue == "White")
{
body.Style.Add("background-color", "#ccc!important");
}
updateColor.Update();
}
Any help would be greatly appreciated <3
I'll try to keep this as simple as possible. I would expect you to build off of the example below.
First, let's just build a simple <select>, like so:
<select id="ddlColor" class="form-control">
<option value="#d2f6e2">Бял</option>
<option value="#ccc">Зелен</option>
</select>
I've pulled the values from your code-behind, and we'll see why in a moment.
Second, let's build a jQuery event handler for when the select's value changes:
$('#ddlColor').on('change', function(e){
});
I'm assuming jQuery is available since I see Bootstrap CSS classes in your markup, which normally means you're also using bootstrap.js somewhere, which has jQuery as a dependency.
Third, we grab the select's selected value, and use the jQuery .css() function to apply your style to the body element:
$('#ddlColor').on('change', function(e){
var color = $(this).val();
$('body').css('background-color', color);
});
This goes anywhere in your page that you either already have scripts or you can add a script tag, as long as the script is after you've loaded jQuery.
As a note, the CSS function doesn't seem to like those !important modifiers, so I removed them. If you absolutely need them, I'd think about creating some classes for these colors instead, and use the addClass and removeClass functions instead.
Demo: https://jsfiddle.net/hfrjufto/
And a version that persists the value in localStorage: https://jsfiddle.net/hfrjufto/3/
if(!localStorage.getItem('bgcolor')) {
populateStorage();
} else {
setStyles();
}
function setStyles() {
var color = localStorage.getItem('bgcolor');
$('body').css('background-color', color);
}
function populateStorage() {
localStorage.setItem('bgcolor', $('#ddlColor').val());
setStyles();
}
$('#ddlColor').on('change', function(e) {
populateStorage();
});

Change Image Using Selection in Radio Button List

I have a project that has me a bit stomped on how to proceed in the manner I would like. On one ASP.net page, I have a form that uses a radio list for the selection options. Also, I have images to the right of the categories, which I would like to change when a particular radio value selection is made.
I have researched how to do this with a regular radio button control, but I cannot seem to get over the hump, as I'm using the ASP RadioList control, and I need guidance on why I cannot get the images to change with the following code:
<script type='text/javascript'>
$(document).ready(function () {
$("input:radio[name=option]").click(function () {
var value = $(this).val();
var image_name;
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
});
});
</script>
I'm using J-Query here, and my page doesn't blow up on load - yet when I select a value, the image doesn't change. As for the [name=option]
part of the code, I don't have name="option" in the HTML code source... I have the following:
<tr>
<td><input id="MainContent_CPUBuilderForm1_radCPUType_0" type="radio" name="ctl00$MainContent$CPUBuilderForm1$radCPUType" value="AMD" /><label for="MainContent_CPUBuilderForm1_radCPUType_0">AMD</label></td>
</tr>
Where name="ctl00$MainContent$CPUBuilderForm1$radCPUType" instead.
I've tried to insert this as a replacement for "option", but still no dice. Can someone help to evaluate what I'm doing wrong here? A million thanks! Cheers.
The problem that you're having is that you're not assigning the value of the image URI to the <img> tag. So you'll need to add something to the bottom of your function to make that assignment. Since you don't have that HTML in your question, I'll write my answer with the assumption that you have a tag in your code as such: <img id="changingImage" src="" alt="" />.
So just add this to your Javascript before your function closes out:
$('#changingImage').attr('src', '../Images/' + image_name);
That should get it to change the file for you, thought you may need to change the folder it's in per your configuration.
use this
HTML
<div>
<asp:RadioButtonList ID="RadioButtonTipoUser" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Value="1">Dome</asp:ListItem>
<asp:ListItem Value="amd">Emp</asp:ListItem>
<asp:ListItem Value="intel">intel</asp:ListItem>
</asp:RadioButtonList>
<asp:Image ID="img" runat="server" ImageUrl="~/Desert.jpg" />
</div>
JQUERY
$(document).ready(function () {
$('#RadioButtonTipoUser_1').on('change', function () {
if ($(this).is(':checked')) {
$('#img').attr('src', 'Chrysanthemum.jpg');
}
});
$('#RadioButtonTipoUser_2').on('change', function () {
if ($(this).is(':checked')) {
$('#img').attr('src', 'Desert.jpg');
}
});
});
</script>
Welcome to the wonderful world of ASP.net Web Forms Name/ID Mangling.
Update
Having dertermined that you are using an asp.net image tag. Note that you don't have to use an asp.net control for an image you could use a plain old HTML contol with an ID instead; this ID wouldn't get mangled. However I'll stick to the asp.net image control for now.
This requires your script to be on the page and not in a js file.
.aspx
<asp:RadioBUttonList ID="yourID" runat="server" />
<asp:Image ID="Image6" runat="server" ImageUrl="~/Images/Icon_CPU.jpg" />
javascript
$(document).ready(function () {
$("#<%= yourID.ClientID %> input").click(function () {
var value = $(this).val();
var image_name;
var image_path = "/Images/";
//If the images directory isn't at the website root you could use asp.nets
//resolveURL method instead
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
//console.log(image_name);
$("#<%= Image6.ClientID %>").attr('src', image_path + image_name);
});
});
The <% %> is a server code block and should be used sparingly in aspx pages. <%= %> is short hand for `<% Response.Write() %>. If you view the source code of the page you will see the ASP.net client ID of the Radio Button List & image controls in the jQuery selectors.
You should also use a tool like FireBug for Firefox or Chrome developer tools to check the paths for the image once you click the check boxes if you are getting unexpected results. Also note the line //console.log(image_name);. Removing comments form this line will dump the value of image_name to the console, which is useful for debugging. See more info here: http://blogs.msdn.com/b/cdndevs/archive/2011/05/26/console-log-say-goodbye-to-javascript-alerts-for-debugging.aspx
Previous Code below - Doesn't address updating the image
A hacky solution is to surround you radio button list with a div or better still a fieldset and give it an id:
<div id="listContainer">
<asp:RadioButtonList ID="yourID" runat="server" />
<div>
Now update your javascript to
$(document).ready(function () {
$("#listContainer input").click(function () {
var value = $(this).val();
var image_name;
if (value == 'AMD') {
image_name = "AMD_CPU_1.jpg";
} else {
if (value == 'Intel') {
image_name = "Intel_CPU_2.jpg";
} else {
image_name = "Icon_CPU.jpg";
}
}
});
});

how to get js POST in asp.net webform?

I know its a rudimentary questions, but I am out of practice on webforms. I am using Stripe.js for the first time, and want to use it in conjunction with stripe.net to process the client side. Here is the client code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="StripePage.aspx.cs" Inherits="StripePage.StripePage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
// This identifies your website in the createToken call below
// You need to put your real publish key here.
Stripe.setPublishableKey('pk_test_1nDJ3hA1Mv2Sy9bUoYcBMXmm');
// ...
// I am using jquery to process the payment. It knows what form to
// process it on based on the name 'payment-form'
jQuery(function ($) {
//payment submission
$('#payment-form').submit(function (event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
//if there is a error, it is displayed on the page if there was
//no error this is where it gets sent to the server.
var stripeResponseHandler = function (status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
});
</script>
<form method="POST" id="paymentForm" runat="server">
<span class="payment-errors" runat="server"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<br />
<input id="number" type="text" data-stripe="number" clientidmode="Static" />
<input type="text" size="20" data-stripe="number" runat="server" />
</label>
</div>
<div class="form-row">
<label>
<span>CVC</span>
<br />
<input type="text" size="4" data-stripe="cvc" runat="server" />
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<br />
<input type="text" size="2" data-stripe="exp-month" runat="server" />
</label>
<br />
<input type="text" size="4" data-stripe="exp-year" runat="server" />
</div>
<asp:Button ID="submit" ClientIDMode="Static" runat="server" Text="SubmitPayment" OnClick="submit_Click" />
</form>
</asp:Content>
The last call in JS creates a JSON object that I want to know how to get to on the C# page on the button click:
protected void submit_Click(object sender, EventArgs e)
{
....
}
I am wanting to do the javascript implementation to avoid having to do PCI compliance. Am I approaching this incorrectly? Should it be all Stripe.net to process everything, and skip the js entirely? Or if this is right, how can I get the form post data in the button click event?
Thanks for the tips in the comments. After much perusal of the internet and hair pulling, I walked away for a bit and came back with this solution.
Made the button just a standard html input (not the asp:Button)
Got the posted back information that was being sent via the JavaScript in the Page_Load event like so
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
StripeConfiguration.SetApiKey("[API Secret Key");
NameValueCollection nvc = Request.Form;
string amount = nvc["amount"];
var centsArray = amount.Split('.');
int dollarsInCents = Convert.ToInt32(centsArray[0]) * 100;
int remainingCents = Convert.ToInt32(centsArray[1]);
string tokenId = nvc["stripeToken"];
var tokenService = new StripeTokenService();
StripeToken stripeToken = tokenService.Get(tokenId);
var myCharge = new StripeChargeCreateOptions
{
TokenId = tokenId,
AmountInCents = dollarsInCents + remainingCents,
Currency = "usd"
};
var chargeService = new StripeChargeService();
StripeCharge stripeCharge = chargeService.Create(myCharge);
}
}
Seems like using the NameValueCollection (which lives in System.Collections.Specialized namespace) gave me the ability to grab what I needed from the Request.Form by pulling it out via variable name. Since I new the variable names, it was simply a matter of grabbing them and then following the Stripe .NET library documentation to get the token and process the payment.
I want to just post a comment to the answer, but I'm not allowed to yet. So, this isn't really an answer, more of a response to the OP's own findings.
I'm doing the exact same thing, using Stripe.js. I can simply grab stripeToken using Request.Form, and get all other non-c/c-related fields the usual way in the code-behind (e.g. int Total = PaymentTotal.Value;); but what I'm noting isn't so much about grabbing the data, it's that you have to handle it on Page_Load (or during some later point in the page life cycle), because the Submit button's onclick event is never actually fired, since the form is actually submitted using js and not the button.
So, being all literal and kinda answering the original question, you can't actually get the data in the button click event, w/o firing that event manually on postback (I'm surmising).
Hopefully save someone else some time figuring that out if they come here looking to make Stripe and .NET work together.

Showing/Hiding div

I am using asp.net ajax control toolkit 1.0 on vs 2005. I am using the collapseablePanel and AlwaysVisibleControlExtender control. When I use these, I notice that it my panel flashes for a few seconds before it is hidden.
To avoid this, I have decided to place it in a div to make it hidden.
I want it shown when I use the control.
Here is what I have:
<div id="menuContent" style="display:none">
<asp:Panel ID="pnlAddNewContent" runat="server" Width="300px">
....//the panel stuff here
</asp>
</div>
and the javascript for this in the header is:
function showdiv() {
if (document.getElementbyId) {
document.getElementbyId('menuContent').style.visibility = 'visible';
}
}
(its for IE 6 for I don't care about compatability)
and body onload=onLoad="showdiv();"
It correctly hides upon load, but I cannot get it to show again. Does anyone have solutions?
You are trying to show it by setting the visibility but you hid it using display.
You actually want something like this:
document.getElementbyId('menuContent').style.display = 'block';
Maybe this is what you're looking for
Javascript function:
function showHide(descriptor)
{
var layer = document.getElementById(descriptor);
if (layer != null) {
if (layer.style.display != 'none') {
layer.style.display = 'none'; //hide layer
} else {
layer.style.display = 'block';//show layer
}
}
}
HTML:
<img id="imgInfo" src="info.gif" border="0" />
<div style="display: none;" id="divInfo">some info</div>
Basically had to use Visibility hidden and visible attributes as these work best on a collapsePanel

Categories

Resources