How to synchronize data-attr and select box vaule? - javascript

I have two elements like:
<select id="data">
<option value=1>hoge</option>
<option value=2>fuga</option>
<option value=3>hogehoge</option>
</select>
hoge
fuga
hogehoge
if I pick hoge on select box, I want data-id="1" to be selected and do some stuff (changing background etc.) using jQuery.
If I click a[data-id="3"], select box option 'hogehoge' to be selected vice versa.
any help would be appreciated.

Have a look at the last line in the click listener. You can trigger a change on an element which will call the corresponding listener instead of duplicating code.
$(function() {
$("#data").on("change", function() {
$("a").removeClass("active"); // remove active class from all <a>
$("a[data-id='" + $(this).val() + "']").addClass("active"); // add active class to link with corresponding data-id
});
$("a").on("click", function() {
$("#data option[value='" + $(this).data("id") + "']").prop("selected", true); // change the selected value
$("#data").trigger("change"); // trigger change on #data to keep active link synced
});
});
.active {
background-color: cornflowerblue;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="data">
<option value=1>hoge</option>
<option value=2>fuga</option>
<option value=3>hogehoge</option>
</select>
hoge
fuga
hogehoge

$(document).ready( function(){
$('a').click(function(){
var id = $(this).data('id');
$('#data').find('option[value='+id+']').prop('selected',true);
)};
)};
I implemented the function in JSFiddle
https://jsfiddle.net/dphf267u/

Related

Add class active to tab button on selected menu option

I have the following tabs component:
<a data-tab="tab-1" class="button active">Tab 1</a>
<a data-tab="tab-2" class="button">Tab 2</a>
<a data-tab="tab-3" class="button">Tab 3</a>
<div class="tab-content active" id="tab-1">Tab 1 content</div>
<div class="tab-content" id="tab-2">Tab 2 content</div>
<div class="tab-content" id="tab-3">Tab 3 content</div>
And underneath it I have a select menu:
<select>
<option>Please select</option>
<option value="tab-1">Tab 1</option>
<option value="tab-2">Tab 2</option>
<option value="tab-3">Tab 3</option>
</select>
When you click on the tabs the respective select menu option changes.
What I'm trying to achieve now is to add the class active to the tab buttons when its respective select menu option is chosen and obviously remove that class from the previous tab button.
This is the JS:
$('.button').click(function(){
var tab_id = $(this).attr('data-tab');
$('.button').removeClass('active');
$('.tab-content').removeClass('active');
$(this).addClass('active');
$("#" + tab_id).addClass('active');
$('select').val($(this).data('tab')).change();
})
$("select").change(function () {
$('.tab-content').removeClass('active');
$('#' + $(this).val()).addClass('active');
});
I've tried to add $('.button').addClass('active'); like so:
$("select").change(function () {
$('.tab-content').removeClass('active');
$('#' + $(this).val()).addClass('active');
$('.button').addClass('active');
});
However this adds the class active to every tab button chosen from the select menu.
Please see Demo here
Thank you for your help.
Consider the following code:
$(".button").click(function () {
var tab_id = $(this).attr("data-tab");
$(".button").removeClass("active");
$(".tab-content").removeClass("active");
$(this).addClass("active");
$("#" + tab_id).addClass("active");
$("select").val($(this).data("tab"));
});
$("select").change(function () {
var target = $(this).val();
$(".button[data-tab='" + target + "']").click();
});
You already have the Click event setup, so no need to double your work.
$("select").change(function () {
$('.tab-content').removeClass('active');
$('.button').removeClass('active');
$('#' + $(this).val()).addClass('active');
$('.button[data-tab="'+ $(this).val() +'"]').addClass('active');
});
Native jQuery:
$("select").change(function () {
$('.tab-content').removeClass('active');
$('#' + $(this).val()).addClass('active');
$('.button').removeClass('active');
$('.button').eq($(this).prop('selectedIndex')-1).addClass('active');
});
How it works:
First:
$('.button').removeClass('active') removes class active from all button-class elements.
Second:
$(this).prop('selectedIndex')-1 is the index of the selected element. That way, you add class active only to the exact one selected element.

Hide elements in jQuery based on select value

I am building a filtering tool using a select element. When you choose something from the drop down, it should filter the divs below to show only the div for that item.
I am targeting the divs using the select value which is also the class of the div the item is in. So for example, if you choose shirts in the drop down the value would be item-shirts and a div below would have a class of item-shirts.
I have figured out how to hide everything that doesn't have the class of the selected item when something is selected. But I can't figure out how to unhide everything when something else is selected. Any help would be greatly appreciated!
Here is my HTML
<select>
<option value="item-shirts">Shirts</option>
<option value="item-shoes">Shoes</option>
<option value="item-shoes">Pants</option>
</select>
<div class="item-section item-shirt></div>
<div class="item-section item-shoes></div>
<div class="item-section item-pants></div>
Here is my jQuery
$('select').on("change", function() {
var value = $('select').val();
if($('.item-section').hasClass(value)) {
$('.item-section.'+value).siblings().hide();
} else {
$('.item-section.'+value).siblings().show();
}
This is similar to adding an active class to a list/group of elements. Typically what you do is loop through all the elements removing the active class (even though it's only applied to one element), then add the active class to the specific element. In your case you might want to hide all DIVs, then show the specific DIV.
var $sections = $( '.item-section' );
$('select').on( 'change', function ( e ) {
$sections.hide();
$( '.' + this.value ).show();
} );
.item-section {
margin: 2rem 0;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="item-shirts">Shirts</option>
<option value="item-shoes">Shoes</option>
<option value="item-pants">Pants</option>
</select>
<div class="item-section item-shirts">Shirt</div>
<div class="item-section item-shoes">Shoes</div>
<div class="item-section item-pants">Pants</div>
Note: You had a few errors in your markup that I changed to make everything work. i.e. Duplicate values for your <option> tags and some missing quotes.
I've done a couple performance improvements too.
You also don't need $( 'select' ).val() inside of your event handler. The context of the handler is the <select> element so you can use the this.value instead and skip jQuery querying the DOM to do the same.
I've also cached the .item-section elements so you're not querying the DOM over and over again on each change of the select.
There was no need to test for hasClass(). All you need to do is get the value from the selected option and show the <div> having that class. I added an extra empty option so that when you select it, it will show all <div>s.
$('select').on("change", function() {
var value = $('select').val();
if (value) {
$(".item-section").hide();
$("." + value).show();
} else {
$(".item-section").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value=""></option>
<option value="item-shirt">Shirts</option>
<option value="item-shoes">Shoes</option>
<option value="item-shoes">Pants</option>
</select>
<div class="item-section item-shirt">Shirts</div>
<div class="item-section item-shoes">Shoes</div>
<div class="item-section item-pants">Pants</div>

JS - apply global function to all select boxes

I have 200+ select boxes, each individually named and with Yes / No / NA as answer options, and now would like to have the background of the <option value="No> option highlighted in red once it is selected.
This works fine via the onchange attribute when adding it to the specific select box, however since I have 200 of those, I do not want to apply this code one by one, but rather apply a global JS function to all <select> boxes, which is where I am stuck. How can I address all select boxes with one JS function?
Javascript:
$('select').on('change', function () {
$(this).focus();
$(this).select();
$(this).className = this.options[this.selectedIndex].className;
});
CSS:
.green{ background-color:green; }
.red{ background-color:red; }
HTML:
<select id="boh_corridor" name="boh_corridor">
<option value=""></option>
<option value="Yes" class="green">Yes</option>
<option value="No" class="red">No</option>
</select>
EDIT: to be exact, the problem is that the option is not highlighted in either red or green at the moment, hence I am suspecting that the function is not being applied. The goal is to have the option highlighted in red/green when selected and while being selected from the dropdown menu.
Two things:
jQuery objects don't have a className property; DOM elements do. Instead of
$(this).className = ...
use
this.className = ...
Your code hooks the change event on select elements that exist as of when that code runs. So you need to be sure they exist prior to running that code. You can do that by ensuring your script tag is at the end of the document, just prior to the closing </body> tag; or by using jQuery's ready callback. Alternately, you can use event delegation (covered later).
Example expecting that the script tag will be at the end of the document (which is where Stack Snippets put it), which is best practice:
$('select').on('change', function() {
$(this).focus();
$(this).select();
this.className = this.options[this.selectedIndex].className;
});
.green {
background-color: green;
}
.red {
background-color: red;
}
<select id="boh_corridor" name="boh_corridor">
<option value=""></option>
<option value="Yes" class="green">Yes</option>
<option value="No" class="red">No</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you don't control where your script tags go or prefer to do something else, using jQuery's ready:
$(document).ready(function() {
// ...the code here...
});
Another option is event delegation. Although change doesn't natively bubble, jQuery makes it bubble, and so you can do this:
$(document).on("change", "select", function() {
$(this).focus();
$(this).select();
this.className = this.options[this.selectedIndex].className;
});
Then it doesn't matter whether the select elements exist or not when you run that code; the event handler is on document, not the individual selects. So it doesn't matter where the script tag is, and you don't need ready.
Example:
$(document).on('change', 'select', function() {
$(this).focus();
$(this).select();
this.className = this.options[this.selectedIndex].className;
});
.green {
background-color: green;
}
.red {
background-color: red;
}
<select id="boh_corridor" name="boh_corridor">
<option value=""></option>
<option value="Yes" class="green">Yes</option>
<option value="No" class="red">No</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Side note: You can use chaining with jQuery objects, rather than repeatedly calling $(): $(this).focus().select();
Do you have a common class for those select boxes? If you do, you can select them doing this:
$(".your_class").on("change", function(){
$(this).addClass("border_red"); //add border to select
$("option",this).removeClass("red"); //clear classes
$("option:selected", this).addClass("red"); //add .red class
});
Check out the fiddle: https://jsfiddle.net/m5mzwyt2/
The code below works for me, both in the sense of highlighting the option value in green / red, and to keep the background color once the option has been selected
JS:
$(document).ready(function() {
$('select').on('change', function () {
$(this).focus();
$(this).select();
this.className = this.options[this.selectedIndex].className;
});
});
I'm not sure what exactly you want to achieve.
I changed your code to:
$('select').on('change', function () {
$(this).focus();
$(this).select();
$(this).css("background-color",$(this).find(":selected").attr("class"));
});
It sets the background color after select based on class name.
Tested on Firefox

Display different result if didn't find the ID in jQuery

I have a select menu and some divs associates with it. I want the select menu to hide / show divs according to the select menu value. But if the jQuery didn't find the associative div then it should alert some text.
Here is my code:
$('select').change(function(){
var div = $(this).val();
$('#results div').hide();
$('#' + div).show();
});
#results div {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="div_1">Div 1</option>
<option value="div_2">Div 2</option>
<option value="div_3">Div 3</option>
</select>
<div id="results">
<div id="div_1">Div 1</div>
<div id="div_2">Div 2</div>
</div>
As you can see in my example above there is no DIV 3 so I want an alert saying that there is no DIV 3 found.
Any kind of help appreciated :)
Use length of a jQuery object to check for matches
$('select').change(function() {
var $div = $('#' + $(this).val()).show();
if ($div.length) {
$('#results div').not($div).hide();
} else {
alert('No Match')
}
});
Personally I think this is a bad user experience and a better approach would be to remove or disable <option>s that don't have matches.
$('option').filter(function(){
return !$('#' + this.value).length;
}).remove()// or prop('disabled', true);
check this fiddle
$('select').change(function(){
var div = $(this).val();
$('#results div').hide();
if($('#results').find('#' + div).length > 0){
$('#' + div).show();
} else{
alert("not find")
}
});

Issue displaying divs using show.hide?

Hi I have some javascript which works in a standalone web page with 5 divs, what it does is when an option is selected it will show a div and hide the others based on drop down selection.Basically what the code does is when a sector is selected on the drop down that corresponding DIV will be displayed eg pubs.
The problem I am having is in the web page I want this working on I have lots of Div tags and when the page loads all the Divs on the page are hidden, obviously I don't want this.
Any help would be much appreciated
The code that hides all the divs on page load is
$('div').not(name).hide();
Is there a way of solving this problem I cant see how I am going to get round it at the moment.?
JS
<script>
$(document).ready(function () {
function showTab( name )
{
name = '#' + name;
$('div').not(name).hide();
$(name).show();
}
$('#dropdown').change( function() {
showTab( $( this ).val() );
});
showTab( $('#dropdown').val() );
});
HTML
<form>
<p>
<select id="dropdown" name="dropdown">
<option value="Pub-Chains" selected="selected">Pubs </option>
<option value="Councils">Councils </option>
<option value="Property">Property </option>
<option value="Various">Various </option>
<option value="Universitys">Universitys </option>
</select>
</p>
</form>
My Div's are named like so
Div id="Pub-Chains"
Div id="Councils"
Div id="Property"
Div id="Various"
Div id="Universitys"
You have to group up the div you want to participate in show hide to separate them from other divs on the page. You can assign a common class to them and use that class to hide them.
Div id="Pub-Chains" class="opt"
Div id="Councils" class="opt"
Div id="Property" class="opt"
Div id="Various" class="opt"
Div id="Universitys" class="opt"
$('div.opt').hide();
$(document).ready(function () {
var ddl = $("#dropdown");
$('#' + ddl.val()).show().siblings().hide();
ddl.change(function () {
$('#' + $(this).val()).fadeIn().siblings().hide();
});
});
See demo
If your target <div>s are all siblings then you can easily do something like follows.
<div>
<div id="Pub-Chains">
<div id="Councils">
<div id="Property">
...
</div>
$(function(){
$("select#dropdown").change(function(){
$('#' + $(this).val()).show().siblings().hide();
}).change();
});
See it here.
If you have a more complicated layout then you can think of using classnames to group the <div> elements.
try this:
$(document).ready(function () {
function showTab( name ){
name = '#' + name;
$(name).siblings().hide(); //<-- hide this way
$(name).show();
}
and if this is not working then you can do this just put it outside of doc ready handler
function showTab( name ){
name = '#' + name;
$(name).siblings().hide(); //<-- hide this way
$(name).show();
}
$(document).ready(function () {
// then all your change stuff here
create a parent div to all this div... and call it in selector..
try this
<div id="tabdivs">
Div id="Pub-Chains"
Div id="Councils"
Div id="Property"
Div id="Various"
Div id="Universitys"
</div>
jquery
*updated*
$('#tabdivs').children().not(name).hide();
fiddle here..

Categories

Resources