Make DIV appear after 'X' amount of radio buttons are selected - javascript

I am trying to figure out how to make a DIV appear after a certain number of radio buttons are selected.
I have it working so it shows up when all of them are selected thanks to individuals inquiring on the similar aspects of this topic, but I was unable to find the code or guidance on my questions.
Your advice is greatly appreciated.
jQuery(document).ready(function() {
$(":radio").change(function() {
var names = {};
$(':radio').each(function() {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function() {
count++;
});
if ($(':radio:checked').length === count) {
$("#hello").show("400","linear","");
}
}).change();
});

$(':radio:checked').length is the number of radio buttons that are selected. So just compare this with the number you want.
if ($(':radio:checked').length == certain_number) {
...
}

It looks like you already have what you want working, but you are comparing the number of checked items to the number of total items. I would think it should work if it looked like the following:
jQuery(document).ready(function() {
$(":radio").change(function() {
var count = 3; // or whatever number you want
if ($(':radio:checked').length === count) {
$("#hello").show("400","linear","");
}
});
});

$(":radio").change(function() {
$(":radio").length == $(":radio:checked").length ? $("#hello").show() : null;
});
Your intermediate step of creating an array and then counting just to get something that is the length of the number of radios is pointless.
Firing the change event immediately after binding the event handler seems illogical to me. Are you sure you want that?

Related

Select2: Multiple select elements constrained

I am trying to achieve something and I can't find/decide what is the best way to do it, so i'm going to ask if somebody did this before or if select2 has something built in in order to achieve what I want.
Heres the thing: I have a number of select (multiple) elements in my DOM, lets say 5, all share the same options, but, If one of the selects has an option selected, I want the others to hide/remove/avoid being selected, I would like to constrain all selects in order to avoid having the same value selected in 2 different selects. I am not asking for a full code solution, I just need to know if someone already did it (if yes, would be nice to get it shared in order for future developers that stumble upon this can see the solution), or if select2 has the functionallity.
What I have done so far is:
$('.constrainedSelect').each(function(i, select) {
var selectedValue = $(select).select2("val");
var options = $('#allOptions').find('option').clone();
if (selectedValue.length !== 0) {
options.each(function(i, option) {
if($(select).find('option[value="' + $(option).val() + '"]').length !== 1) {
$(select).append(option);
}
});
} else {
options.push($("<option />", {value: e.choice.id.trim(), text: e.choice.text.trim()})[0]);
$(select).html(options);
}
});
But thats just a concept and its really buggy.
The version of select2 i'm using (and need to use, no time to change it in production yet) is Version: 3.5.2 Timestamp: Sat Nov 1 14:43:36 EDT 2014
Thanks in advance!
I have found a nice way to do this, if anyone was wondering how, I think this is a good approach but I would like to see comments and if somebody wants to improve my answer, feel free to copy the code and paste it in a separate answer, if the approach gets better I will accept that answer. Thanks guys for the help.
var $selects = $(".constrainedSelects");
$selects.on('change', function(e) {
var selectedValues = $(this).select2('val');
for (var i = 0; i < selectedValues.length; i++) {
$selects.not(this).find("option[value='" + selectedValues[i] + "']").attr('disabled', true);
}
});
$selects.on('select2-removed', function(e) {
$selects.find("option[value='" + e.val + "']").attr('disabled', false);
});
Here is a fiddle to show the result: http://jsfiddle.net/rv38f0v6/
Please See if this helps! this is a jquery validation method to avoid same values in different select boxes.
$.validator.addMethod("valOption", function(value, element) {
var curValue,
allElems,
counter,
totalCount = 0;
curValue = value;
allElems = $('#myPage select');
for (counter = 0; counter < allElems.length; counter = counter + 1) {
if (curValue === allElems.eq(counter).val()) {
totalCount = totalCount + 1;
}
}
if (totalCount === 1) {
return this.optional(element) || (true);
} else {
return (false);
}
}, "Please select different option");
$(document).on('change', '.constrainedSelect', function() {
var changedSelect = $(this);
$(".constrainedSelect").not(changedSelect).select2("val", "").select2("enable", false)
});
I think something like this event listener would take care of it. It makes sure the val of all the others are empty and then disables them so they cannot be selected from.
How about this instead:
Working Fiddle
//setup trackign array and block duplicate selections
var selectedIds = [];
$(document).on('select2-selecting', '.constrainedSelect', function(event) {
var idx = $.inArray(event.val, selectedIds);
if(idx === -1) {
selectedIds.push(event.val);
} else {
event.preventDefault();
}
});
//remove selected item from our tracking array
$(document).on('select2-removed', '.constrainedSelect', function(event) {
var idx = $.inArray(event.val, selectedIds);
selectedIds.splice(idx,1);
});

Unhide div using javascript object oriented

So i am having trouble unhiding a div, once it has been hidden.
The code:
First object
$('#filter_region').on('change', function(e) {
var temp_region_id = $('#filter_region').val();
filterRegionId($temp_region_id);
});
Seconds object:
function filterRegionId(temp_region_id)
{
if ($(temp_region_id) != 1) {
$('.showheadline').hide(); }
else { $('.showheadline').show(); }
}
Really what i want to do, is once the region is changed from the original, the div should be hidden - this works!
However, once the person goes back on the same region, the div is still hidden.
The filter_region echos from 1-8 depending on the region. I realise that i have set the region to 1, this is to test. However, even if the if-statement is set to 1, it still shows the divs when loaded, even if the region is 2-8. Hope this make any sense at all! Please feel free to ask if there are any questions regarding my explanation.
Best Regards,
Patrick
Try this, without the $(..) around the var
$('#filter_region').on('change', function(e) {
var temp_region_id = $('#filter_region').val();
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id)
{
if (temp_region_id != 1) {
$('.showheadline').hide();
}
else {
$('.showheadline').show();
}
}
A text input's value attribute will always return a string. You need to parseInt the value to get an integer
var temp_region_id = parseInt($('#filter_region').val(),10);
and remove the $ from variable name filterRegionId($temp_region_id); and if ($(temp_region_id) != 1) {
$('#filter_region').on('change', function(e) {
var temp_region_id = parseInt($('#filter_region').val(),10);
///parse it to integer
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id){
if (temp_region_id!= 1)
$('.showheadline').hide();
else
$('.showheadline').show();
}
The best solution is to rewrite you code a little.
Please add the filterRegion function on top and change the parametter name as follows
var temp_region_id = $('#filter_region').val();
filterRegionId(temp_region_id);
$('#filter_region').on('change', function(e) {
temp_region_id= $('#filter_region').val();
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id)
{
if ($(temp_region_id) != 1) {
$('.showheadline').hide();
}
else {
$('.showheadline').show();
}
}

How to use radio buttons to calculate output of highcharts

What I am trying to do is find a way so that when a radio button is checked, the value assigned to it can be used in the calculations of the chart, and updates it instantly (just like the sliders do). I think im on the right path... here is a jsfiddle: http://jsfiddle.net/nlem33/ZhER3/
var selected = 1;
$(document).ready(function(event) {
$("input[name=chooseProduct]").change(function(){
selected = $(this).val();
});
Your change function can call the sliderHandler function directly, although it needs a slight modification to work when called this way:
$("input[name=chooseProduct]").change(function(){
selected = $(this).val();
sliderHandler();
});
and the sliderHandler needs this:
if (this.id === 'slider1') {
$('#slider1_value').html(ui.value);
units = ui.value;
} else if (this.id === 'slider2') {
$('#slider2_value').html('$' + ui.value);
price = ui.value;
}
http://jsfiddle.net/L5cY6/

JavaScript while loop get select option and hide option from other select boxes

I'm trying to develop a football teamline function that will store up to 18 players (11 starting players and 7 subs) using a select box for each player.
When a player is selected from one select box they should then be hidden in all the other select boxes to stop the user from being able to select the same player again.
I've written a javascript/jquery function that does this but it is VERY long winded and I'm guessing that the best option to make it a lot more manageable would be to write a while loop but I'm getting myself confused trying to code it.
The current code (for the starting XI) can be seen at http://jsfiddle.net/aFDjS/
Am I right in thinking that what I need to do is probably have a while loop nested inside another while loop to ignore when the count is the same as the player number kind of like this...
i = 1;
playerNo = 1;
while (i < 19) {
while (playerNo < 19 && i != playerNo) {
playerID = $("#player" + i + "Name option:selected").val();
$("select#player" + playerNo + "Name >option" ).filter( "[class='"+ playerID +"']" ).hide();
$("select#player" + playerNo + "Name >option" ).filter( "[class!='"+ playerID +"']" ).show();
playerNo++;
}
i++;
}
Is this along the right lines?
No, you should be using for loops.
The standard is to use for loops when counting something and while loops when you're waiting for an event or value to change.
The logic in those for loops is hard to follow and looks wrong anyway.
But regardless of this, the easiest way to do this is using the power of jquery:
$(function() {
$("select").on("change", function() {
//reset to showing all the options
$("select option").show();
//for each selected option
$("select option:selected").each(function() {
var optionSelected = this;
var playerID = $(this).attr("class");
//hide the option in all the other dropdowns
$("option." + playerID).each(function() {
if(this != optionSelected) {
$(this).hide();
}
});
});
});
});
Working example here:
http://jsfiddle.net/4avwm/1/
Well, don't know what is complete concept of the program, but I think your solution is a bit of overkill.
I would give each checkbox a name (eg.: "plr"+ID) and I would append an onclick event to it. When event is trigered, the checkbox would search for all checkboxes of the same name and disable them.
function selectPlr(event) {
var other = document.getElementsByName(this.name); //Get element collection
for(var i=0; i<other.length; i++) {
if(other[i]!=this) { //Ignore itself
other[i].disabled = this.checked; //Disable if the player is picked, enable if unpicked
}
}
}
Of course, class name can be used instead:
var other = $("input."+this.className);
Here is the active code.
May be this would give you the idea to implement: http://jsfiddle.net/2jGDU/
$('#players').change(function () {
$('#pl_11').prepend($('option:selected', this).clone());
$('option:selected', this).remove();
if ($('option', this).length <= 8) {
$('option:first', this).remove();
$('#sub').prepend($(this).html());
$('option', this).remove();
}
});

Is there an easy way to remove items from a page depending on what I write in a textbox (similar to autocomplete)?

I am trying to implement a feature where if there are 50 links on a page for example, you start typing in a box and the items start to disappear depending on what you type. It is the same idea of autocomplete but instead of creating a list of possible links, you remove the irrelevant ones from the page.
I am sorry if my explanation is not clear enough, if you need more details please ask me and I will answer in the comments.
Thank you in advance.
var anchors = $('a');
$('#filter').bind('keyup', function () {
var filterValue = $.trim(this.value);
anchors.hide().filter(function () {
return $(this).text().indexOf(filterValue) !== -1;
}).show();
});
Example
$(".selector-for input").keyup(function(){
var text = this.value;
$(".selector-for a").each(function() {
var it = $(this);
it.text().indexOf(text) < 0 ? it.hide() : it.show()
});
});
Try using this.Call this function in your 'onKeyUp' event of the textbox
function hideFiltered(){
var text=$("#textbox").val();
var links=$('a[name="linksToHide"]');
for(var i=0;i<links.length;i++){
link=links[i];
if(link.html().indexof(text)>0){
link.hide();
}else{
link.show();
}
}
}
}

Categories