Click function on dynamically created table - c#

I have a table and it created dynamically.When i click the image then i need to remove the table row.In here click function is not working.
Dynamically created table.
row.append($("<td id="imageclose"><p>" + '<img src="' + '/Content/Images/crossimg.png' + '" width:"225px" height:"225px" />' + "</p></td>"));
Click Function
$("#imgclose").click(function () {
alert("asdfg");
});

Use class imageclose instead of id like following. Because id should be unique for each element.
row.append($("<td class="imageclose"><p>" + '<img src="' + '/Content/Images/crossimg.png' + '" width:"225px" height:"225px" />' + "</p></td>"));
You need event delegation for dynamically generated element.
$('body').on('click', '.imgclose img', function () {
$(this).closest('tr').remove();
});

You can not use of 'ID' because it should be unique. So instead of using ID use of class to fulfil your task.
First Way with onclick calling function.
row.append($("<td><p>" + '<img src="' + '/Content/Images/crossimg.png' + '" width:"225px" height:"225px" onclick="abc()" />' + "</p></td>"));
function abc() {
$(this).closest('tr').remove();
}
Second way with class attribute.
row.append($("<td><p>" + '<img class="myclass" src="' + '/Content/Images/crossimg.png' + '" width:"225px" height:"225px" />' + "</p></td>"));
$('#tableId').on('click', '.myclass', function () {
$(this).closest('tr').remove();
});

Related

Why I obtain a SyntaxError: expected expression, got '<) tryng to perform a redirection clicking a button into a SharePoint webpart?

I am pretty new in SharePoint (I am working on SharePoint 2013) and .NET and I have the following problem.
Into a Web Part I have a button and I have to insert a JavaScript redirect using the OnClientClick property. In my code I have done something like this:
ImageButton btnApplica = new ImageButton();
btnApplica.ToolTip = "Documento in Entrata";
//btnApplica.Click += btnApplica_Click_Scelta_Campi_Etichetta;
btnApplica.OnClientClick = "<script>"
+ "function() {"
+ "window.location.href = '" + SPContext.Current.Web.Url + "/MYPROJECTNAME WEBPART/Carica documento.aspx?mode=scelta_campi_facoltativi_etichetta&obj='" +obj
+ ";return false;"
+ "}"
+ "</script>";
//btnApplica.Click += btnApplica_Click;
//openButton.OnClientClick = "return false;";
btnApplica.ID = "btnEntrata";
btnApplica.ImageUrl = "/_layouts/15/images/myprojectname/Default/Ribbon/DocEntrataRibbon.png";
LinkButton text = new LinkButton();
text.Text = "Documento in Entrata";
text.ID = "btnEntrataTxt";
text.Width = 80;
//text.Click += btnApplica_Click;
//text.Click += btnApplica_Click_Scelta_Campi_Etichetta;
buttondiv.Controls.Add(btnApplica);
buttondiv.Controls.Add(new LiteralControl("<br/>"));
buttondiv.Controls.Add(text);
ribbondiv.Controls.Add(buttondiv);
As you can see, I am trying to create an "in client" redirection so I used the OnClientClick property on this button. I defined a simple JavaScript function to perform the rediration that end with the return false to avoid that the entire page is reloaded after the button click, this:
btnApplica.OnClientClick = "<script>"
+ "function() {"
+ "window.location.href = '" + SPContext.Current.Web.Url + "/MYPROJECTNAME WEBPART/Carica documento.aspx?mode=scelta_campi_facoltativi_etichetta&obj='" +obj
+ ";return false;"
+ "}"
+ "</script>";
This code section have some problem, clicking on my button it happens that:
The HTTP POST request is performed to the correct URL:
http://mymachine:8080/Protocollo/pg/MYPROJECTNAME WEBPART/Carica documento.aspx?mode=ant&obj=17&IsDlg=1
(I see it by the Network tab in Firefox, it seems to me absolutly correct)
But the page is entirely refreshed (so I don't obtain the section replacement that I expect).
Looking into the JavaScrip browser console I obtain this error message:
SyntaxError: expected expression, got '<'
So I think that something went wrong defining the second statment of my simple JavaScript function (the return false).
I am doing:
+ ";return false;"
because I am appending the ; symbol to say that the previous statment is complete (the window.location.href=.... that performs the redirection) and it is follwed by the return false.
I am going crazy and I can't understand what is wrong...maybe some symbol or missed escape.
What is wrong? What am I missing? How can I fix this issue?
I think error can be when you are using <script> tags in OnClientClick value.
Write like this:
btnApplica.OnClientClick = "var ClickMySuperButton = function() {"
+ "window.location.href = '" + SPContext.Current.Web.Url + "/MYPROJECTNAME WEBPART/Carica documento.aspx?mode=scelta_campi_facoltativi_etichetta&obj='" +obj
+ ";return false;"
+ "}; ClickMySuperButton();";
or add your script somewhere on ascx page:
function ClickMySuperButton(){
};
and use in code-behind like this:
btnApplica.OnClientClick = "ClickMySuperButton();";

Input button created by SignalR method won't cause jquery click event

I'm looking to create an add/remove rights sheet for a user. On this page, there is a list of available rights in a list, and another list with their current rights. I want to be able to click a remove button on their current rights and move that right to the available rights. And then be able to click an add button on the available rights to move it to their current rights.
Here's the code
$(function ()
{
var test = $.connection.testHub;
test.client.updateAssigned = function (departmentId, departmentName)
{
$('#assigned').append("<tr><td>" + departmentName + " (" + departmentId + ")</td><td><input id='" + departmentId + "' type='button' value='Remove' class='btn btn-default' /></td></tr>");
};
test.client.updateAvailable = function (departmentId, departmentName) {
$('#available').append("<tr><td>" + departmentName + " (" + departmentId + ")</td><td><input id='" + departmentId + "' type='button' value='Add' class='btn btn-default' /></td></tr>");
};
$.connection.hub.start().done(function ()
{
$("input").click(function ()
{
var val = $(this).val();
var id = $(this).attr('id');
if (val == "Remove")
{
test.server.removeDepartment($('#job').val(), id);
$(this).closest('tr').remove();
}
if (val == "Add")
{
$(this).closest('tr').remove();
}
});
});
});
So the buttons created on page load work perfectly, in that when they are clicked, it removes their table row and moves it to the other table. However, that newly created button does not remove and move to the other side. I'm not sure if this is a limitation where if an HTML tag is created after page load won't be allowed to be selected by jquery? Any help would be appreciated!
You created your <input> tag after adding event handlers to all existing <input> tags.
Therefore, you never added any handlers to the new one.
You should call the delegating form of .on(), passing a container and a selector that matches children.
Documentation

JavaScript dialog using AJAX call is out of sync

I'm having a problem with some JavaScript which is intended to display a JQUERY dialog box based on a C# ViewModel.
I have an ASP drop down within a repeater which displays 'Registration Date' information. The idea is when the user selects a date from the list, the JavaScript dialog box will appear displaying a more rounded summary of information relating to that registration using specific View Model properties. The function CustomerSummary is called on a standard $(document).ready for the page in question.
JS Code
function CustomerSummary() {
var registrationId;
var data;
$("select[id$='ddlRegistration']").change(function () {
registrationId = $(this).val();
if (registrationId !== 'default')
{
data = MakeAJAXCall(registrationId);
$("#dialog").html("Registration Id: " + data.RegistrationId + "<br />" +
"Permit From: " + data.PermitFrom + "<br />" +
"Permit To: " + data.PermitTo + "<br />" +
"Registration Status: " + data.RegistrationStatus
);
$("#dialog").dialog({
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
}
});
function MakeAJAXCall(regId)
{
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "text json",
url: "/Secure/CustomerSummary.aspx/GetRegistration",
data: "{ regId: \"" + regId + "\" }",
success: function (msg) {
data = msg.d;
},
error: function (xOptions, textStatus)
{
console.log(textStatus);
console.log(xOptions);
}
});
}
}
C# Code
[WebMethod(), ScriptMethod(UseHttpGet=false)]
public static RegistrationViewModel GetRegistration(int regId)
{
RegistrationRepository repo = new RegistrationRepository();
RegistrationViewModel reg = new RegistrationViewModel();
RegistrationFactory regFac = new RegistrationFactory();
reg = regFac.ConvertToRegistrationViewModel(repo.GetRegistration(regId));
return reg;
}
What is happening during debug
What is happening here is on this line :
$("#dialog").html("Registration Id: " + data.RegistrationId + "<br />" +
I'm getting the error:
Uncaught TypeError: Cannot read property 'RegistrationId' of undefined
The first time I select a date from the menu and the change function is invoked, I get the above error message, and no dialog box appears, if I inspect data I can indeed see that it is undefined. Then, once I select a different data from the drop down menu, and I hit my breakpoint (change.(function) data is set to the data retrieved from the previous AJAX call, the dialog box then pops up but with the previous requests data, the results then stay in this cycle, every time I select a data I am presented with the previous selections information.
Can anyone point out why im constantly one selection out of sync, I believe its due to the first change request but I don't understand why the AJAX call isn't setting data to the desired result until I select the next drop down item.
This will not work
data = MakeAJAXCall(registrationId);
Because MakeAJAXCall is performing an Ajax call and it is asynchronous so the return will not execute in the same order as your return in the function. So, you need to use a callback.
Try this to change your code to something like:
MakeAJAXCall(registrationId, function(data){
$("#dialog").html("Registration Id: " + data.RegistrationId + "<br />" +
"Permit From: " + data.PermitFrom + "<br />" +
"Permit To: " + data.PermitTo + "<br />" +
"Registration Status: " + data.RegistrationStatus
);
});
Then on your Ajax Call you need to make this change as well:
function MakeAJAXCall(regId, callback)
{
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "text json",
url: "/Secure/CustomerSummary.aspx/GetRegistration",
data: "{ regId: \"" + regId + "\" }",
success: function (msg) {
data = msg.d;
callback(data); //<--- You callback function is called here
},
error: function (xOptions, textStatus)
{
console.log(textStatus);
console.log(xOptions);
}
});
}
First A in Ajax is for asynchronous. It means your call will run in the background and that is why you use callbacks. When your call completed with success/error, say 10 seconds later, correct function is called. In the meanwhile, you other code that sets up and creates a result also runs, most likely before any answers received from ajax query. As #Dalorzo suggested, wrap your result dialog code in a callback, so your code will run after results received.

How to create MultiLevel Dynamic dropdown using jquery

I am trying to create Multilevel Dropdown.
I have default dropdown with values
Ex. Parent Dropdown with Id='ddl1'
If we select value from it then load data from server with selected and Create new dropdown name as child dropdown, and again select value from child and load data from server, if data present then create child dropdown.
we have to create drowpdown, till n level.
'Ex. i am creating like below'
function createdropdown(id) {
var labelHtml = "<tr id='trFormType" + id + "' class='trFormType'><td><label class='tdLabel'>" + labelFormType + " * </label></td>";
labelHtml += "<td><select class='ddlFormType' id='ddlFormType" + id + "' name='ddlFormType" + id + "' >";
labelHtml += "<option value=''";
labelHtml += ">" + labelSelect + "</option>";
labelHtml += "</select></td></tr>";
return labelHtml;
}
var selectedId=''; $(".ddlFormType").live("click", function () { selectedId= "#" + $(this).prop('id'); });
$(selectedId).live("change", function () { $.ajax({ url: Url + 'Method/' + (selectedId).val(), type: 'GET', dataType: 'json', cache: false, timeout: 9000, success: function (data) { $("#detailTable tbody").append(createdropdown(currentId)); }
});
'But .change event not get fired, for dyncamically created dropdown'
'Hope you can understand?'
For creating n level dropdowns you need to create a dropdown in ajax callback like this:
$.ajax({
url: "Your URL",
method: "GET",
dataType: 'json',
success: function (data) {
$("Your Dropdown Conatiner").append("<select><option name="option1" value="1"></option>...</select>");
},
error: function (data) {
}
});
It think your problem is that you are creating the select after the DOM has been fully loaded and jQuery has already registered all events.
If you want to add dinamically N selects you should include a call to register it inside the code you are adding to the DOM, check this sample:
<div id="select-container"></div>
<script>
function CreateSelect(id){
return `<select id="ddl` + id + `">
<option value="Opcion">Opcion<\/option>
<option value="Opcion2">Opcion 2<\/option>
<\/select>
<script>
RegisterSelectChangeEvent(` + id + `);
<\/script>`;
}
function RegisterSelectChangeEvent(id){
console.log("Event Raised");
$("#ddl" + id).on("change", function (e) {
jQuery("#select-container").append(CreateSelect(id+1));
});
}
(function(){
jQuery("#select-container").append(CreateSelect(1));
})();
</script>
You can see it working here:
https://codepen.io/anon/pen/LQRqYY

Finding Id, Text of Input types through C#

I have saved input (text,checkbox,dropdownlist) in one html page, and am loading that in asp:panel, after loading users can enter values in that. Now by Clicking Asp:button i have to find that input types and save to database, how can it achieved.
the input code will be in this format .
<label style="left: 46px; top: 73px; position: relative;" id="Llb1" onmouseup="MLup(this.id)" class="ui-draggable" onmousedown="MLdown(this.id)"> Enter the value </label>
<input style="left: 170px; top: 113px; position: relative;" id="T1" onmouseup="mUp(this.id)" class="ui-draggable" onmousedown="mDown(this.id)" value="" type="text">
This input types i have to find those ids, and text... how can it possible..
First of all, you can't get label's value on server. For getting dynamic textbox value you need to assign name attribute on it and get value on postback from Request.Form collection by that name.
You have at least two options to achieve it.
Create some hidden fields also along with the fields you are creating and put the field type value and other required meta data in the hidden fields. When you post the form, these hidden fields will serve you the metadata about the form which you can use to properly insert it in database.
or
When you dynamically create the control, inform the server about it using ajax request so that server has prior knowledge of these fields. You can store this information in session and when the form post back, you can use it to obtain the data from request object.
In either case, you have to use the raw request object to get the values of the fields as asp.net will not parse those fields which were not present on the page as they will not be the part of view state.
It is a good idea to post the entire form using ajax rather then posting it in normal way. This way, you could be sure that only the dynamic data is posted.
Here i got a solution for finding the id of text,select, labels through html Button click
<input type="button" id="save" value="submit" onclick="submitpage()" />
then on submitpage
<script type="text/javascript">
function submitpage() {
var completeids = new Array();
var completevalues = new Array();
var completetype = new Array();
var completeselected = new Array();
var labelvalues = new Array();
// var name = "abc";
var name = document.getElementById('<%=username.ClientID %>').innerHTML
$('input[type="text"]').each(function () {
completeids.push($(this).attr('id'));
completetype.push('TEXTBOX');
completevalues.push($(this).attr('value'));
completeselected.push('no');
});
$('label').each(function () {
completeids.push($(this).attr('id'));
completevalues.push($('label[id= ' + $(this).attr('id') + ']').html());
labelvalues.push($('label[id= ' + $(this).attr('id') + ']').html());
completetype.push('LABEL');
completeselected.push('no');
});
$('select').each(function () {
completeids.push($(this).attr('id'));
completevalues.push($(this).val());
completetype.push('DROPDOWN');
completeselected.push('no');
});
$('input[type="checkbox"]').each(function () {
completeids.push($(this).attr('id'));
completevalues.push($('label[for=' + $(this).attr('id') + ']').html());
completetype.push('CHECKBOX');
completeselected.push($(this).attr('checked'));
});
$('input[type="radio"]').each(function () {
completeids.push($(this).attr('id'));
completevalues.push($('label[for=' + $(this).attr('id') + ']').html());
completetype.push('RADIOBUTTON');
completeselected.push($(this).attr('checked'));
});
$('input[type="file"]').each(function () {
completeids.push($(this).attr('id'));
//completevalues.push('not yet done');
completevalues.push($(this).attr('value'));
completetype.push('FILE');
completeselected.push('no');
});
var loc = window.location.href;
$.ajax({
type: 'POST',
url: loc + "/GetSaved",
data: "{getcompleteids :'" + completeids + "',getcompletevalues :'" + completevalues + "',getcompletetypes :'" + completetype + "',getcompleteselected :'" + completeselected + "',getlabelvalue :'" + labelvalues + "',formname:'"+name+"'}",
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response) {
alert(response.d);
});
}
</script>
at c# code i have used like this...
[WebMethod]
public static string GetSaved(string getcompleteids, string getcompletevalues, string getcompletetypes, string getcompleteselected, string getlabelvalue, string formname)
{
string[] completeids = getcompleteids.Split(',');
string[] completevalues = getcompletevalues.Split(',');
string[] completetypes = getcompletetypes.Split(',');
string[] completeselected = getcompleteselected.Split(',');
string[] labelvalues = getlabelvalue.Split(',');
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dynamic"].ConnectionString);
string FORMNAME = labelvalues[0];
for (int i = 0; i <= completeids.Length-1; i++)
{
con.Open();
//FORM_NAME, USER_NAME ,CONTRO_TYPE, CONTROL_ID, CONTROL_VALUE, CONTROL_SELECTED
SqlCommand cmd = new SqlCommand("INSERT INTO CONTROLS_INFORMATION VALUES('" + FORMNAME + "',' "+formname+" ','" + completetypes[i] + "','" + completeids[i] + "','" + completevalues[i] + "','" + completeselected[i] + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
return "successfully";
}
It was done..
Hope it will be useful to some one like me..hmm...

Categories

Resources