Display Content based On Option Clicked in A Select Box - javascript

I spent several hours on this and couldn't find a solution that worked, so I'm turning to you :) As you can see from this fiddle (http://jsfiddle.net/PPcgE/), I was able to target the radio buttons by click with this code:
$("input[type='radio']").click(function (e) {
if ($('.cos-cond').is(":visible")) {
e.preventDefault();
} else {
var clicked = $(this).attr('title');
var cls = [$('.one'), $('.two'), $('.three'), $('.four'), $('.five'), $('.six'), $('.seven'), $('.eight'), $('.nine'), $('.ten')];
for (i = 0; i < cls.length; i++) {
if (cls[i].attr('title') === clicked) {
cls[i].fadeIn('fast', function(){
setTimeout(function(){
$('.cos-cond').fadeOut('slow');}, 5000);
});
}
}
}
});
I'm trying to do exactly the same thing (displaying either span.eleven, span.twelve or span.thirteen this time) based on which option is clicked/selected in the select box. The best I've been able to manage is to get all three to appear at once.

Your original code is broken, i've create a fiddle that fixes it.
Your problem was when you were fading out, your selector was selecting all of them, visible or not, and then showing ALL of them while fading out.. thus always showing the last one (topmost).
if (cls[i].attr('title') === clicked) {
cls[i].fadeIn('fast', function(){
setTimeout(function(){
$('.cos-cond:visible').fadeOut('slow');}, 5000);
});
}
Beyond that you need to provide your attempt at how you tried to get the dropdown box working. You only provided the old code and nothing more.

Your code shouldn't be longer than this
$(document).ready(function(){
$("input[type='radio']").click(function (e) {
$('.cos-cond, .work-cond').hide();
var clicked = $(this).attr('title');
$('span.cos-cond[title=' + clicked + ']').fadeIn(300);
});
$("select").change(function (e) {
$('.cos-cond, .work-cond').hide();
var value = $(this).val();
var title = $('option[value="' + value + '"]', this).attr('title');
$('span.work-cond.' + title).fadeIn(300);
});
});
http://jsfiddle.net/PPcgE/5/

Try
$(".emf-hide").change(function(e){
var val = $(".emf-hide option:selected").val();
$('.work-cond').hide();
switch(val){
case 'Like New - No Functional Problems':
$('.eleven').show();
break;
case 'Minor Functional Problems':
$('.twelve').show();
break;
case 'Non-functional':
$('.thirteen').show();
break;
}
});
Working example here

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

Javascript Multiple Divs same classname but different id's. Always returns last div on clicking any of them

I feel silly asking this question. I have a javascript problem that I have been trying to solve since spring break.
I dynamically create divs to contain ratings for a product. But when I click on one of them, it always returns the last one.
for(var i=0; i < 5; i++) {
// Create Class called divReview
var divReview = document.createElement("div");
divReview.className = "divReview";
counter_ratings++;
var s = counter_ratings.toString();
divReview.id = "ratings" + s;
divReview.innerHTML = divReview.id;
$( divReview ).click(function() {
alert("You clicked " + divReview.innerHTML);
});
mainContainer.appendChild(divReview);
}
Here's the fiddle:
http://jsfiddle.net/alvasay/a9GZq/4/
I am pretty sure this is a simple problem, but I just can't see where I'm doing wrong. Thanks!
As mglison said, late binding. Alternative solution though is to use this in place of divReview in your click handler to reference the element being clicked.
$( divReview ).click(function() {
alert("You clicked " + this.innerHTML);
});
http://jsfiddle.net/a9HAH/
You're experiencing late binding. At the time the function is called, the value of divReview is the last value it had in the loop. I've solved it by creating a function which wraps the actual function to return so that you get the correct value from the closure:
Essentially, the code is something like:
for (...) {
...
var funcMaker = function(divRev) {
return function() {
alert("you clicked " + divRev.innerHTML);
};
};
$( divReview ).click(funcMaker(divReview));
}
http://jsfiddle.net/a9GZq/9/
Apart from the problem mentioned by mgilson, you have an odd mix of plain JS and jQuery. Here's a shorter version
for (var i = 1; i < 6; i++) {
var divReview = $('<div id="ratings' + i + '" class="divReview">ratings' + i + '</div>');
$('#gameContainer').append(divReview);
divReview.click(function() {
alert("You clicked " + this.innerHTML);
});
}

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