Execute function when the checkbox is checked - javascript

I have below function when we check or uncheck the check box (inside the gridview) it will show the popup and other processing information.
Is there any way to execute this function only when checkbox is checked and not on unchecked condition?
Below is my function:
$(document).ready(function () {
$('#<%= gvPRCertInfo.ClientID %> input[type="checkbox"]').change(function () {
var signValue = $(this).closest('tr').children('td:eq(4)').html();
if (signValue == "Virtual") {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("you have selected virtual do u want to create a new name for this?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
});
});
This is my gridview:
<asp:GridView ID="gvPRCertInfo" runat="server" GridLines="None"
CssClass="data responsive">
<Columns>
<asp:TemplateField HeaderText="Select" SortExpression="">
<HeaderTemplate>
<asp:CheckBox ID="chkboxSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkboxSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkCert" AutoPostBack="true" ClientIDMode="Static" OnCheckedChanged="chkCert_CheckedChanged" runat="server" />
<input type="hidden" id="hdnCertId" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "CertId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CertificateID" HeaderText="Certificate ID" HeaderStyle-HorizontalAlign="Center" />
................
.................
Would anyone please suggest any ideas on how to execute only when I check the checkbox.

Try this inside the on change function of the checkbox.
if($(this).is(':checked') == true)
{
/* Your function code here.*/
}

hello my dear i think this will work but still i'm not sure
you can code like below :
$(document).ready(function () {
$('#myCheckbox').change(function () {
if ($(this).attr("checked")) {
// fire your function
return;
}
// not checked
});
});

try this in side the onchange function
Javascript code
if(document.getElementById('mycheckbox').checked) {
console.log("ckecked")
} else {
console.log("not ckecked")
}
jquery code
if ($('#mycheckbox').attr("checked")) {
console.log("ckecked")
}else{
console.log("not ckecked")
}

You can use jQuery's is() function:
if($("input").is(':checked')) {
dosomething
}

Related

Jquery each function not execute inside gridview textbox in asp.net

Here is my gridview
<asp:GridView ID="gvDoctorVisits" runat="server" DataKeyNames="AdmissionId" class="tableStyle"
AutoGenerateColumns="False" Width="100%" EmptyDataText="No record found" ShowHeaderWhenEmpty="true">
<Columns>
<asp:BoundField DataField="Amount" HeaderText="Amount"></asp:BoundField>
<%--<asp:BoundField DataField="PaidAmount" HeaderText="Paid Amount"></asp:BoundField>--%>
<asp:TemplateField HeaderText="Paid Amount">
<ItemTemplate>
<asp:TextBox ID="txtPaidAmount" type="text" runat="server" Text='<%# Eval("PaidAmount") %>' CssClass='<%# "txtDoctorPaidAmount "+"txtDPPaidAmount_"+Eval("AdmissionId") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am using j query each function of my gridview textbox class,but jquery each function not executing,here is my code
$(".txtDoctorPaidAmount").on('keyup change', function () {
debugger;
var sum = 0;
$('.txtDoctorPaidAmount').each(function () {
sum += parseFloat($(this).text());
});
$("#txtPaidAmount").val(sum.toFixed(2));
});
this each function not executing,how to solve this?
Try this: Use val() instead of text() and add a console.log to see, if iteration is executed.
$(".txtDoctorPaidAmount").on('keyup change', function () {
var sum = 0;
$('.txtDoctorPaidAmount').each(function () {
// use val instead of text
let inputVal = $(this).val();
// this line is just to show, that each is executed
console.log('adding value: ' + inputVal);
sum += parseFloat(inputVal);
});
$("#txtPaidAmount").val(sum.toFixed(2));
});

How to make asp textbox empty by JavaScript

I have got a problem with making textbox empty using JavaScript function.
If checkbox is unchecked the asp:Textbox should make disabled and empty.
It happens, but in code behind all the time is visible previous value which was entered before in that textbox.
<asp:RadioButton ID="radio_fx_no" runat="server" Text="NO" GroupName="optradio1" onclick="CheckBoxChangedDisableFx(this);" />
<asp:RadioButton ID="radio_fx" runat="server" Text="YES" GroupName="optradio1" onclick="CheckBoxChangedAbleFx(this);" />
<asp:TextBox ID="txt_fx" ClientIDMode="Static" runat="server" Enabled="false" />
<script>
function CheckBoxChangedAbleFx(checkbox) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').disabled = false;
}
}
function CheckBoxChangedDisableFx(checkbox) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').value = "";
document.getElementById('<%= txt_fx.ClientID %>').disabled = true;
}
}
</script>
Any ideas what is wrong in my code?
This problem is called the Cacheing the browser data. You can try three things in this case:
1) Clear value of textbox in pageload event at every postback:
if (IsPostBack)
{
txt_fx.text = "";
}
and in your aspx code make text="":
<asp:TextBox ID="txt_fx" Text="".../>
2) Set AutoComplete property of textbox to off for html input
or disable autocompletetype property of asp textbox
<asp:TextBox ID="txt_fx" autocompletetype="disabled".../>
3) or Set AutoComplete of your FORM tag of your page to "off"
If you want to clear actual value of textbox on server side without postback then you need to use AJAX.
Hope it will help you..!!
in .cs file,Page_Load method,plus such code:
if(!Page.IsPostBack)
{
radio_fx.Attributes.Add("onClick", "return CheckBoxChangedState(this,false);");
radio_fx_no.Attributes.Add("onClick", "return CheckBoxChangedState(this,true);");
}
and in .aspx file,change as follows:
<script type="text/javascript">
function CheckBoxChangedState(checkbox, state) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').value = "";
document.getElementById('<%= txt_fx.ClientID %>').disabled = state;
}
}
<asp:RadioButton ID="radio_fx_no" runat="server" AutoPostBack="false" Text="NO" GroupName="optradio1" />
<asp:RadioButton ID="radio_fx" runat="server" AutoPostBack="false" Text="YES" GroupName="optradio1" />

GridView button - yes/no option

I cannot figure out how to make this situation. I have ASP.NET application with webpage showing GridView linked to database - showing books which can be rented. I want to have button at each line, so user can click and rent this book. After click, user should get messageBox with question like "Do you really want to rent this book? and Yes/No option and in c# code I want to gent this answer with line, where this button was clicked and handle it properly.
So far I was able to create this code :
GridView :
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1" EmptyDataText="Žádné datové záznamy k zobrazení." OnRowCommand="GridView2_RowCommand">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="author" HeaderText="author" SortExpression="author" />
<asp:BoundField DataField="genre" HeaderText="genre" SortExpression="genre" />
<asp:BoundField DataField="availability" HeaderText="availability" SortExpression="availability" />
<asp:BoundField DataField="owner" HeaderText="owner" SortExpression="owner" />
<asp:BoundField DataField="isbn" HeaderText="isbn" SortExpression="isbn" />
<asp:BoundField DataField="barcode" HeaderText="barcode" SortExpression="barcode" />
<asp:BoundField DataField="amount" HeaderText="amount" SortExpression="amount" />
<asp:ButtonField CommandName="text" Text="button" />
</Columns>
</asp:GridView>
Script to handle question :
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to rent this book?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
and in my C# code I have
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "text")
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
showMessage("You clicked YES!");
}
else
{
showMessage("You clicked NO!");
}
//GridView2.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Text); -> cell value of clicked row
}
}
private void showMessage(string text)
{
string script = "alert(\"" + text + "\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
But I cannot figure out, how to add script to gridView button, any help?
You can use OnClientClick for that
<asp:ButtonField CommandName="text" Text="button" OnClientClick="return Confirm();"/>
And Your javascript function look like
<script type = "text/javascript">
function Confirm() {
if (confirm("Do you want to rent this book?")) {
return true;
} else {
return false;
}
}
</script>
No need to store value in hidden field because if user click on 'No' then page won't post back.
Just figured out how to do it by myself, button needs to be transfered to templateField and then it´s possible to add onClientClick

How to save the selected value of checkboxlist in array?

I want to save the values of checkbox in an array using javascript or jquery.
My checkboxlist is inside the datalist. Whenever the user select an item, I want to add the value of that selected item to a array.
ASPX :
<asp:DataList ID="dl_Groups_1" RepeatColumns="1" runat="server" OnItemDataBound="dl_Groups_1_ItemDataBound" RepeatDirection="vertical" ShowFooter="False" ShowHeader="False">
<ItemTemplate>
<asp:CheckBox Font-Bold="true" runat="server" ID="chk_Group_1" Text='<%# Eval("category_type") %>' Value='<%# Eval("service_type_category_id") %>' onclick="OnGroupClick" />
<asp:CheckBoxList CssClass="line" runat="server" ID="chkServiceType_1" DataValueField="ServiceTypeID" DataTextField="Name" EnableViewState="true">
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:DataList>
I tried the below to, get the items that are slected, but i am struck up here...
function test() {
$(":checkbox").each(function () {
if (this.checked) {
alert(this);
}
});
}
When i do this, i get alert message as "ON" and not the value. And where do i call the javascript to keep the array updated on selecting and un selecting the items in checkboxlist ?
var arrValues = new Array();
function test() {
$(":checkbox").each(function () {
if (this.checked && arrValues.indexOf(this.value) == -1) {
arrValues.push(this.value);
}
});
}
use map()
var selectedValue= $("input:checkbox:checked").map(function(){
return this.value;
}).get();
console.log(selectedValue);
selectedValue will have all the checked value in array..
var val;
$('#<%= chkServiceType_1.ClientID %> input[type=checkbox]').change(function(){
val = $("#<%= chkServiceType_1.ClientID %> input[type=checkbox]:checked").map(function(){
return this.value;
}).get();
})

how to determine which serverside Button click in Client Side javascript?

How to determine which serverside Button click in Client Side javascript?
There are many Buttons in the form.
function onMyClicked()
{
var btn = ??;
if (btn == 'IDDelete') {
var result = confirm("........ ");
if (result){
xxxxx
}
else close();
}
else if(btn=='IDClose'){
xxxxx
}
window.onunload = function (){
onMyClicked();
}
<asp:Button ID="IDDelete" runat="server" Text="Delete" --->
<asp:Button ID="IDClose" runat="server" Text="Close" ---->
EDIT:
var isDirty;
isDirty = 0;
function setDirty() {
isDirty = 1;
}
function onMyClicked() {
var btn =???;
if (btn == 'IDClose') {
var sSave;
if (isDirty == 1) {
sSave = window.returnValue = confirm('------');
if (window.returnValue == false) closerel();
if (sSave == true) {
document.getElementById('__EVENTTARGET').value = 'IDSave';
document.getElementById('__EVENTARGUMENT').value = 'Click';
window.document.form1.submit();
}
else {
close();
}
}
else close();
}
}
window.onunload = function (){
onMyClicked();
}
<asp:Button ID="IDDelete" runat="server" Text="Delete" >
<asp:Button ID="IDClose" runat="server" Text="Close" >
<asp:Button ID="IDSave" runat="server" Text="Save" >
<asp:Button ID="IDClose" runat="server" Text="Close" >
How to determinde IDClose click?
If you use OnClientClick property of the button, the function you type in the property runs. So your code will become:
function delete()
{
var result = confirm("........ ");
if (result){
xxxxx
}
else close();
}
}
function close()
{
xxxxx
}
<asp:Button ID="IDDelete" runat="server" Text="Delete" OnClientClick="Delete">
<asp:Button ID="IDClose" runat="server" Text="Close" OnClientClick="Close">

Categories

Resources