I have a web form in asp.net coding with vb and it has multiple textboxes and buttons. If one textbox is empty, I would like one button to be clicked if the enter key is pressed, whereas if a different textbox is empty, I would like the other button to be clicked, when the enter key is pressed. I know I can change the default button in the form section, but I don't know how I could go about changing the default button depending on which textbox is empty? I assume I have to do this in javascript, which I have little understanding of so any help would be much appreciated.
Can I do something like this to change the default button?
If txtMembranePressure.Text = "" Then
Dim sb As New System.Text.StringBuilder()
sb.Append("<form id='form1' runat='server'" + "defaultbutton='btnMembranePressure'")
Else
Dim sb As New System.Text.StringBuilder()
sb.Append("<form id='form1' runat='server'" + "defaultbutton='btnDiamondPressure'")
End If
Could I put the default button directly on the form like this?
Would it not be better to have one click routine - all buttons can freely point to that one click routine - but inside of that click routine, you can freely check the value(s) of the given text boxes, and then run the desired code. This seems a whole lot less complex then trying to change what actual button supposed to be clicked. So, have all buttons run the SAME routine, but that routine can simple check which text boxes have values in them.
Then based on what text boxes have (or have not) a value, you simple run or call the code you want based on this information.
Keep in mind, that in most cases, hitting enter key will trigger the button that FOLLOWS the control in the markup after that text box.
Edit: correction: the FIRST button on the page will trigger.
However, you can TURN OFF this behavour by setting in the button markup usesubmitBehaviour=False
<asp:TextBox ID="txtSearchOC" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button"
UseSubmitBehavior="False" />
In fact, if you drop a text box on a form, then say a gridview with 10 rows, and each row of the gridviewe has button with click event? Hitting enter key in above will in fact trigger the FIRST row button click of the gridview!!!
So, often by correct placement of buttons, say like a search text box, and a button after to click "search data", then in fact, if they hit enter key, the button that follows that text box will trigger anyway. (as noted, first button on markup fires - not any button, or not actually the one that follows the textbox).
So, in some cases, the correct order of a text box, and the button that follows can be put to good use here. But, often it can surprise you. You drop in a text box, and a form has 10 buttons that follow, ONE of them WILL trigger when you hit enter key - and this can often be harder to PREVENT this from occurring.
So, keep the above in mind. but, given that you want code to run based on values in text boxes (or lack of values), then I would have ONE routine that the button clicks ALL use, and the code behind can then check the text box values, and take the desired course of action and run your desired code based on this information.
There are 3 steps to do.
You need to know, when a Textbox is changed. For that you can use the TexboxChanged Event.
You need to know, if the Textbox is empty.
You need to know, how to change the default button.
Every Textbox need a TextboxChanged Event. And in every event you should check, if the Textbox is empty. If it is empty, you should set it to default.
In Pseudocode:
if Textbox.Text = "" then
set Textbox to default
For further information on the Textbox Change EVent, search in a searchengine (for example duckduckgo.com) for "textbox changed event":
https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/
To change the default button, please consider following Answers at Stackoverflow:
How to set the default button for a TextBox in ASP.Net?
I have provided you with sufficient detail and example code below to re-engineer this yourself, even if I have not quite understood your requirement. I do agree with the comments above, this is probably not the best approach. You are better off checking server-side whether text boxes are populated or not, and then following a different path in your code.
JQuery lets you find elements by class name (CssClass="" in .NET, class="" on a normal HTML element)
$(".ClassName") makes JQuery find all elements with that class name on the page.
$("#Id") makes JQuery find all elements with that Id on the page.
data-whatYouWantToStore is a convenient way of storing data against an element, that you can then read with Javascript / JQuery. Just keep it all lower case to avoid upsetting it.
$(element).data("the name after the data- bit") will get you the value.
The only bits you need to change to make it run are on the text-boxes:
data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"
Set the class of the button you want it to click when enter is pressed, if the textbox is empty in the data-targetbuttonemptyclass property, and the button to click if text is present in the data-targetbuttonnotemptyclass property. Text boxes must have the class js-click-if-not-empty set on them if you want them to be handled by the "empty / not empty" JavasScript.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Buttons.aspx.vb" Inherits="Scrap.Buttons" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<!--Add reference to Jquery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!--Your Javascript -->
<script type="text/javascript">
$(document).ready(function () {
// find all the buttons we want to set this behaviour on
$(".js-click-if-not-empty").each(function () {
// add a keypress event hander to each button
$(this).on("keypress", function () {
// get the key that was pressed
var keycode = (event.keyCode ? event.keyCode : event.which);
// is it the ENTER key?
if (keycode === 13) {
// prevent anything else that was going to happen because enter was pressed.
event.preventDefault();
// is the textbox empty?
if ($(this).val() === "") {
// yes - get the css class of the button to click when the textbox is empty
var button = $("." + $(this).data("targetbuttonemptyclass"))[0];
// just for debugging to show which button is about to be clicked
alert("going to click empty button: " + button.id);
// click the button
button.click();
} else {
// no - get the css class of the button to click when the textbox is not empty
var button = $("." + $(this).data("targetbuttonnotemptyclass"))[0];
// just for debugging to show which button is about to be clicked
alert("going to click not empty button: " + button.id);
// click the button
button.click();
}
};
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tb_TextBox1" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:TextBox ID="tb_TextBox2" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:TextBox ID="tb_TextBox3" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:Button ID="btn_ClickIfEmpty" runat="server" CssClass="js-button-1" Text="Click If Empty" />
<asp:Button ID="btn_ClickIfNotEmpty" runat="server" CssClass="js-button-2" Text="Click If Not Empty" />
</div>
</form>
</body>
</html>
i'm quite new developing for asp.net and found a problem i can't figure it out.
My .aspx look like the follow:
<form action="#" class="" runat="server" >
<asp:DropDownList ID="ddlCombo" runat="server">
</asp:DropDownList>
</form>
<div class="clsbox-1" runat="server">
<div class="dropzone clsbox" id="mydropzone">
</div>
</div>
As you can see i have a dropdownlist that i will populate on page_load and a dropzone inside a div (i need to be this way).
<script>
Dropzone.autoDiscover = false;
$("#mydropzone").dropzone({
url: "WebForm1.aspx?param=1",
addRemoveLinks: true,
maxFilesize: 0.5,
dictDefaultMessage: 'drag and drop',
dictResponseError: 'Error uploading file!'
});
<script>
this is the script that make div like a dropzone, i'm not sure if the url is right though.
The problems comes when in the page_load part, since i need to populate the dropdownlist on page load,
when i try to upload a file via dropzone it will be sent as postback and enter in the 'if' and populate again the combobox, reseting the value that was selected.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
loadCombo(); //populate ddlCombo
}
string aux = ddlCombo.SelectedValue.ToString();//this will have the first item
//processing file...
}
Please let me know if there is any fancy way to do this because i can't figure it out!
EDIT:
I don't understand why if i send within a form it work as intended:
<form action="#" class="dropzone" runat="server" >
<asp:DropDownList ID="ddlCombo" runat="server">
</asp:DropDownList>
<div class="clsbox-1 " id="mydropzone" runat="server">
<div class="clsbox" >
</div>
</div>
</form>
When i upload a file here it doesn't send as post back.
Thx you!
Your dropzone url parameter should be to a different page/httphandler/controller you have created to accept the upload and save it to a file (or whatever you want to do with it). You could technically use the page you're currently on, but it'd be a little trickier in your situation as you'd need to detect what caused the postback and handle appropriately (ie don't reset the dropdown).
I would recommend using an HttpHandler instead of a normal page for receiving the files. Here's an example of one.
I have a dynamically named DIV in a GridView which contains a user control with a dynamically assigned Parent_ID. The javascript is used to show or hide the DIV. I'll show you two examples of different rows without the ASP code.
Row 1 showing for Order # 123456:
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel123456');" %>" >+</a>
<div id='Order_Notes_Panel123456' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='123456'/>
</div>
Row 2 showing for Order # 678901:
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel678901');" %>" >+</a>
<div id='Order_Notes_Panel678901' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='678901'/>
</div>
The good news is that the user control binds and works perfectly. The javascript shows (sets the style to "display:block;") and hides (style set to "display:none;") the appropriate DIV each time the '+' is clicked.
Here is my problem: there is a 'Reply' link in the user control that, when clicked, does a post-back and puts the control into Edit mode. When I employ this user control on another page without a containing DIV, you won't notice a thing. However, when the 'Reply' does its post-back, the containing DIV reverts back to style="display:none;".
Can you provide a recommendation how to set the parent DIV's style to "display:block;" while a user is obviously working with it? I would imagine the appropriate code would go in the code behind of the user control when it goes into Edit mode.
Thanks,
Rob
Update: I recognize that there is no runat=server in my DIV. Since I'm trying to establish a dynamic ID for each, I get an error if I try to use the runat. That is probably the reason why I can't reach it from code behind...
I am very happy of myself... (see the YouTube video for this phrase, you'll be glad you did.)
In summary, this is what I added:
1. New Javascript function to add the name of the target DIV to a hidden field (The "collapseExpand" function is in the Site.Master. I couldn't put "load_div_to_hidden" in the Site.Master since "myhiddenField" isn't set up on every page
2. New hidden field to capture the name of the target DIV
3. New Javascript function to run on window.onload, check if we've got a post-back, and then display the value from the hidden field
4. Adding second Javascript call from the href in the link
Below are the new snippets of code:
<script type="text/javascript">
function load_div_to_hidden(obj) {
var hidden = document.getElementById('<%= myhiddenField.ClientID %>');
hidden.value = obj;
}
function windowOnLoad() {
var isPostBack = (('<%= IsPostBack %>').toLowerCase() == 'true') ? true : false;
if (isPostBack == true) {
var hid_field_value = document.getElementById('<%= myhiddenField.ClientID %>').value;
var right_div = document.getElementById(hid_field_value);
right_div.style.display = "block";
}
}
window.onload = windowOnLoad;
</script>
<input type="hidden" id="myhiddenField" runat="server" value="" />
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel123456'); javascript:load_div_to_hidden('Order_Notes_Panel123456');" %>" >+</a>
<div id='Order_Notes_Panel123456' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='123456'/>
</div>
Works like a charm!
I am a desktop client developer. I now got to continue this project is ASP.NET with AJAX, so I am learning web development the hard way.
I need to get a list of all check boxes and their states from repeater control on Summary.aspx when user clicks button CmdSave on ChoicePage.aspx.
Can I subscribe to event CmdSave_Click() in Summary.aspx or is there some way to approach Summary.aspx's repeater control from ChoicePage.aspx?
(MSDN talks about passing values from page to page in this article but this doesn't help me)
Here is the problem:
Page ChoicePage.aspx is included in Master AppMaster.master page. ChoicePage has Content tag which includes CmdSave and it's event handler CmdSave_Click() and it also includes iframe tag for displaying another page, Summary.aspx
On Summary.aspx I have repeater control which is bound to DataSource and relevant fields are of type bool represented by column of editable check boxes. Clicking these checkboxes mustn't cause Summary.aspx to refresh so I am not looking to handle (server-side) CheckedChanged event.
I am not sure if any code example would help here since this is more a concept question
function SetFrameStatus() {
var v = hdCommand.value.toString().toLowerCase();
hdCommand.value = "";
var frms = (GetFrameAll("FrameSummary"));
if (frms)
{ }
else return;
FrameSummary = frms[0];
DivSummary = FrameSummary.parentNode;
var FrameWindow = frms[1];
var FrameDocument = frms[2];
if (v == "showsummary") {
FrameWindow.location.replace(SummaryPageName);
}
}
<asp:Content ID="ContentSummary" ContentPlaceHolderID="NoUpdateDiv" runat="server">
<div id="DivMenu" class="Flat" style="overflow:visible; display:none;position:absolute;">
<input type="button" id="CmdSave" value="Save" onclick="CmdSave_Click()" />
</div>
<div id="DivSummary" style="position:absolute;margin:0px;padding:0px;display:none">
<iframe title="Loading" id="FrameSummary" marginheight="0px" marginwidth="0px" scrolling="auto"
style="padding:0px; margin:0px;width:auto;" src="loading.htm?Redirect=Summary.aspx" frameborder="0"
onload="FrameSummary_Load()"
></iframe>
</div>
In the end this is what solved my problem:
On ChoicePage.aspx in CmdSave_Click() function I called another function on Summary.aspx.
This other function did __dopostback("Repeater", "") and on Render event in my code behind I iterate through a Repeater.
I am leaving this question unanswered because I am sure there is a better way to do this.
I have a index page the renders objects from my database as a treeview, each item has a link href="/MessageGroupType/Edit/1002 that makes an Ajax call to display a partial view in a DIV.
Within the partial view there is a delete button which calls my controller to delete the item.
However, i do a check to make sure the item can be deleted, if the item cant be deleted then i wish a pop-up to appear back on the edit form telling the user they cant delete this record.
In my Edit partial view i have the following code
<asp:PlaceHolder runat="server">
<script src="<%= Url.Content("../../Scripts/JQuery/jquery-1.4.1.min.js") %>" type="text/javascript">
</script>
</asp:PlaceHolder>
<script type="text/javascript" >
$(function() {
$("#dialog").dialog();
});
</script>
<% if (Boolean.Parse(ViewData["DisplayWindow"].ToString())){%>
<div id="dialog" title="Cannot Delete Message Group Type">
<p>This Mesage group Type Cannot be deleted as is linked to other message group Types </p>
</div>
<% }%>
So my main questions are
Can i make a reference to a javascript script within my Partial View (i dont want my master page to be called on the partial view)
When i dynamically load the partial view data into my DIV - can i then after calling my controller insert another DIV into the first DIV.
I am i doing this the wrong way - so any pointers is appreciated
Cheers
In your tree view, you can add an Ajax.ActionLink with a OnFailure option in AjaxOptions that will point to your $("#dialog").dialog();
In your controller, if the user can not delete the record associate a bad request code (Response.StatusCode = (int)HttpStatusCode.BadRequest;) to your HttpResponse, so your OnFailure function will be called (and your popup displayed).
Do not forget to associate a OnSuccess function to your Ajax.ActionLink if the record has been deleted