How can I invisiblize groups of controls via jQuery? - javascript

In my Sharepoint project/Web Part/Web Page, I dynamically create page elements/controls using C# in the *.ascx.cs file.
In the *.ascx file, I use jQuery for responding to events that happen on the page (selections, changes of checkbox states, etc.).
I have a need to conditionally invisiblize groups of controls/elements on the page. Specifically, if the user checks a certain checkbox, I can "remove" whole swaths of the page that, in that scenario, don't apply to her.
How can I do this? I've got this starting point:
/* If the select "Yes" (they are seeking payment for themselves, as opposed to someone else), omit (invisibilize) sections 2 and 3 on the form */
$(document).on("change", '[id$=ckbxPaymentForSelf]', function () {
var ckd = this.checked;
if (ckd) {
// what now?
}
});
I could do it the hair-pulling-out way (which would be very painful for me, because I have almost as much hair as Absalom did), and set each individual element, like so:
if (ckd) {
var $this = $('[id$=txtbxthis]');
var $that = $('[id$=txtbxthat]');
var $theother = $('[id$=txtbxtheother]');
. . . // store a reference to all the other to-be-affected elements in vars
$this.visible = false; // <= this is pseudoscript; I don't know what the jQuery to invisiblize an element is
$that.visible = false; // " "
$theother.visible = false; // " "
. . . // invisiblize all the other to-be-affected elements
}
Surely there's a more elegant/better way!
Is it a matter of assigning all the conditionally invisible elements a particular class, and then invisiblizing every element that is assigned that class, or what?
Also, I want the area formerly used by this now-invisible swath to "go away" or "roll up" not sit there with a blank stare, yawning chasm, or Gobi Desert-like featureless expanse.

there are a number of ways to do this. but in your jquery implementation I would decorate the elements with data tags that will tell the code which elements to hide and show.
<input data-group="1" type="text" />
<input data-group="2" type="text" />
var $group1 = $('*[data-group="1"]');
var $group2 = $('*[data-group="2"]');
if (ckd) {
$group1.hide();
$group2.show();
}
else{
$group2.hide();
$group1.show();
}
You could do the same thing with css classes as well but I prefer using the data attribute

If you can group your controls using classes, you could select the class which needs to be hidden in that particular scenario and just use the hide() function:
if (ckd) {
var cls = getClassForCurrentScenario();
$("." + cls).hide(); //slideUp() would be an animated alternative
}
If the controls can be grouped inside a div, for example, then you'd just need to hide that element:
if (ckd) {
var id = getElementIdForCurrentScenario();
$("#" + id).hide(); //slideUp() would be an animated alternative
}
It really depends on how you manage to group your controls into "target groups", so that you can efficiently access them later.

You can hide an element like so:
$('...').hide();
Or you can slide it up with:
$('...').slideUp();
to get a nice sliding up animation.
On a side note, you can do this to multiple elements at once, in your case:
$('[id$=txtbxthis], [id$=txtbxthat], [id$=txtbxtheother]').slideUp();

Related

Catch all radiobuttons inside a div using jQuery

Someone knows how can I get all the radiobuttons inside a div? The div has a id as follows
<div id="quest{{ $groups }}" class="quest">
I'm using Laravel, therefore my idea is to get the values inside a div, and put in jQuery something like
var radios = $("input[type='radio'][id^='quest'"+groups+"]");
But this doesn´t work, so I want to know how to get all the radiobuttons inside a div an do a loop inside using .each I think.
I need to duplicate one group of questions and then be able to do a validation, but only works for the first group, the second group is not validated and I´ve checked the id value for each radiobutton and change to previousid_2, and the questionnaire is cloned. Also I want to know how can I reset the values when I clone the questionnaire, because if you have select YES NO YES NO, in the second group when you clone it, those results are selected and the disabled fields too.
You're actually asking for several things. Your code implies you have access to the current group in a variable called groups. so...
1) select all radio inputs within a div:
var div = $("div#quest"+groups);
var radiosBtns = div.find("input[type='radio']");
2) Loop over them, and do some work on each element:
var doSomeWork = function(i,radiobtn){
console.log('the value of radio button #' + i ' is ' + radiobtn.value);
};
$.each(radioBtns,doSomeWork);
3) Duplicate a group of radio buttons:
var fromgroup = $("div#quest"+groups);
var togroup = fromgroup.clone();
var insertionPoint = $('body');
var toGroupId = 'questXXX';
// set the ID so it can be targetted
togroup.prop('id',toGroupId);
// reset radio button values
togroup.find('input[type="radio"]').each(function(){
this.prop('checked',false);
});
togroup.appendTo(insertionPoint);
4) Run validation on a specific group
var validateGroup = function(elements){
// your validation logic goes here
var isValid = false;
$.each(function(){
console.log( this.name, this.value );
});
return isValid;
};
// run the validation on the newly inserted group
var targetElements = $("#"+toGroupId).find("input[type='radio']");
var groupIsValid = validateGroup( targetElements );
You can get all radio buttons and iterate on them like following
$("input[type='radio'][id^='quest']").each(function(){
// add your logic here
});
it's very simple using Id's
To get all the elements starting with "quest" you should use:
$("[id^=quest]")
To get those that end with "jander"
$("[id$=quest]")
and the complete answer is
var radios = $("input[type='radio'][id^='quest']");
the point is what if you want to wildcard class :( :(
$("[class^=quest]")
on a dom like
<pre>
<a class="btn quest primary">link</a>
<pre>
it won't work , thus you will need a more complex wildcard that you have to till me when you find it :D
the fact is you will not need it , whenever you need to get a list of element using classes just use a common class :D
hope i helped u well

jQuery Chosen plugin query

I am using chosen plugin for a multiple select and I want to dynamically display all the selected options somewhere in the page.
I am able to show them, however, I also want to remove them if someone deselects/removes them. This is what I am struggling with.
My code till now looks like
$(".chosen-select").chosen({max_selected_options: 5}).change(function() {
var bStr = "#home-summary-right";
var htmlContent = $("#home-summary-right").html();
$(".search-choice").find("span").each(function() {
$(bStr).html("" + htmlContent);
toAppend = '<span>' + $(this).text() + '</span>';
$(bStr).append(toAppend);
});
});
Okay
Otherwise, is there any way to disable removing of elements once they are select in the multiple select? There is that cross, to which I can do display none, but I still don't know how can i disable the backspace from removing the elements.
Okay, I fixed it.
I used setTimeout in combination with bunch of other things.
The problem was after change, the inner html would return the same content as before... So I called an event after pretty much everything was done. Works super smooth!

Add/Remove elements via onclick

I have a chrome extension written in pure JS which is basically composed of functions which append data to links on the page.
An example of the functions which basically just appends a click integer to the link element passed in from another function:
function addCounttoLinks(link, counts) {
var clicks = counts.split(":")[1].split(",")[0].trim();
var count = document.createTextNode((" (" + clicks + ")"));
var dspan = document.createElement("span");
dspan.appendChild(count);
dspan.style.fontSize = "10px"; dspan.style.textAlign = "center";
link.appendChild(dspan);
}
What is the most efficient way to execute/unexecute these functions, so that I can implement a "on/off" button for the user to click which would add/remove the data appended by the extension. Is the only solution to write functions to remove the previously created elements?
Put a class on the span (say, my-nifty-extension-extra — you want it to be fairly unlikely to clash with something else), then add a class to body (say, hide-my-nifty-extension) when hiding the data, and remove it when showing it. Then use this style rule:
body.hide-my-nifty-extension span.my-nifty-extension-extra {
display: none;
}
E.g., just before your appendChild:
dspan.className = "my-nifty-extension-extra";
And then:
function showExtraData() {
document.body.classList.remove('hide-my-nifty-extension');
}
function hideExtraData() {
document.body.classList.add('hide-my-nifty-extension');
}
(One of the joys of writing a Chrome extension is that you know you have things like classList.)

How to entirely disable/enable html elements?

I have several elements on the page. Something like:
<div id="el1"><div id="el2"><span id="el3">1</span><span id="el4">2</span></div><span id="el5">3</span></div>
I need to disable/enable any of them, using their ids.
<input type="radio" name="do" onclick="disable(document.getElementById('el4'));">
<input type="radio" name="do" onclick="enable(document.getElementById('el4'));">
What should be in disable() and enable() functions to really disable elements?
By "disable" I mean make it invisible for user, inaccessible by "id" and be restorable by "enable()" function.
Is it possible to turn elements on/off? Entirely, I mean.
function addEl4(){
var elem = document.getElementById('el2');
var newElem = document.createElement('div');
newElem.setAttribute('id', 'el4');
newElem.innerHTML = 2;
elem.appendChild(newElem);
};
function disable(elem){
var container = document.getElementById('el2');
container.removeChild(elem);
};
If you are talking in terms of removing the element from the page completely.
Then you can use the .removeChild() method..
Then need to append it to the div you are talking about..
Check Fiddle
You may use
document.getElementById('el4').style.display='none'; // hide
document.getElementById('el4').style.display=''; // show
You could define functions like this :
function hide(element){
element.style.display='none';
}
function show(element){
element.style.display='';
}
I really suggest not to use the enable and disable words, as they have other meanings (a disabled widget is one you can see but you can't change).
A better solution would be to define a css class
.hidden {
display: none;
}
and change the class in js :
document.getElementById('el4').classname='hidden'; // hide
If you want to completely remove an element, you may use removeChild :
var node = document.getElementById('el4');
node.parentNode.removeChild(node);
but it's almost never useful. Prefer to hide as is commonly done.

Use function to write to .js file

I've never particularly used JS much, with the exception of basic animations,
The page I'm working on requires me to fade out the active div and fade the requested one in, I have around 25 different div's I'll be fading between. At the minute I can't think of how to only fade the active one out so I'm trying to fade every div but the one that's requested out.
Here's the code I'm attempting to get working
var active = 0;
for (i=0;i<array.length;i++) {
if (i != active){
document.write("$('."+array[i]+"').fadeOut(900);");
}
naturally i know the document.write shouldn't be there, but ideally that code has to be printed into the .js file I'm using, however. I don't have a clue how to print it to the .js.
any suggestions would be greatly appreciated, or a way to do this in php without a page reload!
When you find yourself generating code on the fly, it usually indicates that you want to take a step back and re-evaluate your approach. :-)
In this case, there's no need to create the JavaScript dynamically. It's just a matter of running the code.
I wasn't sure what your definition of "active" was, so here's something that fades divs in/out on the basis of what buttons you press:
The HTML:
<input type='button' value='1'>
<input type='button' value='2'>
<input type='button' value='3'>
<input type='button' value='4'>
<input type='button' value='5'>
<input type='button' value='6'>
<div id='container'>
<div class='c1'>This is c1</div>
<div class='c2'>This is c2</div>
<div class='c3'>This is c3</div>
<div class='c4'>This is c4</div>
<div class='c5'>This is c5</div>
<div class='c6'>This is c6</div>
</div>
The JavaScript (teaching version):
jQuery(function($) {
// Hook our buttons; this selector hooks all of them,
// so you probably want to narrow that down, but I
// have no idea what your definition of "active" is,
// so I made one up.
$(":button").click(function() {
// Get the value of the button, e.g., 1, 2
var val = this.value;
// Get all of the divs in the container
var divs = $("#container div");
// Fade out all of the ones that aren't our target;
// fade in the one that is
divs.not(".c" + val).fadeOut(900);
divs.filter(".c" + val).fadeIn(900);
});
});
Live copy
That does this:
Uses the jQuery ready function (the shortcut form where I just pass a function into the jQuery function) to run the code when the page is "ready" (the DOM has been built)
Looks up all divs we want to be dealing with. In my case, it's all the divs in a container, but you can use just about any CSS3 selector you want (and then some).
Uses not with a class selector to filter out the div that has the target class, then uses fadeOut to start fading the other ones out.
Uses filter to reduce the set to just our target div, and fadeIn to start fading it in.
That version is for clarity. Here's a more concise version (still perfectly clear to people who know jQuery well, but tricky for folks still finding their feet):
The JavaScript (chained version using end):
jQuery(function($) {
// Hook our buttons; this selector hooks all of them,
// so you probably want to narrow that down, but I
// have no idea what your definition of "active" is,
// so I made one up.
$(":button").click(function() {
// Get the value of the button, e.g., 1, 2
var val = this.value;
// Get all of the divs in the container
// Fade out all of the ones that aren't our target;
// fade in the one that is
$("#container div")
.not(".c" + val).fadeOut(900)
.end()
.filter(".c" + val).fadeIn(900);
});
});
Live copy
Not sure why you are using document.write instead of simply executing the javascript.
var active = 0;
for (i=0;i<array.length;i++) {
if (i != active) {
$("."+array[i]).fadeOut(900);
}
Additionally, try using a jQuery selector to select all the non-active divs by adding an additional class to each div:
var active = array[0];
var classname = "some_class";
$("div." + classname + ":not(." + active + ")").fadeOut(900);
You could even just select the visible divs that are not the active one and fade them out:
var active = array[0];
var classname = "some_class";
$("div." + classname + ":not(." + active + "):visible").fadeOut(900);

Categories

Resources