Calling event click with JavaScript - javascript

It is possible to call a event click with JavaScript? how?
I'm trying to call this event when a button get clicked.
I'm creating Buttons dynamically so the id's change constantly
Here is how i make the buttons dynamically and assign the event click
protected void Page_Init(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);
Button Btn_clic = (Button)sender;
var name = Btn_clic.Text;
List.ListUsers listArea = new List.ListUsers();
List<Data.Area> Area = listArea.AreaList();
List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();
List<Button> Botones = new List<Button>();
var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();
foreach (var team in TeamFCH)
{
Button newButton = new Button();
newButton.CommandName = "Btn" + Convert.ToString(team);
newButton.ID = "Btn_" + Convert.ToString(team);
newButton.Text = team;
newButton.CommandArgument = name;
newButton.Click += new System.EventHandler(newButton_Click);
Botones.Add(newButton);
GoodPanel.Controls.Add(newButton);
newButton.CssClass = "btn-primary outline separate";
}
}
protected void newButton_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);
Button Btnclick = (Button)sender;
var team = Btnclick.Text;
string name = Btnclick.CommandArgument;
List.ListUsers listArea = new List.ListUsers();
List<Data.Area> Area = listArea.AreaList();
List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();
var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
Grv_Eng.DataSource = ListOfToolsOk;
Grv_Eng.DataBind();
}

If you want to assign a OnClick event, do it like this.
Button Btnclick = new Button();
Btnclick.Click += newButton_Click;
Btnclick.Text = "MyButton";
Btnclick.ID = "MyButtonID";
PlaceHolder1.Controls.Add(Btnclick);
And if you want to reference the dynamic ID, use FindControl and ClientID on the aspx page.
document.getElementById("<%= PlaceHolder1.FindControl("MyButtonID").ClientID %>").click

Assign an onClick listener to your button.
document.getElementById("your-id").click = function () {
newButton_Click();
}

Here you go try this for dynamically created buttons
$(document).on('click', '#id', function(){});

You can use a data- attribute to id the buttons from javascript and then you just attach to the javascript event:
So, from the server side you can do this:
newButton.Attributes["data-dynamic-button"] = team;
And you can implement this on the client side:
$("[data-dynamic-button]").click(function (event) {
event.preventDefault()
alert($(event.currentTarget).data("dynamic-button"));
});

Related

How can i get The Html Object in a Event on Bridge.net C#?

in Bridge.net i can only create a defult eventlistner.
In javascript i will do it like this.
<div id="nose" onclick="Test(this);"></div>
<script>
function Test(htmlelement) {
var id = htmlelement.id;
console.log('area element id = ' + id);
}
</script>
I fixed that this way.
public Static void SomeFunc(){
var label = new HTMLLabelElement();
label.TextContent = txtbox.Value;
label.Style.FontSize = "40px";
label.AddEventListener(EventType.Click,ClickEvent );
}
public static void ClickEvent (Event e)
{
var x = (HTMLElement)e.Target;
x.SetAttribute("value", "HelloWorld");
}

Checkbox Check changed event firing twice C#

I have a listview with checkbox. According to my requirement I uncheck through javascript. But because of that script my Checkchanged event fires twice and returns the previous unchecked(through javascript) value on second time fires.
Also usually any operation check box triggers an event. But if you check the same item which is unchecked through javascript just before is not fires the checkedchanged event.
I am not sure why is it happening when using script.
Please find the code below
JavaScript
function CallConfirmBox() {
alert("456");
if (confirm('Schedule more than one time slot for the same day will overwrite the file')) {
return true;
}
else {
var id = document.getElementById('<%= hdnValue.ClientID%>').value;
alert(id);
$('#' + id).attr('checked', false);
alert("123")
id = "";
return false;
}
}
CodeBehind
protected void chkCheck_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkCheck = (CheckBox)sender;
ListViewItem item = (ListViewItem)chkCheck.NamingContainer;
ListViewDataItem dataItem = (ListViewDataItem)item;
string lookupId = lvLookup.DataKeys[dataItem.DisplayIndex].Value.ToString();
hdnValue.Value = chkCheck.ClientID;
if (lookupMstVal == "ScheduledTime." && lbCheckedIdList.Items.Count > 0 && chkCheck.Checked)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);//" + chkCheck.ClientID + "
}
if (chkCheck.Checked)
lbCheckedIdList.Items.Add(lookupId);
else
lbCheckedIdList.Items.Remove(lookupId);
hdfLookupId.Value = "";
foreach (ListItem itm in lbCheckedIdList.Items)
{
hdfLookupId.Value += (hdfLookupId.Value == "" ? "" : ",") + itm.Value;
}
postbackFlag = true;
}
Please Help! Thanks.

UpdatePanel Breaks JQuery Script on datalist

I have an update panel and inside the update panel I have a datalist.
On the datalist I have multi div
<div class="prod_details_tab">
<div class="prod_details_sell">
<a href="Handler.ashx?action=addToBasket&productID=4" onclick="return false;">
<img src="images/cart.gif" alt='<%#String.Format("{0}", Eval("k_name1")) %>'
width="16" height="16" id='<%#String.Format("{0}", Eval("k_name1")) %>'
class="left_IB" />
</a>
</div>
</div>
I write a jQuery code that when a person click on cart.gif pic run the jQuery
$(".prod_details_sell a img").click(function () {
//some code is here
});
On the first page of datalist jquery run good and all thing is ok.
But on the second page when I click on cart.gif pic jQuery does not run.
Please help me to fix it
Thanks
Edit: I write next button and prev button click in here
protected void cmdNext_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage += 1;
PagedDataSource pagedDS = new PagedDataSource();
pagedDS.DataSource = ((DataTable)Cache["DataTable-cach"]).DefaultView;// cacheItem.DefaultView;
pagedDS.AllowPaging = true;
pagedDS.PageSize = 6;
pagedDS.CurrentPageIndex = CurrentPage;
dlPaging.DataSource = pagedDS;
dlPaging.DataBind();
// Disable Prev or Next buttons if necessary
cmdPrev.Enabled = !pagedDS.IsFirstPage;
cmdNext.Enabled = !pagedDS.IsLastPage;
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
PagedDataSource pagedDS = new PagedDataSource();
pagedDS.DataSource = ((DataTable)Cache["DataTable-cach"]).DefaultView;// cacheItem.DefaultView;
pagedDS.AllowPaging = true;
pagedDS.PageSize = 6;
pagedDS.CurrentPageIndex = CurrentPage;
dlPaging.DataSource = pagedDS;
dlPaging.DataBind();
lblCurrentPage.Text = pagedDS.PageCount.ToString() + " صفحه " + (CurrentPage + 1).ToString() + " از ";
// Disable Prev or Next buttons if necessary
cmdPrev.Enabled = !pagedDS.IsFirstPage;
cmdNext.Enabled = !pagedDS.IsLastPage;
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default page index of 0
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
thank you friends
I edit html file
<ContentTemplate>
<script type="text/javascript">
Sys.Application.add_load(BindEvents);
</script>
.
.
.
and edit my jquery file
function BindEvents() {
//my jquery codes
}
Be Happy
When you go to next page of data list the onclick event gets unbinded as update panel refresh the content inside div. So onclick event must be added again to get the expected result.
Try the following in cs page below your datalist bind code.
ScriptManager.RegisterClientScriptBlock(id of update panel,
typeof(UpdatePanel), "string",
"$(function () {$('.prod_details_sell a img').click(function () {
//some code is here
});)", true);
Just replace this:
$(".prod_details_sell a img").click(function () {
//some code is here
});
with this:
Sys.Application.add_load(initJavaScripts);
function initJavaScripts() {
$(".prod_details_sell a img").click(function () {
//some code is here
});
}

Calling Web Method using Javascript on dynamically created Control

I am creating some controls dynamically in these Dynamic control there is <asp: Image> Control
I want to call webmethod when I click that Image control.I searched a lot but nothing is happening.
the code for Dynamic control is
for (int i = 0; i < SearchResult.Length; i++)
{
System.Web.UI.HtmlControls.HtmlGenericControl panel = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
panel.Attributes["class"] = "panel";
panel.ID = "panel_" + (i + 1).ToString();
System.Web.UI.HtmlControls.HtmlGenericControl inside = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
inside.Attributes["class"] = "inside";
Image img = new Image();
img.ImageUrl = SearchResult[i].ImageUrl;
// img.Attributes.Add("onclick", THE WEB Method I want to call);
inside.Controls.Add(img);
Label label = new Label();
label.Text = SearchResult[i].Title;
label.Font.Size = 10;
label.Font.Bold = true;
panel.Controls.Add(label);
panel.Controls.Add(inside);
test.Controls.Add(panel);
}
and my web method is
[WebMethod]
public static void AddToDownload(String ConnectionString,String Query)
{
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
cmd.ExecuteNonQuery();
con.Close();
}
Get rid of the "onclick" line and wire up a server-side Click event, like this:
protected void Page_Load(object sender, EventArgs e)
{
var img1 = new ImageButton
{
ID = "ImageButton1",
AlternateText = "Button 1"
};
img1.Click += img_Click;
Panel1.Controls.Add(img1);
var img2 = new ImageButton
{
ID = "ImageButton2",
AlternateText = "Button 2"
};
img2.Click += img_Click;
Panel1.Controls.Add(img2);
}
private void img_Click(object sender, ImageClickEventArgs e)
{
var whoClicked = (sender as ImageButton).ID;
}
I have changed your Image server controls to ImageButton server controls to more easily accommodate the Click event.
Each of the two buttons is wired up to a common event handler and then in the event handler it is casting the sender (the control that initiated the event) to an ImageButton and then grabbing its ID to distinguish between the two buttons. You would want to put a null check there in case something besides an ImageButton initiates a click event.
Let me know if you need anything clarified or have further questions.

Javascript event handler fires "error: CS1026: ) expected" exception

I've created a table of dynamic controls which each row is a couple of (DropDownList and TextBox) then I've associated an event handler on each DropDownList selected change event so I can change on its TextBox as the code below shows :
DropDownList TypeDDL = new DropDownList();
TypeDDL.ID = "TypeDDL_" + rowN.ToString();
TypeDDL.Width = 120;
TypeDDL.Height = 20;
InitializeTypeDDL(TypeDDL);
TypeDDL.AutoPostBack = true;
TypeDDL.Attributes.Add("onchange", "javascript:handleFieldsDDLEvent(this);");
TextBox FieldsDDL = new TextBox();
FieldsDDL.ID = "FieldsDDL_" + rowN.ToString();
FieldsDDL.Width = 120;
FieldsDDL.Height = 20;
FieldsDDL.Attributes.Add("style", "float:right");
but the Javascript code of the event handler fires an exceptions telling:
function handleFieldsDDLEvent(e) {
var elementId = (e.target || e.srcElement).id;
var IdArray = elementId.Split('_');
var ControlId = "Control_"+IdArray[1].toString();
if (IdArray[1] != "") {
var FieldsDDL = document.getElementById("<%="+ControlId +".ClientID%>");
// error CS1026: ) expected
ValueTxtBx.style.display = "none";
}
}
In your javascript you have
var FieldsDDL = document.getElementById("<%="+ControlId +".ClientID%>");
The <%= ... %> parts are rendered on the server so it cannot be done this way in javascript.

Categories

Resources