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

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

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();";

Textbox (and other controls) - "Object not set to an instance...."

I realize this is a common error and I've followed the many fixes to this problem offered online but have yet to find a solution.
I developed a winform app which gets JSON from an external website. I click a button control and the app goes through my json serialiser method and posts the results to a textbox and appends to a textarea.
public void RenderData(string buttonText)
{
if (buttonText == "Start")
{
EquationData deserializedData = getData("http://test.ethorstat.com/test.ashx");
var processed = new ProcessEquation();
int result = processed.Calculate(deserializedData);
string res = deserializedData.parm1 + " " + deserializedData.op + " " + deserializedData.parm2 +
" = " + result;
TextBoxResult.Text = res;
equation.Append(" " + deserializedData.parm1 + " " + deserializedData.op + " " + deserializedData.parm2 +
" = " + result + '\n');
TextAreaResults.Value = equation.ToString();
}
}
This worked fine as it was. But requirements have changed in that the app has to poll data every second. Therefore I created a wcf web service called by a jquery script to run every second.
The problem is my controls - textbox and textboxarea - generate {"Object reference not set to an instance of an object."}. My assumption is that these controls aren't being loaded now that I'm calling the method from JQuery's ajax function (?).
$(document).ready(function () {
//while ($('#eThorButton').text != "Stop") {
if ($('#eThorButton').click) {
$.ajax({
url: 'Service/eThorService.svc/getUpdate',
method: 'get',
dataType: 'json',
success: function(){
alert("success");
},
error: function (err) {
alert(err);
}
})
//delay(1000);
}
});
My controls do show in intellisense and, of course, on Default.aspx when I run it. How can I fix this?
EDIT
I solved the 'Object not set...' problem by instantiating a new textbox:
public partial class _Default : Page
{
public static StringBuilder equation = new StringBuilder();
public TextBox TextBoxTest = new TextBox();
When I debug and step through the value is set, the textbox renders but the textbox is empty. How do I fix that?
Make your method static and add annotation [WebMethod] and return list of results.
[System.Web.Services.WebMethod(EnableSession=true)]
public static List<string> RenderData(string buttonText)
{
// return result here
}
Pass parameter with data:{buttonText:yourvalue} to $.ajax call. and change the success function and assign values to your control on client side via javascript.
success : function(msg){
if(msg.d!=null){
$('#<%=TextBoxResult.ClientID%>').val(msg.d[0]);
}
}

Dynamic textboxes with dropdownlist populated by database

I have a project where I need to provide functionality that allows a user to click a button (1 or more times) to dynamically add 2 textboxes with labels and a dropdownlist populated by a database call each time the button in clicked.
At first I was using jquery to add the 2 textboxes with labels but just had the requirement to add the dropdown populated by a database call.
I was using the following code for the jquery:
<script type="text/javascript">
$(document).ready(function () {
$("#btnAdd").click(function () {
var field = $("#field").val();
var input = "<input name='titles' id='field' type='text' />";
var input2 = "<textarea name='descriptions' id='field' rows='8' columns='80' />";
var newRow = "<tr><td>" + field + "</td><td>" + input + "</td><td>" + input2 + "</td></tr>";
var newRow2 = "<br /><label>Additional Issue: </label><br /><input type='text' size='50' name='addIssue' id='field' value='' /><br /><br /><label>Description:</label><br /><textarea rows='8' cols='80' name='addProblem' id='field' ></textarea><br /><br />"
$('#controls').append(newRow2);
});
});
</script>
That works great. However, I'm struggling with the best way to add in the dropdown, and it can be server side or clientside. I really haven't created asp.net controls dynamically, but I think that would be the way to go.
Any suggestions?
Well, to fit in with the rest of your design, you should probably just do it client side. You can create a select input pretty much just like you're doing your text inputs, then add options using AJAX call to a JSON web method. There are a lot of examples of this online, but here's one and here's another. And here's a third.

Click function on dynamically created table

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();
});

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