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.
Related
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();";
How can I loop through html controls inside an ASPX page which don't have "runat=server" attribute?
Because of using code blocks and dynamic variables on them I cannot add the attribute:
<input lang='<%= language.ID %>' checked='<%= check(x) %>' />
How can I loop through html controls inside an ASPX page which don't have "runat=server" ...
Depends on what you want you're looking to do.
As the other answers have stated, end of the day, it's all HTML and therefore a Form will submit (by default an HTTP POST for ASP.Net Web Forms hence Postback) somewhere and you can loop through HttpRequest.Form on the server side (aka "code-behind").
As stated, in the end everything renders as a standard HTML element that you can provide id or class and "loop" through them and do what you want on the front end.
Here's a trivial example:
var eles = document.getElementsByClassName('inputs');
var count = eles.length;
var str = "there are " + count + " elements:<br>";
for (var i = 0; i < count; i++) {
str = str + "name: " + eles[i].name + " id: " + eles[i].id + "<br>";
}
var result = document.getElementById("result");
result.innerHTML= str;
<input name="foo" lang='some-server-generated-string-1' id="ele1" class="inputs" />
<input name="bar" lang='some-server-generated-string-2' id="ele2" class="inputs" />
<p id="result"></p>
Hth.
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
I used a hidden field inside li tag in c#. please help me to get the value of hidden field in it..
public string text="";
for (var i = 0; i < dt.Rows.Count; i++)
{
text += "<li class=''>";
text += "<input type='hidden' id='hid_dtlid' name='hid_dtlid' value='" + dt.Rows[i]["Spindtlid"].ToString() + "'/>";
text += "</li>";
}
All the name attributes of the hidden field elements should be unique. This can be accessed on the server (provided they are all nested in a html form element). You simply make you use of Request.Form collection.
Say below is what your markup rendered by asp.net looks like
<form method="post" action="foo.aspx">
<!-- other stuff -->
<input type="hidden" name="fooField" value="bar"/>
<!-- more other stuff -->
</form>
Note that this is not an element marked with runat="server". And even if its so, you wouldn't know the difference unless you inspect carefully.
On the server-side you can access it as follows:
var value = Request.Form["fooField"]; //stores "bar"
In jquery it would be:
thevalue = $('#hid_dtlid').val()
If you're loking for server side on postboack Request.Form["hid_dtlid"]
Asp.net is nothing but a series of request and responsonses with some fancy absctration on top. The basics are still accessible through the Request and Response objects
Since you have not added these hidden fields as a C# hidden field object hence they will not be available directly.
However with post back these fields will be sent by the browser client in the header in Request.Form collection which can be extracted like below:
var hiddenElements = Request.Form["hid_dtlid"] ;//it will return an array of fields with name hid_dtlid
As you want to get the cotnrol value directly in c# you need to set runat="server" for that control asp.net web forms.
<input runat="server" type='hidden' id='hid_dtlid' name='hid_dtlid' value='" + dt.Rows[i]["Spindtlid"].ToString() + "' />
when it will post data you can get
var hiddenElements = Request.Form["ID"]
I want to collect action response using JS in ASP.NET C#. So on an ASP.NET Button click I am doing following
Button on ASPX page
<asp:Button ID="btn_add" runat="server" CssClass="button btn-entry"
Text="Add" OnClick="btn_add_Click"
Inside btn_add_Click , I have
bool continue_ = isEmpty_InputForm(input_form_index);
if (!continue_)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"onclick",
"<script type=\"text/javascript\">"
+ " var action_res = document.createElement(\"INPUT\");"
+ " action_res.type = \"hidden\";"
+ " action_res.name = \"action_res\";"
+ " action_res.value = null;"
+ " if (confirm('Are you sure?')) {"
+ " action_res.value = 'Yes';"
+ " }"
+ " document.forms[0].appendChild(action_res);"
//+ "confirm('Are you really sure?');"
+ " </script>",
false);
}
Then to collect the value of action_res JS var I am doing following
string action_res = Request.Form["action_res"];
The page gives me the confirm popup just fine, but action_res value is always null!
I am new to JS, can someone help me spotting the error please.
Think about it this way - if the posted page is generating that script, the server code is not waiting for the information from that confirmation dialog. It's always going to be null because the server doesn't know about var action_res; it wasn't establish before post back. Maybe handle the confirmation on the client side with JavaScript, set a hidden input up on your page (input id="confirmation_res" type="hidden" runat="server" />) and call string action_res = action_res.Value; in your C# code?