When a certain check box is checked, check on other - javascript

I want to ensure that when I check a certain box then another checkbox will be checked and unable to uncheck unless the master checkbox is deselected. When the ECOM checkbox is checked the 3d secure checkbox is automatically checked and cannot be unchecked until the Ecom box is deselected.
<%
If Request.QueryString("ECOM") = "ON" Then
Apply_ECOM_Check.Checked = True
End if
If Request.QueryString("MOTO") = "ON" Then
Apply_MOTO_Check.Checked = True
End if
If Request.QueryString("TERMINAL") = "ON" Then
Apply_TERMINAL_Check.Checked = True
End if
If Apply_ECOM_Check.Checked = False and Apply_MOTO_Check.Checked = False and Apply_TERMINAL_Check.Checked = False then
Apply_ECOM_Check.Checked = True
End if
%>
<script type="text/javascript">
function enableaddonservice() {
var ecom =document.getElementById("Apply_ECOM_Check").checked;
var moto =document.getElementById("Apply_MOTO_Check").checked;
var terminal =document.getElementById("Apply_TERMINAL_Check").checked;
if (ecom==true ) {
document.getElementById("addonservices").style.display = "block";
} else {
document.getElementById("addonservices").style.display = "none";
}
}
var chk1 = $('#Apply_ECOM_Check');
var chk2 = $('#Apply3DSecure');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});</script>
<input class="noborder" type="checkbox" ID="Apply_ECOM_Check" name="Apply_ECOM_Check" runat="server" style="width: 18px" value="ON" onClick="enableaddonservice();" /> ECOM
<input class="noborder" type="checkbox" ID="Apply_MOTO_Check" name="Apply_MOTO_Check" runat="server" style="width: 18px" value="ON" onClick="enableaddonservice();" /> MOTO
<input class="noborder" type="checkbox" ID="Apply_TERMINAL_Check" name="Apply_TERMINAL_Check" runat="server" style="width: 18px" value="ON" onClick="enableaddonservice()" /> TERMINAL
Once Ecom is selected above then the 3d secure below is automatically selected and can not be removed unless ecom is deselected
<table style="width: 100%">
<tr>
<td><input class="noborder" type="checkbox" ID="Apply3DSecure" name="Apply3DSecure" runat="server" style="width: 18px" /> 3D Secure </td>
<td> <input class="noborder" type="checkbox" ID="Apply_Mobilepaypage" name="Apply_Mobilepaypage" runat="server" style="width: 18px" /> Mobile PayPage </td>
<td> <input class="noborder" type="checkbox" ID="Apply_RepeatPayments" name="Apply_RepeatPayments" runat="server" style="width: 18px" /> Repeat Payments </td>
</tr>
The Java script works on it's own with the check boxes but because the 3d secure selection addon is only displayed when Ecom is selected. I think that interferes. I have tried many functions in these check boxes and it will not do anything.

The code you posted does not match the functionality that you ask for in your question so I am providing code for what you asked for when you say "When the ECOM checkbox is checked the 3d secure checkbox is automatically checked and cannot be unchecked until the Ecom box is deselected."
You will need two asp text boxes as follows:
<asp:CheckBox ID="Ecom" runat="server" AutoPostBack="true" />
<asp:CheckBox ID="threed" runat="server" AutoPostBack="true" Enabled="False" />
Now in the code behind you will need this code:
Private Sub Ecom_CheckedChanged(sender As Object, e As EventArgs) Handles Ecom.CheckedChanged
If Ecom.Checked = True Then
threed.Checked = True
ElseIf Ecom.Checked = False Then
threed.Enabled = True
End If
End Sub
I hope this helps.

Related

Check all "yes" checkboxes in Javascript

I am trying to implement a "yes to all" checkbox on my website.
This is a sample of part of the code I have so far.
$("input:checkbox").each(function () {
var pos = $(this).prop("id");
var arr = pos.split("_");
var arr2 = arr[1].split("C");
if (arr2[1] == undefined) {
var arr3 = arr[1].split("W");
$(this).addClass(arr3[0]);
}
else {
$(this).addClass(arr2[0]);
}
});
$(".P2").change(function () {
var a = $(".P2:checkbox:checked");
if (a.length = 1) {
$(".P3").prop("checked", true);
$(".P4").prop("checked", true);
$(".P5").prop("checked", true);
$(".P6").prop("checked", true);
$(".P7").prop("checked", true);
$(".P8").prop("checked", true);
$(".P9").prop("checked", true);
$(".P10").prop("checked", true);
$(".P11").prop("checked", true);
}
});
<asp:CheckBox ID="P2C1" runat="server" text=" Yes to All"/>
<asp:CheckBox ID="P3C1" runat="server" text=" Yes" />
<asp:CheckBox ID="P3C2" runat="server" text=" No" />
<asp:CheckBox ID="P4C1" runat="server" text=" Yes" />
<asp:CheckBox ID="P4C2" runat="server" text=" No" />
That is just a portion of the checkboxes it goes on in the same pattern. The first box is yes and the second no. I need to implement the P2 checkbox as a select yes to all and only have the javascript select the checkboxes with an ID of C1 at the end. Currently, when checked the select yes to all checks both yes(C1) and no(C2) boxes. I have tried to change the code to:
$(".P2").change(function () {
var a = $(".P2:checkbox:checked");
if (a.length = 1) {
$(".P3C1").prop("checked", true);
$(".P4C1").prop("checked", true);
But that does not work and it does not check any boxes.
I know it has to do with the top input function, but I am just not sure what to change. I don't want to mess with the top input function at all because other things rely on that to work as is.
I swapped out the JSP tags for native HTML tags. The example below should adhere to your algorithm.
The "Yes to All" should have a special class or ID.
$('.all').change(function() {
$('input[id$="_C1"]:not(.all)').prop('checked', $(this).is(':checked'));
$('input[id$="_C2"]:not(.all)').prop('checked', false);
});
$('input:not(.all)').change(function() {
var id = $(this).attr('id'),
parts = id.split(/_/),
group = parts[0];
$('input[id^="' + group + '"]:not(#' + id + ')').each(function() {
if ($(this).is(':checked')) {
$(this).prop('checked', false);
}
});
});
body { display: flex; flex-direction: column; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="checkbox" id="P2_C1" class="all" />Yes to All</label>
<label><input type="checkbox" id="P3_C1" />Yes</label>
<label><input type="checkbox" id="P3_C2" />No</label>
<label><input type="checkbox" id="P4_C1" />Yes</label>
<label><input type="checkbox" id="P4_C2" />No</label>

jQuery get correct value of selected radio button

After research and lot of attempts of various implementations looking how to get radio button value from my application. Basically it is very simple radio button in file Index.cshtml :
<div class="col-md-2">
<div style="padding: 0 20px;">
<label for="star-filter2"> Projects vendors status:</label>
<fieldset id="star-filter2">
<input class="radioCheck2" id="rated-filter2" value="true" type="radio" name="starfilter2" />Rated<img src="~/images/check.png" alt="tick box" height="20" width="20" />
<br />
<input class="radioCheck2" id="rated-filter2" value="false" type="radio" name="starfilter2" />Not rated<img src="~/images/excl_mark.png" alt="excl mark" height="20" width="20" />
<br />
<input class="radioCheck2" id="rated-filter2" value="null" type="radio" name="starfilter2" />NULL<img src="~/images/excl_mark.png" alt="excl mark" height="20" width="20" />
</fieldset>
</div>
</div>
Here is my javascript code where I am trying to get selected radio button value:
$("#filter2").click(function () {
var showRated = $('#rated-filter2').is(':checked');
localStorage.setItem("showRated", showRated);
var location = $("#filter-button2").find("a").attr("href")....;
window.location.href = location;
});
In this code line: var showRated = $('#rated-filter2').is(':checked'); is working , but it is only to get value when it is checked. What I want , I want to get value of selected radio button, for example : true , "null" and any value which I insert into radio button.
I tried these lines, where I was getting 'undefined' or always false value.
$('#input[name=\'starfilter2\']:checked').val();
$('#rated-filter2:selected').val();
$('#input[name=starfilter2]:checked').val();
None of them it is not working.
Whoa, first of all, there is no reason to have multiple Ids of the same name in this case rated-filter2. IDs are supposed to be unique (like a driver's license ID or a social security number)
$(document).ready(function(){
$("input[type='button']").click(function() {
var radioValue = $("input[name='star-filter2']:checked").val();
if(radioValue){
alert("Selected: " + radioValue);
}
});
});
Or replace this
var radioValue = $("input[name='star-filter2']:checked").val();
with this
var radioValue = $("input[id='rated-filter2']:checked").val();
Keep in mind to have unique IDs.

Validating input field contained in table row

<tr>
<td>.....</td>
<td>
<div class="...">
<div class="..." id="..." style="display:block;">
<ul id="..." class="..." style="position:relative;">
<%
for(int i = 0;i < len;i++)
{
//get a json object
if(jsonobj != null)
{
//Get style...id..and some other values....
%>
<li class="..." style="display:block;" id="...">
<div style="<%=style%>">
<input type="checkbox" id="<%=Id%>" class="..." value="true" <%if(enabled){%> checked="checked" <%}%> onClick="..."/>
<input id="inp_<%=Id%>" type="text" class="..." style="border:none;padding-left:5px;" value="<%=text%>" title="<%=title%>">
</div>
</li>
<% }
}
%>
</ul>
</div>
</div>
</td>
</tr>
I have a table row like the above code. As you can see, there are two inputs, a checkbox and a text field. While submiting the form I want to validate the text field and show an error message with a small error icon at the right side. But since the input is in a table row I'm unable to to this.
I have a function which shows a tool tip. I just have to pass the id of the element and the message to that function. I want to validate the input field, show a small error image and call the tool tip function so that the tool tip is shown on the error image.
I want the error image to appear next to the required input field i.e., if the 3rd input field is vaidated to false, then the error should be displayed next to the 3rd containing the input field.
How do I do it?
It's a simple task for jQuery. See the example below:
$(document).ready(function(){
$("#btnSave").click(function(){
$(".txtvalidatorMessage").remove() // remove all messages
var inputs = $(".txtvalidator");
function ShowMessage(message, input){
var messageContainer = $("<div class='txtvalidatorMessage'>"+message+"</div>");
messageContainer.insertAfter(input)// show the message beside the input
}
inputs.each(function(){
var validationType = $(this).attr("validationType");
var require = eval($(this).attr("require"));
switch(validationType)
{
case "NotEmpty":
if ($(this).val() == "" && require == true)
ShowMessage("cant be empty",$(this))
break;
case "Number":
var isnum = /^\d+$/.test($(this).val());
if (!isnum && require == true)
ShowMessage("only number",$(this))
break;
}
});
});
});
.txtvalidatorMessage{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type='text' value="" placeholder='Cant be empty' class='txtvalidator' validationType='NotEmpty' require='true' />
</td>
</tr>
<tr>
<td>
<input type='text' value="" placeholder='only Number' class='txtvalidator' validationType='Number' require='true' />
</td>
<tr>
<td>
<input type='button' value="Validate" id='btnSave' />
</td>
</tr>
</table>

Trying to disable CSS buttons using ASP hidden value and javascript

I am using the ASP.NET PasswordRecovery method, and have a couple of CSS buttons to submit the form OR cancel the request.
I also grab the users email address to pass along to the successtext value of PasswordRecovery method, set the ASP hiddenvalue to success, and then try to use javascript to disable the buttons based on this value.
The problem is that this hiddenfield value seems to be set to "success" on initial page load, even though when viewing the source of the rendered page shows NO value.
There is probably a better approach to this, but I have tried several different ways, and this is successful up the point that I cant change the view state of the buttons.
<script runat="server">
protected void resetuserpassword_SendingMail(object sender, MailMessageEventArgs e)
{
e.Message.IsBodyHtml = true;
e.Message.Subject = "Password Assistance";
TextBox txtUserName = (TextBox)resetuserpassword.UserNameTemplateContainer.FindControl("UserName");
string UserEmailID = Membership.GetUser(txtUserName.Text.Trim()).Email;
resetuserpassword.SuccessText = "Password sent to ";
resetuserpassword.SuccessText += UserEmailID;
ValueHiddenField.Value = "Success";
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderArea" Runat="Server">
<script type="text/javascript">
window.onload = disableButtons;
function disableButtons() {
var element = document.getElementById('ContentPlaceHolderArea_ValueHiddenField');
if (typeof(element) != 'undefined' && element != null) {
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value = 'Success') {
var submitBtnElement = document.querySelector("#submitBtn");
var cancelBtnElement = document.querySelector("#cancelBtn");
submitBtnElement.style.display = "none";
cancelBtnElement.style.display = "none";
}
}
}
function clickSubmit() {
document.getElementById("ContentPlaceHolderArea_resetuserpassword_UserNameContainerID_SubmitButton").click();
}
function clickCancel() {
window.location.replace("~/Login.aspx");
}
</script>
<asp:hiddenfield id="ValueHiddenField" value="" runat="server"/>
<asp:hiddenfield id="ValueHiddenField" value="" runat="server"/>
<asp:PasswordRecovery ID="resetuserpassword" runat="server"
MailDefinition-BodyFileName="~/ResetPasswordEmailTemplate.html"
OnSendingMail="resetuserpassword_SendingMail"
successtext="Password sent to email address on record."
Width="300px" Font-Names="Arial" Font-Size="Small" UserNameTitleText="" >
<InstructionTextStyle Font-Names="Arial" Font-Size="Small" />
<MailDefinition BodyFileName="~/ResetPasswordEmailTemplate.html"></MailDefinition>
<UserNameTemplate>
<div><asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName" style="display:none;"></asp:Label></div>
<div style="font: arial, verdana, sans-serif;font-size: 13px;padding-bottom: 5px;font-weight: bold;">Please Enter your Username</div>
<div><asp:TextBox ID="UserName" runat="server" style="width: 180px;"></asp:TextBox></div>
<div><asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="PasswordRecovery1">*</asp:RequiredFieldValidator></div>
<div><asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal></div>
<div style="display: inline;" ><asp:Button ID="SubmitButton" runat="server" CommandName="Submit" Text="Submit" ValidationGroup="PasswordRecovery1" style="display: none;" /></div>
</UserNameTemplate>
</asp:PasswordRecovery>
<div>
<div id="submitBtn" onclick="clickSubmit()">Submit</div>
<div id="cancelBtn" onclick="clickCancel()">Cancel</div>
</div>
</asp:Content>
Your javascript if statement is assigning the value 'Success' to the Hidden Field (single equals sign).
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value = 'Success') {
...
}
Change it to this (double equals sign):
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value == 'Success') {
...
}

jQuery RadioButtonList checked value returns "on"

I have a strange problem. I have a radio button list that when it is checked, it shows the div below that corresponds with the selected item. Above the radio button list is a check box list. The radio button click event works fine until you check a box from the above check box list. Once you check an item from the check box list above, it starts returning "on" rather than the selected radio button's value. Any idea?
jQuery:
<script type="text/javascript">
function CheckAllTrucks(sendingcb) {
$("#divTruckList :checkbox").prop("checked", $(sendingcb).prop("checked"));
}
function SetTimeframeInput(sendingrbl) {
var value = $(sendingrbl + ":checked").val();
$("#divTimeFrameControls .timeframectrls").each(function () {
$(this).hide();
});
$("#div" + value).show();
}
HTML/ASP.NET Code:
<div class="form-field">
<asp:CheckBox ID="cbSelectAllTrucks" runat="server" Text="Select All Trucks" onclick="CheckAllTrucks(this)" />
<div id="divTruckList">
<asp:CheckBoxList ID="cblTrucks" runat="server" />
</div>
</div>
<div class="form-field">
<asp:RadioButtonList ID="rblTimeFrame" runat="server" onclick="SetTimeframeInput(this)">
<asp:ListItem Text="Month" Value="month" />
<asp:ListItem Text="Quarter" Value="quarter" />
<asp:ListItem Text="January-December" Value="jandec" />
<asp:ListItem Text="July-June" Value="juljun" />
</asp:RadioButtonList>
<div id="divTimeFrameControls">
<div id="divmonth" class="timeframectrls" style="display: none;">
<!-- month fields -->
</div>
<div id="divquarter" class="timeframectrls" style="display: none;">
<!-- quarter fields -->
</div>
<div id="divjandec" class="timeframectrls" style="display: none;">
<!-- jandec fields -->
</div>
<div id="divjuljun" class="timeframectrls" style="display: none;">
<!-- juljun fields -->
</div>
</div>
</div>
Thanks in advance!
EDIT
I have found this only happens when one of the check boxes are checked. If you check and then uncheck, the value is still correct. It is only when a check box is checked does it set the value as "on".
Still don't know what the problem was, but was able to fix it by referencing the ID of the radio button list directly. Like this:
function SetTimeframeInput() {
var value = $("#rblTimeFrame input:checked").val();
$("#divTimeFrameControls .timeframectrls").each(function () {
$(this).hide();
});
$("#div" + value).show();
}
Thanks for your input.
Instead of passing (this) to functions try using EventObject which is passing by default on click :
function SetTimeframeInput(e) {
var value = $(e.currentTarget).val();
// value contains selected radio button`s value
// continue your code here
}
I hope, this helps.

Categories

Resources