I have a list in my aspx page where the values for the list are coming from the database. The data can be added to the list successfully
But how can I retrieve the value of the selected list item when I click on that? (ul_Click event)
I don't want to redirect to another page because I'm using AJAX. so i want it in the same page. that's why i commented the
<ul runat="server" id="ulList" onclick="ul_Click">
</ul>
The data is binded to the list in the page_load event.
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("Server=NIPUNA-PC\\SQLEXPRESS; Database=XXX; Trusted_Connection=True");
string[] itemList = authorList();
foreach (string item in itemList)
{
HtmlGenericControl newLi = new HtmlGenericControl("li");
//newLi.InnerHtml = "" + item + "";
newLi.InnerText = item;
ulList.Controls.Add(newLi);
}
}
I want the ul_Click() event?
seems like you were on track with the innerHtml thing. You can pass some kind of an ID with the link.
"" + item + "";
then do a request querystring and check for that id. if it's there, then call a function?
i'm not 100% sure, but what you're trying to do might be impossible otehrwise with HtmlGenericControl. I don't think you can bind an onclick event to HtmlGenericControl
Your other option is perhaps go with ajax/javascript
EDIT> just saw the comment. so .... you might do something like
"" + item + "";
you could also do
"" + item + "";
i personally dislike the last one as <a href="#" version because it can cause bad client side behavior such as to go to page top or something stupid like that when clicked.
just to wrap things up. Keep in mind that you'll need a client side javascript to handle the function
<script language="javascript">
function callMyAjaxFunction(bookid){
// do something
}
</script>
adding to robert's ideal instead of including item twice in the markup, you might do
" + item + "
<script language="javascript">
function callMyAjaxFunction(e){
alert(e.innerHTML);// do something
}
</script>
Related
I'm trying to make it so if your Session["LoggedIn"] is true, the wuc (Web User Control, which is the Navbar and is connected to the MasterPage which is connected to the page) prints a logout button.
so I have it like this:
Response.Write("<a runat='server' ID='lblLogout' class='nav-link' CausesValidation='False' OnServerClick='lblLogout_Click'>Logout</a>");
the CodeBehind function looks like this:
protected void lblLogout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Session["LoggedIn"] = false;
Session["IsAdmin"] = false;
Session["Username"] = "";
}
now, I've tried everything, if I use response.write like that, I can't click it, it just doesn't fire or do anything, if I don't use it inside Response.Write, it does work..
I even tried prinitng an asp:LinkButton instead to see if that works, but it doesn't print out anything when I use it like:
Response.Write("<asp:LinkButton class='nav-link' runat='server' ID='lblLogout' Text='Logout' CausesValidation='False' OnClick='lblLogout_Click' />");
Now the solution that I found was putting another page for logout and placing the function on PageLoad, which works, but I'm wondering if I can make it work so I can use the function from CodeBehind, instead of having to go to another page.
my working solution:
if ((bool)Session["LoggedIn"] == true)
{
Response.Write("<li class='nav-item'> <a runat='server' ID='lblLogout' class='nav-link' CausesValidation='False' href='../PagesForVisitor/wfLogout.aspx'>Logout</a></li><li><a class='navbar-brand' href='#'><img src='" + GetSource() + "' width = '30' height = '30' alt = ''/ ></a></li>");
}
(this one prints out a profile pic as well)
p.s using Bootstrap for styling, not sure if that matters, thanks a bunch..
You should use
<asp:Button id='' runat='server'>
tag
or use css to custom the button look depending on the style.
You can make it a hyperlink in the properties.
Hi it just so happens that I have to need this kind of approach (or any suggestion if you have)
this code produce table
while (rd.Read())
{
resultsHtml.Append("<tr class='odd gradeX'>");
resultsHtml.Append("<td>" + rd["region_location"].ToString() + "</td>");
resultsHtml.Append("<td>" + rd["region_tag"].ToString() + "</td>");
resultsHtml.Append("<td class='center'>");
resultsHtml.Append("<div class='tooltip-demo'>");
resultsHtml.Append("<a class='btn btn-info' href='regionEdit.aspx?id=" + rd["region_id"].ToString() + "'><i class='fa fa-paw'></i></a> ");
resultsHtml.Append("<asp:Button ID='btnDelete' runat='server' Text='Login' CssClass='btn btn-outline btn-primary' Style='width: 100px;' OnClick='btnDelete_Click' />");
resultsHtml.Append("</div>");
resultsHtml.Append("</td>");
resultsHtml.Append("</tr>");
}
if you will notice there is an asp:button there. because i want that if the user clicks that button, it will just delete it. So I put an
public void btnSubmitDelete_Click(object sender, EventArgs e)
{
}
but the things is. It is not displaying and I can't figure out how to put the region_id in the asp:button to determine which is which to delete and every loop of the while. Please help
i think when u want to add an asp control and show that control to end user u should add dynamically control to a placeholder or panel like this code :
<asp:PlaceHolder runat="server" ID="_plchControles"></asp:PlaceHolder>
and in code bihind :
var btn = new System.Web.UI.WebControls.Button();
btn.Text = "sample";
btn.ID = "btnSubmitDelete";
btn.OnClientClick += btnSubmitDelete_Click;
_plchContent.Controls.Add(btn);
Your script will work as HTML control and you can bind click event from Javascript. To do so define a WebMethod in c# and call it from Javascript click event.
e.g.
$("#btnDelete").on("click",function(e)
{
var para=[]
para.param1=val1;
para.param2=val2;
$.post("/path/delete",para,function(result)
{
});
});
C#
[WebMethod]
public void delete(string param1,string param2)
{
//Delete code here
}
else
mohammadreza izadi answers will work if you want to asp.net control but you have to make object of button as defined not string.
I'm trying to get jQuery to bind an onClick function when the document loads to my radio buttons.
ASP goes back to the database and finds all the open markers and then it sends a response to the page with the raw HTML to make a radio button and an image of the marker. What I need to do is have jQuery (or anything for that matter) bind an onClick that will signal what one is clicked so I can send that markerId back to the database to attach it to a person.
Here is a rough jsFiddle of what I've tried so far. In debugging I added alerts in the each function and I see them 3x like I should but the attr('id') comes back undefined.
This is the html that puts the radio buttons on the form
<br />
<p>Select open marker for new user:
<% getMarkers(); %>
</p>
This is the codebehind for that call
while (reader.Read())
{
if (readIndex % 3 == 0)
markerTable += "<tr>";
string markerId = reader["marker_id"].ToString();
string fileName = reader["marker_filename"].ToString();
markerTable += "<td><input type=\"radio\" name=\"openMarker\" value=\"" + markerId + "\" " +
"id=\"oMrk" + markerId + "\"><label for=\"oMrk" + markerId + "\"><img src=\"/Markers/" +
fileName + "\" /></label></input></td>";
readIndex++;
if (readIndex % 3 == 0)
markerTable += "</tr>";
}
if (readIndex % 3 != 0)
markerTable += "</tr>";
markerTable += "</table>";
}
else
markerTable = "<p>No empty markers. Please delete a user to continue.</p>";
sCon.Close();
return markerTable;
The fiddle I posted has the source pasted into it from this function.
I have two questions.
Why does this not work? It seems like it should, I am getting 3 elements from my jQuery selector statement, It's being called from $(document).ready() why are the attributes undefined?
Is there a better way to do this? I was planning on putting the value in a page variable and then sending it with an ASP button back to the server to a stored procedure to add that marker with some text from another field back to the database. I realize I could add the onClick event into the response html, but dang it I need to understand why what I'm doing isn't working.
I'm pretty new to web, so if I am way off the mark procedurally, I am open for suggestion.
LINK
$(document).ready(function () {
$('input:radio').each(function (radElem) {
var radId = $(this).attr('id');
alert(radId);
});
$('input:radio').on('click', function () {
alert('Clicked');
});
});
$(document).ready(function () {
$('input:radio').on('click', function() {
alert($(this).attr('id'));
});
});
Do you need to send the value to the server while staying on the page? (via ajax)
or do you need to post the form to another page?
It doesn't work because you are trying to bind onClick instead of
just click
The other answers have provided the jQuery for you. In the each you
just need to use this keyword
I tested this in a fiddle, it works. Others have provided similar answers, but here's the fiddle anyway: THE FIDDLE
$(document).ready(function () {
$("input:radio").each(function () {
var radId = $(this).attr('id');
alert(radId);
$(this).on('click', function () {
alert('Clicked');
});
});
});
As for a better way to do what you are trying to accomplish, I do not have a firm grasp of what you are trying to do really, sorry. It feels though, like you should be initially populating this in asp.net, but the constraints of your page may not make this possible. I can't say.
Also, go ahead and pick one of the previous answers, I just wanted to explain to you why what you had wasn't working.
I created a javascript confirm as below.
<script Type="Text/Javascript">
function CheckListBox(lvi)
{
if(lvi == "")
{
if(confirm("Are you sure?"))
{
return true;
}
else
{
return false;
}
}
}
</script>
I need to test if the ListBox.Items control is empty... I already made reference on my aspx page
<script language="javascript" type="text/javascript" src="/JS/confirm.js"></script>
I want to know how to call it on my aspx.cs page . . . So I can pass the parameter:
string oi = Listbox_Clubes.Items.Count.ToString();//Its the parameter I want to pass
See this link for how to execute javascript from code behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "CheckListBox(" + Listbox_Clubes.Items.Count.ToString() + ");", false);
}
Note: you must add a ScriptManager control in aspx page.
For your javascript, you can get the value without the code-behind (this assumes the script code is in the same page, in order to get the client ID):
<script>
function ClickListBox() {
if ($("#<%= Listbox_Clubes.ClientID %>").val() === null) {
if (confirm("Are you sure?")) {
return true;
}
else {
return false;
}
}
}
</script>
Similarly, you don't use javascript to validate on the server side. The code you posted will return all items in the ListBox. Here is one way to get the count of the number of selected items (I'm using .ToString() based on the OP code example):
string oi = Listbox_Clubes.Items.Cast<ListItem>().Where(i => i.Selected).Count().ToString();
However, there is no reason why you would get this value and pass it back to the client-side to do validation (what it sounds like you want to do in your post). Mainly because this involves a post-back, and client-side validation, by its nature, should occur before post-back. Also, you will still need to do server-side validation, even when you have client-side validation.
Related: in the code-behind, you can test to see if anything is selected by:
bool hasValue = Listbox_Clubes.SelectedItem != null;
The .SelectedItem returns the selected item with the lowest index in the list control. When nothing is selected, this value is null... so you know if the value isn't null, then at least one item was selected.
If you want to require that they choose at least one item, you can use a RequireFieldValidator and let that handle both validations. If you haven't done much with ASP.NET validators, that would be one good thing to read up on.
It sounds like you probably should read more about client-side validation and server-side validation and how to use them... because it seems like you are mixing them up.
The count code is a modified version of code in ASP:ListBox Get Selected Items - One Liner?
So I have a text box, where I add an onchange event of markAsException.
My javascript is -
function markAsException(recordID) {
//alert("Exception");
//mark exception column
document.getElementById("ctl00_cpMain_lblScrollException_" + recordID).innerText = "Exception";
document.getElementById("ctl00_cpMain_lblScrollException_" + recordID).style.color = "#FF0000";
document.getElementById("ctl00_cpMain_tdScrollException_" + recordID).style.backgroundColor = "#99CCFF";
//enable comments ddl and remove blank (first item)
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).disabled = false;
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).focus();
document.getElementById("ctl00_cpMain_ddlCommentId_" + recordID).options[0] = null;
}
What I want to do is, when a user changes the value in a textbox, to mark a column as "Exception", and then focus a drop down list where they have to chose the reason for the exception.
This is what happens.. If I am on that text box and change it, then tab, it tabs to the drop down list.
However, if I change the value and then simply click in another text box on the form, I don't focus the drop down list.
How would I accomplish that?
I would suggest using JQuery's change() function.
The advantage is that it will be more stable across different browsers.
Something like:
$('#<%= TextBox1.ClientID %>').change(function(){
// extract the recordID from the textbox - perhaps with an attribute?
markAsException(recordID);
});
My comment was getting longer so I'm expanding:
Take a look at the JQuery documentation for setting this up as the page finishes loading. If tb is the ID of your textbox your selector would be
$('#<%= tb.ClientID %>')
I would suggest you replace your code and use
tb.Attributes.Add("recordID", recordId.ToString());
This will add the ID you need onto the textbox tag. Once you're in the function I outlined above you can use the following selector to get the recordID in javascript
var recordID = $('#<%= TextBox1.ClientID %>').attr('recordID');
All together
$(document.ready(function(){
$('#<%= tb.ClientID %>').change(function(){
var recordID = $('#<%= tb.ClientID %>').attr('recordID');
if(recordID){
markAsException(recordID);
}
});
});