Use select change to fadeout or fadein another field - c#

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');
}
});
});

Related

I want the to load all the data at once at some specific condition in my page using jquery

I have this jquery function.It is working fine and bringing the data when i click at any particular character. If i click "A" then it bring all the places starting with A.But i want to load all the countries at once irrespective of any character click if i write some condition.
jQuery(function ($) {
alert(1);
// Listen for Click
$(".serving-nav a").click(function (e) {
// Get the Character
var theChar = $(this).data('alpha');
// Hide Others
$(this).parent().find('a').not($(this)).removeClass('active');
$(".serving-data .serving-nav-data").stop(true, true).slideUp(500);
// Show the Related
$(this).addClass('active');
$(".serving-data .serving-nav-data[data-alpha='" + theChar + "']").stop(true, true).slideDown(500);
// Prevent Default
e.preventDefault();
return false;
});
// Trigger Click on Active One
$(".serving-nav a.active").click();
});
It looks like you'd just do:
$(".serving-data .serving-nav-data').show();
Or, if you still want them animated:
$(".serving-data .serving-nav-data').stop(true, true).slideDown(500);
Basically, if you don't want to select based on the data-alpha property, just don't include that selector.

How can I elegantly get two HTML checkboxes to tick each other off?

I have two mutually exclusive checkboxes; that being so, I'd like each one to automatically reflect the opposite state of the other when a change is made: if checkboxA is checked, checkboxB should be, if checked, unchecked (etc., I'm sure you know what I mean).
I'm creating the checkboxes in my code-behind like so:
ckbxPaymentForSelf = new CheckBox();
ckbxPaymentForSelf.Text = "myself";
ckbxPaymentForSelf.ID = "ckbxPaymentForSelf";
this.Controls.Add(ckbxPaymentForSelf);
ckbxPaymentForSomeoneElse = new CheckBox();
ckbxPaymentForSomeoneElse.Text = "someone else";
ckbxPaymentForSomeoneElse.ID = "ckbxPaymentForSomeoneElse";
this.Controls.Add(ckbxPaymentForSomeoneElse);
Based on this, I thought maybe I could use the checkbox's Name property and set them both to the same value, something like "ckbxsSelfOrSomeoneElse" but there is no "Name" property on Checkbox available to me.
I could write some jQuery like so (pseudoscript):
$(document).on("change", '[id$=ckbxPaymentForSelf]', function () {
var ckd = this.checked;
if (ckd) // check ckbxPaymentForSomeoneElse and uncheck if it it's checked
else // check ckbxPaymentForSomeoneElse and check if it it's unchecked
});
$(document).on("change", '[id$=ckbxPaymentForSomeoneElse]', function () {
var ckd = this.checked;
if (ckd) // check ckbxPaymentForSelf and uncheck if it it's checked
else // check ckbxPaymentForSelf and check if it it's unchecked
});
...but am wondering if there is a more obvious or elegant solution to this, as this is indubitably a common requirement.
UPDATE
I tried 's answer:
$(document).on("click", '[id$=ckbxPaymentForSelf]', function () {
alert('reached onclick for ckbxpaymentforself');
$('#ckbxPaymentForSomeoneElse').prop('checked', !this.checked);
});
$(document).on("click", '[id$=ckbxPaymentForSomeoneElse]', function () {
alert('reached onclick for ckbxpaymentforsomeoneelse');
$('#ckbxPaymentForSelf').prop('checked', !this.checked);
});
...but, illogically (it seems to me and, obviously, him), it doesn't work. The strange/suspicious thing is that the alert messages are showing twice! I have to click them twice to dismiss them. Why would that be, and could that be the/a problem? I did notice that the jQuery appears twice in the "View Source" although, of course, it is in only one place in the actual source code (at the bottom of the .asxc file).
UPDATE 2
As wilusdaman suggested (make it an answer, Wilus, and I'll accept it as such), the elegantest way is to use radiobuttons instead. All that is needed is this:
rbPaymentForSelf = new RadioButton();
rbPaymentForSelf.Text = "myself";
rbPaymentForSelf.ID = "rbPaymentForSelf";
rbPaymentForSelf.GroupName = "SelfOfSomeoneElse";
this.Controls.Add(rbPaymentForSelf);
String checkboxPaymentForSomeoneElseText = "someone else";
rbPaymentForSomeoneElse = new RadioButton();
rbPaymentForSomeoneElse.Text = checkboxPaymentForSomeoneElseText;
rbPaymentForSomeoneElse.ID = "rbPaymentForSomeoneElse";
rbPaymentForSomeoneElse.GroupName = "SelfOfSomeoneElse";
this.Controls.Add(rbPaymentForSomeoneElse);
...and this jQuery, relatedly, then acts:
/* If user selects "payment for self" (they are seeking payment for themselves, as opposed to someone else), omit (invisibilize) sections 2 and 3 on the form */
$(document).on("change", '[id$=rbPaymentForSelf]', function () {
if (this.checked) {
$('[id$=panelSection2]').slideUp();
$('[id$=panelSection3]').slideUp();
$('[id$=_MailStopRow]').slideDown();
$('[id$=_AddressRows]').slideUp();
}
});
/* If user selects "payment for someone else" (they are seeking payment for someone else, as opposed to themselves), make sections 2 and 3 on the form visible */
$(document).on("change", '[id$=rbPaymentForSomeoneElse]', function () {
if (this.checked) {
$('[id$=panelSection2]').slideDown();
$('[id$=panelSection3]').slideDown();
$('[id$=_MailStopRow]').slideUp();
$('[id$=_AddressRows]').slideDown();
}
});
However, the sections that should show if the user selects "someone else" do not display the first time the user (me for now) selects the "someone else" radio button - subsequently, it does work, though...
i am able to achieve using javascript as below:
<body>
<input type="checkbox" id="one" name="one" onchange="check1()"/>
<input type="checkbox" id="two" name="two" onchange="check2()"/>
<script>
function check1()
{
if(one.checked)
{
document.getElementById("two").checked = false;
}
else
{
document.getElementById("two").checked = true;
}
}
function check2()
{
if(two.checked)
{
document.getElementById("one").checked = false;
}
else
{
document.getElementById("one").checked = true;
}
}
</script>
</body>
This can be used for each instance you have in your project, you never need to worry about mixing the logic in for each selector you wish to target. Super reusable!
Since the click event happens on the client side, heres some jQuery to fit your requirements:
$.fn.dependantCheckbox = function() {
"use strict";
var $targ = $(this);
function syncSelection(group, action) {
$targ.each(function() {
if ($(this).data('checkbox-group') === group) {
$(this).prop('checked', action);
}
});
};
$('input[type="checkbox"][data-checkbox-group]').on('change', function() {
var groupSelection = $(this).data('checkbox-group');
var isChecked = $(this).prop('checked');
syncSelection(groupSelection, isChecked);
});
}
$('input[type="checkbox"][data-checkbox-group]').dependantCheckbox();
http://codepen.io/nicholasabrams/pen/mJqyqG
I believe using a client side MVC framework is a much better elegant solution.
Eg, in AngularJs, you can bind your view (two checkboxes) to your model, and every time when you change your model, your view will be updated by framework.
In addition, I believe you can also use observationCollection to do the same on the server side (https://msdn.microsoft.com/en-us/library/ms668604(v=vs.110).aspx).
While this is elegent you will face an issue because the change event will fire for both. This would be a cartesian product as the two will start a war. the code would change the state of the other going forever, or at least causing unwanted results. Using click would be a better solution.
$(document).on("change", '#ckbxPaymentForSelf', function () {
$('#ckbxPaymentForSomeoneElse').prop('checked', !this.checked);
});
$(document).on("change", '#ckbxPaymentForSomeoneElse', function () {
$('#ckbxPaymentForSelf').prop('checked', !this.checked);
});
I suggest the following. Note the labels and use of the class vs the id to assign the event handler:
$(document).on("click", '.ckbxPaymentForSelf', function () {
$('#ckbxPaymentForSomeoneElse').prop('checked', !this.checked);
});
$(document).on("click", '.ckbxPaymentForSomeoneElse', function () {
$('#ckbxPaymentForSelf').prop('checked', !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="ckbxPaymentForSelf" class="ckbxPaymentForSelf" type="checkbox" checked/>
<label class="ckbxPaymentForSelf" for="ckbxPaymentForSelf">Payment For Self</label></br>
<input id="ckbxPaymentForSomeoneElse" class="ckbxPaymentForSomeoneElse" type="checkbox" />
<label class="ckbxPaymentForSomeoneElse" for="ckbxPaymentForSomeoneElse">Payment For Someone Else</label></br>
Note: When creating the controls server side you may want to set the
ClientIdMode="Static"
or script this way:
$('#<%= ckbxPaymentForSomeoneElse.ClientID %>').prop('checked', !this.checked);
in the script to be sure your control is referenced

How to hide a checkboxlist based on a dropdown selection using JQuery?

I have a form with a dropdownlist. Based on the selected item in the dropdown respective chekbox list appears and other checkboxlist disappears. How can you accomplish this using JQuery?
Here's Javascript that you should be able to easily adapt to your specific elements:
$('#dropdownlist').on('change', function () {
if ($(this).val()) {
if($(this).val() === "some value") {
$('#somecheckboxgroup').show();
$('#someothercheckboxgroup').hide();
}
else if($(this).val() === "some other value") {
$('#somecheckboxgroup').hide();
$('#someothercheckboxgroup').show();
}
}
});
Essentially, you just want to run a function every time the dropdownlist changes, and in it, check the currently selected value and then run your desired code based on the observed value.
Here is a really basic example - http://jsfiddle.net/jayblanchard/G8z3r/
The code can be shortened up just by using different selectors, id's and classes but I wanted to give you a basic idea on how this works.
$('select[name="showbox"]').change(function() {
if('foo' == $(this).val() ) {
$('div').hide(); // make sure all divs are hidden
$('#checkboxA').show(); // show the right one
} else if ('bar' == $(this).val() ) {
$('div').hide(); // make sure all divs are hidden
$('#checkboxB').show(); // show the right one
} else if ('both' == $(this).val() ) {
$('div').show(); // sow all divs
} else {
$('div').hide();
}
});

Set SELECT value after filling it with jQuery

I'm trying to populate a SELECT using jQuery and after it's populated set the value i want.
I'm working with ASP.NET MVC 5.
The problem is the value doesn't get set
Here's my code:
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(); //Populates the dropdownlist
PreviousCategory(); //Sets DropDownList value to previous state (posted value)
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategory").val(previousCategory);
}
}
$("#PreviousCategory") is a hidden input wich gets it's value server-side after a postback with the next code:
#if (ViewBag.Category!=null)
{
#Html.Hidden("PreviousCategory",(object)ViewBag.Category);
}
Both functions work separately, the DropDownList gets populated flawlessly, but the value doesn't get set.
If i trigger PreviousCategory() from another event (for example a button click), the value gets set perfectly.
I didn't think it was necessary to post ListCategories() code since it works well and you can just assume it fills the dropdownlist, though if anyone find it necessary let me know and i'll edit the post.
EDIT:
Here is ListCategories() code:
function ListCategories(){
_idOrganigrama = $("#IdOrganigrama").val()
_idTipoPedido = $("#IdTipoPedido").val()
data = { idOrganigrama: _idOrganigrama, idTipoPedido: _idTipoPedido }
$.post("ListCategories/", data, function (categoryList) {
$("#IdCategoria").empty();
$(categoryList).each(function () {
$("<option />", {
val: this.Id,
text: this.Descripcion
}).appendTo($("#IdCategory"));
});
});
}
By the way...$("#IdCategory") is the select.
The problem seems to be in the ListCategories where you might be using a async function like ajax to fetch data from server and populate the select.
So use a callback based solution like this
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(PreviousCategory); //Populates the dropdownlist
//Sets DropDownList value to previous state (posted value) after the values are loaded
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategoria").val(previousCategory);
}
}
function ListCategories(callback) {
//your ajax request to populate the select
$.ajax({}).done(function () {
//populate the select
//then at the last call the callback method which will set the value
callback()
})
};

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