Issues with "&" symbol in javascript - javascript

I have a aspx page from which some strings are passed into the Javascript function. I am facing a strange issue if the string contains a & symbol.
Here is the simplified version of the code
if(stringWhichComesFromUI == "AD&D")
{
//populate a hidden field
$('#hdnSomeHiddenField').value = "AD&D";
}
and in the UI, the hidden field value is populated in a cell inside a grid.
Now the problem is, even if user is sending "AD&D" from the UI, the variable stringWhichComesFromUI is becoming "AD&Amp;D" thats why the if block never executes.
I have also tried with
if(stringWhichComesFromUI == "AD&D" || stringWhichComesFromUI == "AD&Amp;D")
{
//populate a hidden field
$('#hdnSomeHiddenField').value = "AD&D";
}
This executes the if block, but the value which is going into the hidden field does not show properly in the UI. Value which is displayed in UI is "AD", the "&D" part is gone! I am not able to figure out why, please help?

There is error in syntax of assigning value in jquery. Use this
<asp:TextBox ID="myinput" runat="server" />
<asp:Button ID="SubmitButton" runat="server" OnClientClick="Showme()" Text="Submit" />
<asp:HiddenField ID="hiddenFieldText" runat="server" />
And your script will be like this:
function Showme(){
var stringWhichComesFromUI= $("#myinput").text();
if(stringWhichComesFromUI == "AD&D")
{
//populate a hidden field
$("#hiddenFieldText").val("AD&D");
}
}

Related

asp.net Run Javascript confirm from codebehind with custom text and return if OK selected

I have a grid on a page with a list of items - I have a column for tickbox - One use is to remove/delete item.
I have a button "Delete Item" - this runs some code behind to find the item ticked and if only one ticked I would like to ask the user - "Do you want to delete item ABC ... " i.e. showing the text of item selected - If they click OK continue.
I have tried a few options - closest is to use a hidden field to store the value as in below but the code behind goes to the line to read the hidden field before the confirm box comes up so its not going to pick up the value. The confirm box opens OK and message OK.
<script type="text/javascript">
function Confirm(txt) {
if (confirm(txt)) {
hdnResultValue = 1
}
}
</script>
<asp:HiddenField ID="hdnResultValue" Value="0" runat="server" />
<asp:Button ID="DelItem" runat="server" Text="Remove Item"/>
In code behind
Page.ClientScript.RegisterStartupScript(Page.GetType(), "myconfirm", "Confirm('" & txtMsg & "');", True)
If hdnResultValue.Value = 1 Then
'Code to delete
End If
Appreciate any ideas on getting this to work or alternatives.
Reply to Jon:-
Thanks Jon - I had a go at that but doesn't get the itemname - suspect its because I need to reference the grid - presume rather than "this" I need the gridID but this didn't work either.
Below main part of page:-
In console first log for "this" came up empty. I have the button sitting above the grid not as part of the grid!.
<script type="text/javascript">
function confirmClick() {
var itemName;
itemName = $(this).closest("tr").find("td:eq(2)").text();
//AS I haven't tested this lets add some debugging
//Check $(this) exists
console.log($(this));
//Check we got a tr
console.log($(this).closest("tr"));
//Check we got the target td
console.log($(this).closest("tr").find("td:eq(2)"));
return confirm("Are you sure you want to delete: " + itemName);
confirm(txt)
}
</script>
<div>
<asp:Button ID="DelItem" runat="server" Text="Delete Item" OnClientClick="return confirmClick();"/>
</div>
<asp:GridView ID="ItemList" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="Select" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemID" HeaderText="ItemID" Visible="True">
</asp:BoundField>
<asp:BoundField DataField="ItemName" HeaderText="Item Name" Visible="True">
</asp:BoundField>
</asp:GridView>
The probelm with your approach is that by the time your javascript is triggered the page has already been posted back. So then when the client clicks "OK" the page will have to be posted back yet again.
The rule to remember is javascript is executed client side in the browser, vb.net on the server. Also remember that the whole serverside code is executed before the page (HTML/CSS/javascript) is returned to the browser. So in your current example the hdnResultValue.Value = 1 check is going to happen before the javascript is executed, as the page has yet to be sent to the browser.
What you need to do is trigger the javascript before the page is posted back
<asp:Button ID="DelItem" runat="server" Text="Remove Item" OnClientClick="return confirmClick(this);"/>
Then have your javascript already on the page, I'm going to use the incredibly helpful jQuery library to get the text for the item:
<script type="text/javascript">
function confirmClick(itemClicked) {
var itemName;
//If you have a class on the colum with the item for this example
//class="itemName"
//itemName = $(itemClicked).closest("tr").find(".itemName").text();
//If you don't have a class you could use the columns index
//3rd column for this exampl
//Index is 0 based
itemName = $(itemClicked).closest("tr").find("td:eq(2)").text();
//AS I haven't tested this lets add some debugging
//Check $(this) exists
console.log($(itemClicked));
//Check we got a tr
console.log($(itemClicked).closest("tr"));
//Check we got the target td
console.log($(itemClicked).closest("tr").find("td:eq(2)"));
return confirm("Are you sure you want to delete: " + itemName);
}
</script>
Don't forget to include the jQuery library!
Your other option is yo use AJAX for an asynchronous post back to generate the confirm message.
Here's an article outlining how to use the ModalPopUpExtender to use a fancier confirm: http://mattberseth.com/blog/2007/07/confirm_gridview_deletes_with.html.
Update A quick bug fix. I forgot to pass through the item bein click. It has been added as a parameter to the javascript function.
Demo of the script in action
Update 2 - Get Text of checked row
Change button to (we've taken out the parameter):
<asp:Button ID="DelItem" OnClientClick="return confirmClick();" runat="server" Text="Remove Item" />
Change your script to
function confirmClick() {
//<%= ItemList.ClientId %> gets the rendered client side ID of your gridview
var table = $("<%= ItemList.ClientId %>");
var checkedRow = $(table).find("tr").has("input:checked");
var itemName = $(checkedRow).find("td:eq(2)").text();
return confirm("Are you sure you want to delete: " + itemName);
}
Script Demo
To set value of hidden field do
document.getElementById("hdnResultValue").value = 1;

setting label value in javascript

I have code like this
<table>
<tr>
<td>
<div>
<asp:Label runat="server" ID="lblBookmarksIds" Style="visibility: hidden;" Text="test"/>
</div>
</td>
<td>
<asp:UpdatePanel runat="server" ID="buttonPanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button runat="server" ID="btnInvokeImageRead" CausesValidation="false" UseSubmitBehavior="false"
OnClick="btnInvokeImageRead_Click" Style="visibility: hidden;" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
in javascript i'm trying to set value of label and call codebehind function so that i will have desired value passed to codebehind like that :
alert(document.getElementById('<%= lblBookmarksIds.ClientID%>').firstChild.nodeValue);
document.getElementById('<%= lblBookmarksIds.ClientID%>').innerText = str;
alert(document.getElementById('<%= lblBookmarksIds.ClientID%>').firstChild.nodeValue);
//alert('1');
if (str != "") {
document.getElementById('<%= btnInvokeImageRead.ClientID%>').click();
}
when second alert gets displayed the value of lblBookmarksIds has changed value, but when i debug in codebehind function btnInvokeImageRead_Click the value of lblBookmarksIds has its old value.
Anybody knows Why ?
Regards
Wojciech
Labels are not passed to code behind. You will have to use an input(TextBox) for that purpose.
You can style an input to look like a label using CSS.
Alternatively, you can keep the value in a hidden field, and use javascript to show the value in a label and pass it back in the hidden field.
The reason ASP.NET is able to "see" the values entered into a TextBox and similar controls is because the values of these controls are sent in the POST body when the page posts back. You can see this through any number of tools, including the Developer Tools your browser likely includes or an intercepting proxy like Fiddler. When the postback occurs, each of those controls has a LoadPostData function that processes the POST data and updates the Text properties (or whatever properties) of the control.
The contents of a Label are not submitted in the POST data, so .NET has no way to see any changes made to it from JavaScript.
The controls that do process post data all implement IPostBackDataHandler.

Unable to read hidden field value from server side

I have a aspx page (default.aspx), inside which I am loading a user control (tree.ascx).
inside the tree.ascx there is a hidden field.
<asp:HiddenField ID="HiddenField1" runat="server"/>
I am assigning a value to the hidden field using javascript.
document.getElementById('<%=HiddenField1.ClientID%>').value = "some text here";
alert(document.getElementById('<%=HiddenField1.ClientID%>').value);
document.getElementById('form1').submit();
The alert displays the value absolutely fine. which means the value gets inserted in the hidden field properly.
But when I am posting back to server and checking the value, it is always null.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// do something.
}
else
{
string str = this.HiddenField1.Value;
}
}
My code is always getting a empty string here. somehow the postback is erasing the value from the hidden field.
What could be the reason?
Try using below syntax. It works for me even after postback.
ASPX code
<asp:HiddenField runat="server" ID="aspHiddenField" />
<input type="hidden" id="inputHidden" value='<%= aspHiddenField.ClientID %>' />
JavaScript Code
var inputHidden = document.getElementById('inputHidden');
$("#" + inputHidden.value).val("some text");
Code Behind
if (!string.IsNullOrEmpty(aspHiddenField.Value))
{
//Your code goes here
}
Check if your control is within a master page, if it is, then you need to access it like that, 1st Master Page->within master page look for the control's value, it will work surely.
Place your hidden field in update panel like :
<asp:UpdatePanel ID="UpnlHidden" runat="server">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
This will work for you :-)

Creating a Button Click Event and Validating TextBoxes using Javascript

I am having so much trouble with this. I have looked everywhere so I hope someone can either explain to me how to do this or show me. Here's my problem:
I have a DataGrid filled with DataBound Items (ItemTemplate) which was created using ASP.Net.
My reason for the ItemTemplates over a regular DataBound field is to enable the Edit Mode of the DataGrid. In my ItemTemplates, I have labels to display the data and two option buttons (Edit/Delete). I've got the buttons working in the code behind (C#).
Edit places the DataGrid in Edit Mode. In the EditItemTemplates I've got DropDownLists, TextBoxes, and a Save button in place of the Edit button.
The Save button also works with the code I've written for it. All-in-all, the DataGrid works beautifully and displays everything neatly. However, there is one final job I want the Save button to do: I want it to check the TextBoxes and validate that the values entered match the criteria I have set (keep in mind that these are in EditItemTemplates).
I have Javascript already written that will check for validation. I want a modal window (that I have already set up) to display and I want the CSS of the TextBoxes in question to change.
I want to do this using Javascript but my problem is that I can't check for the Save button to create the Click event and I can't 'locate' the TextBoxes to validate them. Is there a way I can 'find' those elements while the DataGrid is in Edit Mode?
Here's a small bit of the code used to create the DataGrid if it helps:
<asp:DataGrid ID="dgCamsizer" CssClass="data" runat="server" AutoGenerateColumns="False"
GridLines="None" OnItemCommand="dgCamsizer_ItemCommand" ShowHeader="true">
<Columns>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG">
<HeaderTemplate>
Operator</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Operator" Text='<%# DataBinder.Eval(Container.DataItem, "Operator") %>'
runat="server" /></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="EditOper" Width="40px" Text='<%# DataBinder.Eval(Container.DataItem, "Operator") %>'
runat="server"></asp:TextBox></EditItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG">
<ItemTemplate>
<asp:Button ID="Edit" Text="Edit" CommandName="Edit" runat="server" /></ItemTemplate>
<EditItemTemplate>
<asp:Button ID="Save" Text="Save" CommandName="Save" runat="server" /></EditItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Perhaps I should re-phase my question: I managed to 'find' the TextBoxes thanks to Zetlen. I've also managed to get the values. Now... How do I use those values to test for validation?
Here is the code I used to get the values:
$("#<%=dgCamsizer.ClientID %> :text").each(function () {
alert($(this).val());
});
ASP.NET webforms are hard to work with in JavaScript, because the IDs of your HTML elements change during the page lifecycle! The input you're calling "EditOper" will get an HTML ID of something like "dgCamSizer_ctl102_EditOper". One thing you can do is collect these elements on pageload in a cache of DOM element references. I recommend using jQuery or a similar DOM querying library.
<script type="text/javascript">
$(document).ready(function() {
var $editorElms = {},
idSeparator = "_"; // the underscore is ASP.NET's default ID separator, but this can be changed if you wish with the IDSeparator property.
$('#dgCamSizer input').each(function() {
$editorElms[this.id.split('_').pop()] = $(this);
});
// now you can access every input using the $editorElms hash.
// e.g.
function someValidationRoutine() {
if (!$editorElms.EditOper.val()) {
someErrorDisplayer("EditOper must not be blank.");
return false;
}
}
})
</script>
And, again using jQuery, the Save button shouldn't be too tough to find.
var $saveButton = $('#dgCamSizer :submit[value=Save]');
So you can bind the event that way:
$saveButton.click(function(e) {
if (!someValidationRoutine()) {
e.preventDefault();
}
});
This is not the most high-performance solution--selectors of that complexity are always a bit slower. But it gets the job done without messing too much with the DataGrid.
So I managed to solve my own problems and answer my own question. I was able to get the id's of all of the TextBoxes and I even placed them into an array to be used for my validations. Here's what I used to do all of this:
var i = 0;
var data = [];
$("#<%=dgCamsizer.ClientID %> :text").each(function () {
data[i] = $(this).attr("id");
i++;
});

getElementById not finding control generated by ASP.net

I am simply trying to store a label in a variable in javascript but for some reason this isn't working with document.getElementById('control');. I know my javascript is linking to my html file fine because everything else works.
Here is my javascript code:
function performEvapCooledCircuit(txt)
{
var error = document.getElementById('lblError');
if (txt.value == null || isNaN(txt.value))
{
error.style.visibility = "visible";
}
}
Here is the html code for my label:
<asp:Label ID="lblError" class="NormLabel" runat="server"
style="color:red; visibility:hidden;" Text="Invalid Input."></asp:Label>
I am getting an error that says object expected??
The ID that ASP.NET will generate will not be "lblError" so you'll need to reference it by its ClientID
document.getElementById('<%=lblError.ClientID %>');
If your javascript file is external I've usually had to write a type of "Init" javascript method to make sure my ID's were set up property
On your ASPX page:
<script type="text/javascript">
var lblError = null;
function InitializeVariables()
{
if (lblError == null) // make sure you only do this once
{
lblError = document.getElementById("<%=lblError.ClientID %>");
}
}
</script>
<asp:Label
ID="lblError"
class="NormLabel"
runat="server"
style="color:red; visibility:hidden;"
Text="Invalid Input."></asp:Label>
Then in your javascript file you'll have to call InitializeVariables() to make sure you've got the variables pointing to the proper asp.net controls
function performEvapCooledCircuit(txt)
{
InitializeVariables();
if (txt.value == null || isNaN(txt.value))
{
lblError.style.visibility = "visible";
}
}
"hunter" gives a pretty solid way of doing things, however a, in my opinion far better method is to use the "CliendIDMode" property on the control and set that property to "Static". This will make the client and server IDs the same. Like this:
<asp:TextBox ID="ServerAndClientId" runat="server" ClientIDMode="Static" />
The ID of the label is not "lblError". The ASP.net engine changed the ID. Check the HTML source code in the browser to find out the real ID.
That's not HTML for the label, that is an ASP.NET Control which will be rendered into HTML before it is sent in the response. ASP.NET WebForms controls sometimes change the id for the HTML they create.
View the source of the webpage to see what the id for the HTML element is on the rendered page.
You can use this:
document.getElementById('<%= lblError.ClientID %>').click()
Starting from ASP.NET 4.0 you can use ClientIDMode property for you element. And if you set it into Static then the ClientID value will be set to the value of the ID property:
<asp:Label ID="lblError" runat="server" ClientIDMode="Static" />
will be rendered as something like this:
<span id="lblError" name="ctl00$MasterPageBody$ctl00$Label1" />

Categories