checkbox checked in JQuery is not working - c#

I've a simple situation.
When the checkbox is checked then the textbox is shown. Unchecking checkbox will hide the textbox.
I move the value to (asp:Textbox) textboxA.text and set the (asp:Checkbox) "chkboxA" to Checked in Server side (Page load).
then my jquery code document.ready is executed.
C# code behind
protected override void OnLoad()
{ textboxA.Text = "Hello World";
chkboxA.Checked = !string.IsNullOrEmpty(textboxA.Text);
}
JQUERY CODE:
$('input[id$=chkboxA]').click(function () {
var checked_status = this.checked;
if (checked_status == true) {
$('input[id$=textboxA]').show();
}
else {
$('input[id$=textboxA]').hide();
}
});
$('input[id$=chkboxA]').click(); //this statment triggers the checkbox checked
PROBLEM:
When the page is first shown the "textboxA" is shown but the checkboxA is unchecked.
Then when I click on the checkboxA the checkbox is checked and the TextboxA remains on the screen.
Then when I click on the CheckboxA again to uncheck then the texboxA is not shown.
so the issue is on first load (first shown on the screen).
Why is the checkboxA not checked when the page is first shown while the TextboxA is shown?
what is wrong in my code?

I think easiest way is to use toggle()
try something like this
Initially set the visible false in textbox
$(".chk").click(function() {
$(".txt").toggle(this.checked);
});
Something like http://jsfiddle.net/5udtC/1880/

Here is how I would go about it:
Instead of,
chkboxA.Checked = !string.IsNullOrEmpty(textboxA.Text);
you could have a script that is executed once the page is done loading (in you markup)
<script type="text/javascript">
$(document).ready(function() {
if($('#textboxA').attr('value') != '') {
$('#chkboxA').attr("checked", "checked");
} else {
$('#chkboxA').attr("checked", false);
}
});
</script>
Then, when evaluating whether the checkbox is checked, you could use:
$('#chkboxA').click(function () {
if (this.attr('checked')) {
$('#textboxA').show();
}
else {
$('#textboxA').hide();
}
});

Try add this line :
if ($('input[id$=chkboxA]').is(':checked')) {
$('input[id$=textboxA]').show();
}
else {
$('input[id$=textboxA]').hide();
}
after :
$('input[id$=chkboxA]').click();
If you remove : $('input[id$=chkboxA]').click(); you will see that textbox will hidden.

Related

Toggle Button State

I would like to use a toggle button in my toolbar but I can't find out how to retrieve the state.
Could someone explain me how to do that?
<%= Html.Kendo().ToolBar()
.Name("ToolBar")
.Items(buttonsItem =>
{
buttonsItem.Add().Type(CommandType.Button).Text("Unconfirmed").Id("isConfirmed").Togglable(true).Toggle("isConfirmed");
})
%>
function isConfirmed(e) {
if (document.getElementById("isConfirmed").checked == true)
{
alert("yes")
}
else
{
alert("no")
}
Regards
In the toggle event itself you can look at e.checked to determine the toggle state.
In this example I am also changing the text of the button depending on the checked state:
function isConfirmed(e) {
var text = e.checked ? "Confirmed" : "Unconfirmed";
e.target.text(text);
alert(text);
}
If you want to get the state later (e.g. when a submit button is clicked), you can check the selected option of the button object ($("#isConfirmed").data("button").options.selected):
$("#btnIsConf").on("click", function(){
if ($("#isConfirmed").data("button").options.selected){
alert("Yes");
} else {
alert("No")
}
});
DEMO
You do not need to look the dom element back up to determine the state i.e. the checked property.
It is available in your e parameter as follows:
function isConfirmed(e) {
if (e.checked) {
alert("yes")
}
else {
alert("no")
}
}
Screen Grab

pop up does not go for post back in asp.net

I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}

User text input handling using TextBox

I have this control:
I'm trying to create a kind of validation, that whenever the user enters text to the TextBox, the "Add" button will be Enabled, and when the text is "" (null), the "Add" button is disabled.
I dont want to use validators.
here's the code:
protected void addNewCategoryTB_TextChanged(object sender, EventArgs e)
{
if (addNewCategoryTB.Text != "")
addNewCategoryBtn.Enabled = true;
else
addNewCategoryBtn.Enabled = false;
}
The problam is, that when the user enter's text, the "Add" button doesn't changes from disabled to enabled (and vice versa)...
any ideas?
Is it Web Forms? In Web Forms the TextChanged event of the TextBox won't fire by default.
In order to fire the event, you have to set the AutoPostBack property of the TextBox to true.
BUT, this would perform a HTTP post, what is kink of ugly, or you can wrap that in an UpdatePanel
A more elegant option, is to do that using jQuery, to do that in jQuery, you'll need some code like:
$(document).ready(function() {
$("#<%= yourTextBox.ClientID %>").change(function() {
var yourButton = $("#<%= yourButton.ClientID %>")
yourButton.attr('disabled','disabled');
yourButton.keyup(function() {
if($(this).val() != '') {
yourButton.removeAttr('disabled');
}
});
});
});
You'll need to accomplish this with Javascript, since ASP.NET is incapable of performing such client-side modifications. Think about it ... every time you pressed a letter inside the text box, it would have to postback and refresh the page in order to determine if the text box was empty or not. This is one way that ASP.NET differs from Winforms/WPF.
TextChanged events will make postback on server every time. You don't need to increase those request for such task.
You can use jquery to achieve this
var myButton = $("#btnSubmit");
var myInput=$("#name");
myButton.prop("disabled", "disabled");
myInput.change(function () {
if(myInput.val().length > 0) {
myButton.prop("disabled", "");
} else {
myButton.prop("disabled", "disabled");
}
});
JS Fiddle Demo
You just need to take care of elements Id when you are using Server Controls. For that Either you can use ClientID or set property ClientIdMode="Static"

Use select change to fadeout or fadein another field

I am trying to use a dropdown which as 2 values yes/no to change whether a field is displayed or not. I still want element to exist just no visible.
I am using Razor and MVC3 to render the page.
So I have tried the following code:
$(function () {
$("DiscountOn").change(function () {
if ($("DiscountOn").Value == 0) {
$("DiscountPercentage").fadeOut('fast');
}
else {
$("DiscountPercentage").fadeIn('fast');
}
});
});
DiscountOn is the dropdown which has values of either 0 or 1, text no or yes respectively. I want it to make DiscountPercentage dissappear when DiscountOn is turned to 0 and reappear when DiscountOn is turned 1. And for value added, if you can make it appear or or disappear when the page has loaded depending on which option is set in the dropdown that would be excellent.
$("DiscountOn")
does not select the element properly. If the ID of the element that you wish to select then you need to either do:
document.getElementById("DiscountOn") // Pure JS
or
$("#DiscountOn") // jQuery
Your other problem is how you are getting the value. You either need to do this
.value // Pure JS
or
.val() // jQuery
Remember that JS is case-sensitive!
$(function () {
$("#DiscountOn").change(function () {
if ($(this).val() == '0') {
$('#DiscountPercentage').fadeOut('fast');
}
else {
$('#DiscountPercentage').fadeIn('fast');
}
});
});
And for value added, if you can make it appear or or disappear when
the page has loaded depending on which option is set in the dropdown
that would be excellent.
Ideally this should be done on the server side and not using any javascript. You already know the selected value of the dropdown, so you could dynamically add some CSS class around the DiscountPercentage element to show/hide it.
The problem is with the selector
If DiscountOn and DiscountPercentage are IDs or the element. Prefix it with # if they are class then with .
$(function () {
$("#DiscountOn").change(function () {
if ($("#DiscountOn").val() === 0) {
$("#DiscountPercentage").fadeOut('fast');
}
else {
$("#DiscountPercentage").fadeIn('fast');
}
});
});

How to initialize textbox to hide for first display and still have jquery work

So I now have the following jquery to hide or show a textbox based on specific values selected in a DropDownList. This works except that I need the first display of the popup to always be hidden. Since no index change was made in the drop down list, the following does not work for that. If I code it as visible="false", then it always stays hidden. How can I resolve this?
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION) {
$(".statusActionAmountCssClass").attr("disabled", false);
$(".statusActionAmountCssClass").show();
}
else {
$(".statusActionAmountCssClass").attr("disabled", true);
$(".statusActionAmountCssClass").hide();
}
});
}
</script>
Thank you,
Jim in Suwanee, GA
If you set
visible=false
.Net will not render it. You can do
style="display:none;"
and .Net will render the tag properly but CSS will hide it from the user.
Add the following to pageLoad function
function pageLoad(sender, args) {
$("input.statusActionAmountCssClass").hide();
.... rest of code .....
}
By the way, I would recommend using the selector $("input.statusActionAmountCssClass") to get a jQuery object containing a reference to your input, otherwise jQuery will search all elements to match the CSS class .statusActionAmountCssClass
EDIT:
Another change that could also be made is to use jQuery's data() to store the two global variables
$.data(window, "_CASE_RESERVE_ACTION","317");
$.data(window, "_LEGAL_RESERVE_ACTION","318");
then when you need them simply cache the value in a local variable inside the function
function someFunctionThatNeedsGlobalVariableValues() {
var caseReserveAction = $.data(window, "_CASE_RESERVE_ACTION");
var legalReserveAction = $.data(window, "_LEGAL_RESERVE_ACTION");
}
this way, the global namespace is not polluted. See this answer for more on data() command

Categories

Resources