Dynamically added button omits confirm - javascript

I'm developing a website for users where I add controls dynamically.
The problem is that after a confirmBox appears it doesn't matter what I click (Ok/Cancel) it still deletes my objects.
This is how I add them from codeBehind:
aPanel.RegisterAction("DeleteStuff", "Delete object",
true, btnDeleteClick, null);
where aPanel is ActionPanelDx
right after this comes:
if (actionPanel["DeleteStuff"] != null)
actionPanel["DeleteStuff"].ClientSideEvents.ItemClick =
"function(s,e){return confirm('Are you sure you want to delete?')}";
protected void btnDelete_Click(object sender, MenuItemEventArgs e)
{
//Im using self written classes for handlig SQL logic it looks like this:
MySQLCommand commad = new MySQLCommand("delete_object");//procedure
commad.MyParam.AddWithValue("#ob_id", ObjectID);
commad.myExecuteNonQuery();
}
Am I using the JS function in a wrong?

Now what your code does it to delete your object whenever a button (doesn't matter which) is clicked. What you need to do is something like that:
protected void btnDelete_Click(object sender, MenuItemEventArgs e)
{
if (e.item.name === "Yes")
{
MySQLCommand commad = new MySQLCommand("delete_object");//procedure
commad.MyParam.AddWithValue("#ob_id", ObjectID);
commad.myExecuteNonQuery();
}
}
instead of e.item.name it could be e.item.text or something like that, put a breakpoint or console.log to see what is inside of your e property if you not sure.

Related

Android[Kotlin] - ERROR TypeError: ["Android"].showToast is not a function

I am loading the webpage in webview using WebChromeClient(). The webpage has a dropdown whenever the user select's item from that dropdown I need to show a toast. For this, I'm following official doc I've implemented the same as the doc says. still, I'm getting the error in the console. "showToast is not a function".
In Fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val webSettings = webView.settings
webSettings.javaScriptEnabled = true
webSettings.domStorageEnabled = true
webSettings.databaseEnabled = true
webView.addJavascriptInterface(WebAppInterface(requireContext()), "Android")
webView.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
Log.i(TAG, consoleMessage.message())
return true
}
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
if (newProgress == 100) {
if (webView != null) {
webView.settings.builtInZoomControls = true
webView.settings.displayZoomControls = false
webView.loadUrl("javascript:loadMobileDashboard($data);")
}
}
}
}
webView.loadUrl(url)
}
WebAppInterface:
class WebAppInterface(private val context: Context) {
private val TAG = WebAppInterface::class.java.simpleName
#JavascriptInterface
fun showToast(toast: String) {
Log.d(TAG, "showToast: $toast")
}
}
I tried several changes and searched about it on the internet didn't work single solution. Please let me know what mistake am making here. Thanks :)
Create an html page in your assets folder, let's say named dropDown.html.
Copy this code into that file
<input type="dropDown" value="Hello" onClick="showToastInWebView('strMsg')" />
<script type="text/javascript">
function showToastInWebView(toast) {
Android.showToast(toast);
}
</script>
Now load url like this
myWebView.loadUrl("file:///android_asset/dropDown.html");
Note: webView does not invoke the JS function you have added a bridge to, You need to use your own webpage(in this case which is dropDown.html) that does indeed invoke the function, either local(our case) or on the web.

OnServerClick with dynamic anchorlink not firing

I'm trying to fire an OnServerClick event from some anchor tag created dynamically. My event isn't firing from my anchor tag. i have no error.
Can someone help me ?
HtmlAnchor btn_close = new HtmlAnchor();
btn_close.Attributes.Add("class", "close");
btn_close.Attributes.Add("data-dismiss", "alert");
btn_close.Attributes.Add("aria-label", "Ne plus afficher");
btn_close.Attributes.Add("title", "Ne plus afficher");
btn_close.Attributes.Add("runat", "server");
btn_close.ServerClick += new EventHandler(hideNotificationBtn_Click);
btn_close.ID = notificationSent.NotificationSentID.ToString();
btn_close.InnerText = "test";
div_alert.Controls.Add(btn_close);
protected void hideNotificationBtn_Click(object sender, EventArgs e)
{
HtmlAnchor cb = (HtmlAnchor)sender;
int test = int.Parse(cb.Name);
NotificationSent.SetNotificationAsHidden(int.Parse(cb.Name));
}
My hide notification isn't fired from by anchor when i click on it.
I already tried to change it to a button.
Thank you for your help.
Anchors don't call server side functions even when they are runat server, however there is the LinkButton class that can be used instead. Ultimately it is rendered as JavaScript initiated postback. Check out https://forums.asp.net/p/1519048/3644158.aspx for more information.
Make sure you are creating that button early enough in the page lifecycle. Look to get it created OnInit of the Page.
This is because the event handling events happen after Page Init. Of course, the button has to have been created before the events can be detected on
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["falg"] != null)
{
Create();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Create();
ViewState.Add("falg", true);
}
void BtnServices_Click(object sender, EventArgs e)
{
Response.Write("hi");
}
void BtnServices_Command(object sender, CommandEventArgs e)
{
Response.Write("hi");
}
void Create()
{
BtnServices = new Button();
BtnServices.ID = "BtnServices";
BtnServices.Text = "Click Me";
BtnServices.Click += new EventHandler(BtnServices_Click);
BtnServices.Command += new CommandEventHandler(BtnServices_Command);
form1.Controls.Add(BtnServices);
}
Easier and reliable way to do this could be , instead of dynamically
adding the control, always add it, but set Visible=false initially.
Then where you're currently adding it, instead just make it visible.

Unable to copy the text in clip board inside the repeater

I am trying to copy the text in clip board inside the repeater but it's not copying.
Below is what I have tried so far.
protected void rptCopy_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e) {
if (e.CommandName == "Copy") {
System.Web.UI.WebControls.LinkButton btnCopy = (LinkButton) rptQuestResponseDtl.Items[0].FindControl("lnkCopy");
System.Web.UI.WebControls.Label txtMsg = (Label) rptQuestResponseDtl.Items[0].FindControl("lblComment");
txtMsg.Focus();
btnCopy.Attributes.Add("onclick", "function copyClipboard(){ CopiedTxt = document.selection.createRange();CopiedTxt.execCommand('Copy'); }");
}
}
should the onclick event be onclientclick like btnCopy.Attributes.Add("onclientclick",... ? Also you defined the function copyClipboard but never called it like copyClipboard()... My recommendation is define function in JS file, include it in your ASPX page and then use clientclick event to call the function

Telerik ASP.Net RadGrid Add New Record Client Side Javascript Prevent Behavior

I am attaching an onClick event to the Add Record button on my RadGrid. Code as follows:
Code Behind
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
LinkButton lnk = (LinkButton)e.Item.FindControl("InitInsertButton");
lnk.Attributes.Add("onClick", "testClick()");
}
}
Javascript
function testClick(){
// Perform some Client Side Validation
var validated = false;
if(!validated){
radalert('Validation Fail', 100, 100, 'Window', null, null);
// What to call here to prevent the RadGrid from going into Insert (Edit) mode??
//I tried return false; but that did not prevent the grid.
}
}
So on my JS call, after the alert window has been displayed and I closed it, the RadGrid still goes into edit mode.
I tried a variation of the following:
Code Behind
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if(e.CommandName == RadGrid.InitInsertCommandName)
{
// If Validation Failed, prevent Radgrid from going to Edit Mode.
RadGrid1..MasterTableView.ClearEditItems();
}
}
Posting an answer so that for everyone who may stumble on this:
Code Behind:
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
LinkButton lnk = (LinkButton)e.Item.FindControl("InitInsertButton");
lnk.Attributes.Add("onClick", "return testClick()");
}
}
Javascript
function testClick(){
// Perform some Client Side Validation
var validated = false;
if(!validated){
radalert('Validation Fail', 100, 100, 'Window', null, null);
return false;
}
}

Dynamically open a radwindow defined in Javascript

Objective:- From the server-side, I need to open a radwindow(defined in JavaScript of the aspx page) automatically on an IF condition.
Code used:-
In aspx page, I defined the radwindow as:-
<telerik:RadWindowManager Skin="WBDA" ID="AssetPreviewManager" Modal="true"
EnableEmbeddedSkins="false" runat="server" DestroyOnClose="true" Behavior="Close"
style="z-index:8000">
<Windows>
<telerik:RadWindow ID="DisclaimerAlertWindow" runat="server" Width="720px" Height="220px"
Modal="true" visibleStatusbar="false" VisibleTitlebar="false" keepInScreenBounds="true" title="Sourav">
</telerik:RadWindow>
</Windows>
</telerik:RadWindowManager>
In JavaScript, a function is defined for opening the radwindow:-
function openRadWindow()
{
var oWnd = radopen('DisclaimerAlert.aspx, 'DisclaimerAlertWindow');
oWnd.set_title('Access Denied !');
oWnd.Center();
return false;
}
So on the server side of the aspx page, In the Page Load event an IF condition is checked and then I'm calling 'openRadWindow()' function as:-
protected void Page_Load(object sender, EventArgs e)
{
if (fieldValue == "False")
{
string xyz = "<script type='text/javascript' lang='Javascript'>openRadWindow();</script>";
ClientScript.RegisterStartupScript(this.GetType(), "Window", xyz);
}
}
Problem:-
But on running this, these JavaScript errors are coming:-
Object doesn't support this property or method.
'undefined' is null or not an object
Please help how to achieve my objective. I am totally stuck.
Hi I want to share with you my solution to create RadWindow dialog in Javascript code only.
We need to implement 2 methods: one for initializing RadWindow dialog, and the last one for recieving the arguments returned after closing the RadWindow. You can do what you want in this second step (e.x postback,...)
Here is my code:
Initializing RadWindow dialog:
function openMyDialog(url, args) {
var manageWindow = GetRadWindowManager();
if (manageWindow) {
var radWindow = manageWindow.open(url, "<your_dialog_name>");
if (radWindow) {
radWindow.set_initialBehaviors(Telerik.Web.UI.WindowBehaviors.None);
radWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize);
radWindow.setActive(true);
radWindow.SetModal(true);
radWindow.center();
radWindow.set_visibleStatusbar(false);
radWindow.set_keepInScreenBounds(true);
radWindow.set_minWidth(640);
radWindow.set_minHeight(480);
radWindow.setSize(640, 480);
radWindow.set_destroyOnClose(true);
radWindow.add_close(closeMyDialog);//after closing the RadWindow, closeMyDialog will be called
radWindow.argument = args;//you can pass the value from parent page to RadWindow dialog as this line
}
}
}
Closing the RadWindow dialog:
function closeMoveProjectDialog(sender, args) {
var objArgs = args.get_argument();
//objArgs variable stored the values returned from the RadWindow
//you can use it for your purpose
}
How to call this?
You can put the open method into your expected method. In my side, I have a method as shown below and I will call the RadWindow as this way:
function ShowForeignKeyFrontEditSingle(param1, param2){
var url = "ForeignKeyFrontEditSingle.aspx";
var objArgs = new Array();
objArgs[0] = param1;
objArgs[1] = param2;
openMyDialog(url, objArgs);
return;
}
Of course, you have to declare a RadWindowManager control
function GetRadWindowManager() {
return $find("<%=your_radwindow_manager_control.ClientID%>");
}
Take a look here, it explains how to use the ScriptManager.RegisterStartupScript method: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-javascript-from-server-side.html. Note it the ScriptManager's method. Also look at the Sys.Application.Load event to prevent your code from executing too early.

Categories