pass the id of textbox to dropdownliast onchange event in javascript - javascript

I have a dropdownlist defined:
<asp:DropDownList Width="300px" ID="PlaceHoldersDropDownList" runat="server"
AppendDataBoundItems="True" TabIndex="3" onchange="PasteTextInEditor
(this.options[this.selectedIndex].value), '<%=
SubjectTextBox.ClientID %>'" >
So, I pass the selected text and a textbox ID to a javascript function. The text box is defined as:
<asp:TextBox Width="660px" ID="SubjectTextBox" Text='<%# Bind( "Subject") %>'
runat="server" TabIndex="4" MaxLength="100">
</asp:TextBox>
So, in script function, when i put alert like this :
alert(text); //shows selected value
alert(editor); // shows undefined
So editor value is turning up undefined. So, can you please let me know the mistake I've been doing. I would like to save that value selected from dropdown into textbox.Please help me fixing th eproblem. Thank You

It looks like your bracket is in the wrong place in your "onchange": you're only passing one parameter and not the client id.
But regardless, the ClientID is not going to be parsed here. Instead, I suggest you add your onclick in the code behind, either in your Page_Load or Page_PreRender:
PlaceHoldersDropDownList.Attributes.Add("onchange", "PasteTextInEditor(this.options[this.selectedIndex].value, '" + SubjectTextBox.ClientID + "');")

Related

How to pass Javascript value to label server side

I have a gridview that contains two(2) ASPxComboBox the value of the second Combo box is base on the value of the first combo box. DevExpress demos and sample are a bit complicated and time consuming so I think of a workaround that when the selected item of combo box is exchange the value will store in a label. And I will get the value of label to store in dropdown. But I don't know how to pass the value of label in server side. Any help would be much appreciated. Thank you!
Here's my code.
FrontEnd
<asp:Label ID="LblProduct" runat="server" Text="Label"></asp:Label>
<dx:ASPxGridView ID="ASPxGridView2" OnRowDataBound="ASPxGridView2_RowDataBound" ClientInstanceName="GridV" runat="server" AutoGenerateColumns="False" DataSourceID="forprod" KeyFieldName = "ppdtl_no">
<columns>
<dx:GridViewDataTextColumn FieldName="fld_product" Name="Dd_product" ShowInCustomizationForm="true" VisibleIndex="3">
<SettingsHeaderFilter>
<DateRangePickerSettings EditFormatString="" />
</SettingsHeaderFilter>
<EditItemTemplate>
<dx:ASPxComboBox ID="ASPxComboBoxProduct" runat="server" DataSourceID="pp_prod" TextField="pp_ppname" ValueField="pp_ppcode">
<ClientSideEvents SelectedIndexChanged="function(s, e) { OnProductChanged(s); }"></ClientSideEvents>
</dx:ASPxComboBox>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
<dx:GridViewDataComboBoxColumn FieldName="fld_type" Name="dd_type" ShowInCustomizationForm="true" VisibleIndex="4">
<SettingsHeaderFilter>
<DateRangePickerSettings EditFormatString="" />
</SettingsHeaderFilter>
<EditItemTemplate>
<dx:ASPxComboBox ID="ASPxComboBoxType" runat="server" DataSourceID="pp_type" TextField="pp_codetype" ValueField="pp_codetype">
</dx:ASPxComboBox>
</EditItemTemplate>
</dx:GridViewDataComboBoxColumn>
</columns>
</ASPxGridView>
JavaScript
function OnProductChanged(s, e) {
var selected_index = s.lastSuccessValue;
var aa = document.getElementById('LblProduct').innerText = selected_index;
}
onload = OnProductChanged;
You need to use the ClientID property of any element you run at server level in your selector. To achieve this, you have to write the JavaScript inside the file with your label, and then use <%= LblProduct.ClientID %>.
<script type="text/javascript">
document.getElementById('<%= LblProduct.ClientID %>');
</script>
Look at your project during runtime with Inspect - you will see the ID after compilation is not LblProduct, but something similar to ProjectName_PageName_ContentPlaceHolderName_LblProduct.
You could also just copy-paste that, though it's not open to change.

JavaScript alert with label's text

Quick and silly question perhaps, but how do I pass a label's text into a javascript confirm or alert function?
Here is what I've done but it's not good:
<asp:Label ID="lblGVDeleteMessage" runat="server" Text="Show me!" style="display:none;" ></asp:Label>
<asp:ImageButton ID="btnDelete" runat="server" AlternateText="Delete"
CommandName="Delete" Height="15px" ImageUrl="~/Images/document_delete.png"
OnClientClick="return confirm('#<%=lblGVDeleteMessage.ClientID%>')"
Width="15px" />
Thanks!
You need to grab the element by it's ID, then read it's innerHTML property:
OnClientClick="return confirm(document.getElementById('<%=lblGVDeleteMessage.ClientID%>').innerHTML)"
But you might want to consider moving the logic out into another function:
Script:
function showConfirm(id) {
var elem = document.getElementById(id);
return confirm(elem.innerHTML);
}
ASPX:
OnClientClick="return showConfirm('<%=lblGVDeleteMessage.ClientID%>')"
You probably want this to be:
"return confirm(document.getElementById('#<%=lblGVDeleteMessage.ClientID%>').innerHTML)"
Based off the comment below and the fact that you must be dynamically setting the text to the label in the first place, can you not just set the text dynamically into the call instead? Bit neater than outputting an extra dom element that will always be hidden, e.g.:
"return confirm('<%# SomeFunctionTosetTheText() %>')"
The only way I made it work was to set ClientIDMode="Static" on the label and on the OnClientClick event do this: "return showConfirm('lblGVDeleteMessage');"

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;

Set asp.net textbox value using javascript

I want to set the value of a asp.net textbox using javascript
My JS Code is:
document.getElementById('<%=txtFlag.ClientID %>').value = "Track";
My textbox is:
<asp:TextBox ID="txtFlag" runat="server" Visible="False"></asp:TextBox>
But it gives me an error document.getElementById(...)' is null or not an object
I dont understand what is wrong.
Please help.
<asp:TextBox ID="txtFlag" runat="server" Visible="False"></asp:TextBox>
Setting visible=false will cause this textbox to not appear in the rendered page. Remove this, and add display:none;
<asp:TextBox ID="txtFlag" runat="server" style="display:none;"></asp:TextBox>
Try including the ClientIDMode property in your textbox
<asp:TextBox ID="txtFlag" runat="server" Visible="False"
ClientIDMode="Static"></asp:TextBox>
You are calling javascript before complete document load. Please write your javascript code on document.ready function like this
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
document.getElementById('<%=txtFlag.ClientID %>').value = "Track";
});
</script>
And second thing is that use display none in place of visible false or use hidden field control
<asp:TextBox ID="txtFlag" runat="server" style="display:none;"></asp:TextBox>
Solution 1:
Make that textbox as visible=true and try,
When you make a control as visible false, that control will not be loaded in client side and as you knew javascript will be executed on client side itself.
Solution 2:
Add this javascript at the end of the page.
document.getElementById('txtFlag').value='Track'
try this

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.

Categories