I am trying to hide an element when a certain option value is selected from a fieldset drop down. I am unsure how to use jQuery to read the text contained in the option value (either the actual text or the value is fine):
<div class="filter_options">
<input id="search_query" type="hidden" value="Texts" />
<fieldset class="filterType">
<label>Filter By Type</label><select id="search_filter_type">
<option value="">All</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option></select></fieldset>
</div>
and then hide the certain div classes "pg_list" which do not contain the selected value.
<div class="pg_list">
<p>This text contains a Dog</p>
</div>
<div class="pg_list">
<p>This text contains a Cat</p>
</div>
<div class="pg_list">
<p>This text contains a Rabbit</p>
</div>
So If I choose option value - Cat, then it would hide the div containing Dog or Rabbit, and leave Cat.
Lastly, I have the following .css ready to go:
.displayNone{
display: none;
}
Hopefully this makes sense. Here is my jQuery for a input text field which works, but I can't work out how to use the same basis to work for a selected drop down:
$('input').on('keypress keyup', function(){
var value = $(this).val().toLowerCase();
if (value != '') {
$('.pg_list').each(function () {
if ($(this).text().toLowerCase().indexOf(value) > -1) {
$(this).removeClass('displayNone');
} else {
$(this).addClass('displayNone');
}
});
} else {
$('.pg_list').removeClass('displayNone');
}
});
Thank you for reading.
First, you need to select the correct component, which is the dropdown box: $('#search_filter_type'). Second, you want this to occur when the value of the dropdown box is changed: $('#search_filter_type').on('change', ...
$('#search_filter_type').on('change', function() {
var value = $(this).find('option:selected').text().toLowerCase();
if (value != "all") {
$('.pg_list').each(function() {
if ($(this).text().toLowerCase().indexOf(value) > -1) {
$(this).removeClass('displayNone');
} else {
$(this).addClass('displayNone');
}
});
} else {
$('.pg_list').removeClass('displayNone');
}
});
.displayNone {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filter_options">
<input id="search_query" type="hidden" value="Texts" />
<fieldset class="filterType">
<label>Filter By Type</label>
<select id="search_filter_type">
<option value="">All</option>
<option value="Cats">Cat Pictures</option>
<option value="Dogs">Dog Pictures</option>
</select>
</fieldset>
</div>
<div class="pg_list">
<p>This text contains a Dog Pictures</p>
</div>
<div class="pg_list">
<p>This text contains a Cat Pictures</p>
</div>
<div class="pg_list">
<p>This text contains a Rabbit</p>
</div>
In jQuery, to read the value of a <select>, it's the same as <input>:
$('#my-select').val(); // where this is your select
You can put it in a change event, which is what fires when it is changed:
$('#my-select').on('change', function() {
var value = $(this).val().toLowerCase();
// rest of your code
});
If you want the text of the selected option, you can use this instead:
$('#my-select').on('change', function() {
var value = $(this).find('option:selected').text();
// rest of your code
});
A slight improvement to your design though would be to add a class to each of your <div> elements which match the value of your options. Then, instead of having to loop through, you can use not() to set it on everything except the one you want to leave visible.
$('select').on('change', function () {
var value = $(this).val();
$('#divs').children() // all children of the proper parent
.removeClass('displayNone') // remove 'displayNone' from them all
.not('.' + value) // remove the one we aren't hiding
.addClass('displayNone'); // add 'displayNone' to all remaining
});
.displayNone {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="">-- Select --</option>
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="rabbit">Rabbit</option>
</select>
<div id="divs">
<div class="cat">Cat</div>
<div class="dog">Dog</div>
<div class="rabbit">Rabbit</div>
</div>
By doing it this way, you aren't locking yourself in to them always having matching text, giving you better flexibility. You also don't have to loop through and do a text comparison.
Related
I have the following dropdown:
<select name="about_performance_lead_singer" id="about_performance_lead_singer" value="">
<option value="Toni">Toni</option>
<option value="Jack">Jack</option>
<option value="James">James</option>
</select>
Below this I have the following divs:
<div class="singer_profile_overview" id="toni">...</div>
<div class="singer_profile_overview" id="jack">...</div>
<div class="singer_profile_overview" id="james">...</div>
These are set to display:none using css
I'm trying to make it so when I select the name from the dropdown, the class "visible" is added to the corresponding div - and then removed again if the selection is changed again.
Here is what I have tried so far, but with no luck:
jQuery(document).ready(function($){
$("#about_performance_lead_singer").change(function () {
$('#'(this).val()).addClass('visible');
});
});
Here is how I would do this:
html:
<select name="about_performance_lead_singer" id="about_performance_lead_singer" value="">
<option value="nothing">Select One</option>
<option value="Toni">Toni</option>
<option value="Jack">Jack</option>
<option value="James">James</option>
</select>
<div class="singer_profile_overview" id="Toni">toni</div>
<div class="singer_profile_overview" id="Jack">jack</div>
<div class="singer_profile_overview" id="James">james</div>
jquery:
jQuery(document).ready(function($){
$("#about_performance_lead_singer").change(function () {
var $this = $(this);
$('.singer_profile_overview').removeClass('visible');
$('#' + $this.val()).addClass('visible');
});
});
Couple of notes:
It is a good practice to store $(this) in a local variable, I usually call it $this.
You had an upper case / lower case problem in your original code. The id of the class to update needs to match the id you call in your selector
Remove the visible class from every <div> prior to applying one.
And there is still one problem, if you click your dropdown and select the first option, the event will not fire because nothing changed. That is why I added a 'Select One' option.
And here is a fiddle.
Try this. You also need to convert the value to lowerCase() to get the exact match.
<select name="about_performance_lead_singer" id="about_performance_lead_singer" value="">
<option value="Toni">Toni</option>
<option value="Jack">Jack</option>
<option value="James">James</option>
</select>
<div class="singer_profile_overview" id="toni">toni</div>
<div class="singer_profile_overview" id="jack">jack</div>
<div class="singer_profile_overview" id="james">james</div>
<style>
.singer_profile_overview
{
display:none;
}
.visible
{
display: block
}
</style>
<script>
jQuery(document).ready(function($){
$("#about_performance_lead_singer").change(function () {
$('.singer_profile_overview').removeClass('visible'); // hide all divs by removing class visible
$('#' + $(this).val().toLowerCase()).addClass('visible'); // find the matching div and add class visible to it
});
});
</script>
Example : http://jsfiddle.net/RxguB/204/
It is because the value of the dropdown are capitalized, while your ids are lowercase. Consider the following:
jQuery(document).ready(function($){
$("#about_performance_lead_singer").change(function () {
$('#'(this).val().toLowerCase()).addClass('visible');
});
});
Or alternatively, you can manually change the values to lower case, or the ids to be capitalized to match the values.
To answer the question as it was asked:
$("#about_performance_lead_singer").on("change", function(){
$(".singer_profile_overview").removeClass("visible");
$("#" + $(this).val().toLowerCase()).addClass("visible");
});
However, if you're only using the class "visible" to toggle their display, you can replace
removeClass("visible")
with
hide()
and
addClass("visible")
with
show()
Use the :selected selector to find the option that was selected. We can get its value by calling the prop method and passing in value as an attribute. Since the ids we are trying to get are lowercase, we use the toLowerCase() method.
The div we're trying to get is of the class .singer_profile_overview. We should use the filter function to get the ids. We store the result of this filter in a jQuery variable and finally add a class to it.
$("#about_performance_lead_singer").change(function () {
var selectedValue = $(":selected").prop("value").toLowerCase();
var selectedDiv = $(".singer_profile_overview").filter(function() {
return $(this).prop("id") == selectedValue;
});
selectedDiv.addClass('visible');
});
.visible {
color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="about_performance_lead_singer" id="about_performance_lead_singer" value="">
<option value="Toni">Toni</option>
<option value="Jack">Jack</option>
<option value="James">James</option>
</select>
<div class="singer_profile_overview" id="toni">Toni</div>
<div class="singer_profile_overview" id="jack">Jack</div>
<div class="singer_profile_overview" id="james">James</div>
I have a jQuery code that displays a div upon selection of an option in a dropdown list. It is working fine but not as I need. the problem is that upon selecting the option, the page refreshes as there is an onchange="submit()" on the select. That makes the div appears for about half second and then disappear again when the page is loaded
Sample HTML:
<select onchange="submit()">
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display:none;">This is a string.</div>
jQuery:
$('select').change(function(){
decide($(this));
});
var decide = function (elem) {
var touch = elem;
if (touch.val() === 'anything') {
return $('#somediv').css('display', 'block');
}
};
I want the div to be displayed when the option of id="two" and value="anything" is selected, and to remain displayed after the page refreshes. When the user selects the other option, the div disappears and remains hidden after the page refreshes. How can I achieve this please? All answers would be greatly appreciated.
You should remove the submit() from the onclick and submit after you call the decide function
Something like:
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display:none;">This is a string.</div>
JS:
$('select').change(function(){
decide($(this));
$('form').submit();
});
var decide = function (elem) {
var touch = elem;
if (touch.val() === 'anything') {
return $('#somediv').css('display', 'block');
}
};
I'd suggest the following approach:
// define the function:
function showIfSelected() {
// 'this' is passed in by jQuery, and is the <select> element,
// this.options is a NodeList of the <option> elements of
// the <select>, this.selectedIndex is the index of the selected
// <option> from amongst that NodeList:
var opt = this.options[this.selectedIndex];
// finding all <div> elements with a 'data-showif' attribute:
$('div[data-showif]')
// hiding them all:
.hide()
// filtering that collection of <div> elements, to find the one
// whose 'data-showif' attribute shares the value with the <option>:
.filter('[data-showif=' + opt.value + ']')
// showing that <div>:
.show();
}
// binding the showIfSelected() function as the change-event handler:
$('select').on('change', showIfSelected)
// triggering the change event (to show/hide the correct <div>
// on document ready:
.change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" data-showif="anything">This is a string.</div>
References:
CSS:
Attribute selectors.
*jQuery:
change().
on().
filter().
hide().
show().
If you don't want to use ajax to submitting your data, you should pass selected value via get/post or store it in a session/cookie then retrive it when the page loads.
Instead, if you use ajax you could do something like this
$('select').change(function(){
decide($(this));
$('form[name=a]').submit();
})
var decide = function (elem) {
var touch = elem;
if (touch.val() === 'anything') {
return $('#somediv').css('display', 'block');
}
}
$('form[name=a]').submit(function(){
$('#res').text('Submitted!');
// Put $.ajax to submit your data
return false; // Commenting this will result in a page refresh
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="a" method="post">
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
</form>
<div id="somediv" style="display:none;">This is a string.</div>
<div id="res"></div>
Try this code,it may works.
<option id="one" value="First">Car</option>
<option id="two" value="Second" selected="selected">Plane</option>
</select>
<div id="div1">This is a string</div>
jQuery:
$(document).ready(function () {
$("select").change(function () {
var v = $("select").val();
if (v == "Second") {
$("#div1").show();
}
else {
$("#div1").hide();
}
});
});
How can i hide and show a div when click on the basis of text box. i want to show these type of result,the cursor pointer is inside the textbox the div will shown otherwise the focus is out the div will be hidden and if any value is inside a textbox the div will shown if the value is cleared the div will be hidden .these are the code
<div class="banner_search_inner_box_search">
<input type="text" name="search" class="search" id="searchid" onkeyup="getshows();" value="" placeholder="Enter a City,Locality" autocomplete="off">
<div id="result"></div>
</div>
<div id="drope_box" style="display:none;">
<div class="banner_search_type">
<select id="property_type" name="property_type">
<option value="All">All</option>
<option value="Apartment">Apartment</option>
<option value="Plot">Plot</option>
</select>
</div>
<div class="banner_search_price_min">
<select name="price_min" class="search_list" id="price_min">
<option value="">Price Min</option>
<option value="100000">1 lac</option>
<option value="1000000">10 lacs</option>
</select>
</div>
<div class="banner_search_price_max">
<select name="price_max" id="price_max">
<option value="">Price Max</option>
<option value="100000">1 lac</option>
<option value="1000000">10 lacs</option>
</select>
</div>
</div>
here is my js code
<script type="text/javascript">
function getshows()
{
if(document.getElementById("searchid").value != "")
{
document.getElementById("drope_box").style.display="block";
}
else
{
document.getElementById("drope_box").style.display="none";
}
}
</script>
<script type="text/javascript">
$('#searchid').blur(function() {
$("#drope_box").hide()
});
$('#searchid').focus(function() {
$("#drope_box").show()
});
</script>
somebody please help me
Here: http://jsfiddle.net/Kq9pX/
JS
Do it on load: Wrap around document.ready function.
$('#searchid').blur(function() {
if($(this).val() != ""){
$("#drope_box").show();
}
else{
$("#drope_box").hide();
}
});
$('#searchid').focus(function() {
$("#drope_box").show();
});
It's generally advised to attach events using jQuery's on rather than blur(), focus(), click() etc in newer versions of jQuery, although I admit in this case there is no difference (read more here Why use jQuery on() instead of click()). But caching jQuery objects by storing them in a variable, like below, is slightly faster.
var $search = $('#searchid');
var $dropBox = $('#drope_box');
$search.on('blur', function () {
$dropBox[($.trim($search.val()).length > 0 ? 'show' : 'hide')]();
}).on('focus', function () {
$dropBox.show();
});
There's no problem with show and hide other than when it's showed the div hides if you try to select the options, to turn this around we can use focusout on the drope_box div:
$(document).ready(function(){
$('#drope_box').focusout(function() {
//check if the text input and selects have values selected
if($("#searchid").val() == "" &&
$("#property_type").val() == "" &&
$("#price_min").val() == "" &&
$("#price_max").val() == "" )
$("#drope_box").hide() //if not, hides
});
$('#searchid').focus(function() {
$("#drope_box").show()
});
});
Of course, for it to work the:
<option value="All">All</option>
Must be cleared:
<option value="">All</option>
FIDDLE: http://jsfiddle.net/e672Y/1/
Use jQuery:
$("#textbox").mouseenter(function(){
$("#div").show();
});
$("#textbox").mouseleave(function(){
$("#div").hide();
});
This so far will show the div whilst it is hovered, mouseenter checks if the textbox is moused over, mouseleave checks if it is not.
EDITED : (corected code mistake)
I have created a form with several fields, chosen via a dropdown.
This works fine and I can save the data to database.
But the problem is that when I need to edit the data with the form, the jQuery "change" function isn't triggered and the fields shown aren't selected with the dropdown (value of the dropdown is save too).
How can I achieve this? Maybe another jQuery function would be better?
This is my markup and code:
html:
<body>
<div class="div1">
<label class="label1">label1</label>
<select id="select">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="div2">
<label class="label2">label2</label>
<input type="text" name="input1" class="input1">
</div>
<div class="div3">
<label class="label3">label3</label>
<input type="text" name="input2" class="input2">
</div>
<div class="div4">
<label class="label4">label4</label>
<input type="text" name="input3" class="input3">
</div>
<div class="div5">
<label class="label5">label5</label>
<input type="text" name="input4" class="input4">
</div>
</body>
jQuery:
$(document).ready(function() {
$('.div2').hide();
$('.div3').hide();
$('.div4').hide();
$('.div5').hide();
$('#select').change(function () {
if ($('#select option:selected').text() == "option1"){
$('.div2').show();
$('.div3').hide();
$('.div4').hide();
$('.div5').show();
}
else if ($('#select option:selected').text() == "option2"){
$('.div2').hide();
$('.div3').show();
$('.div4').hide();
$('.div5').show();
}
else if ($('#select option:selected').text() == "option3"){
$('.div2').hide();
$('.div3').hide();
$('.div4').show();
$('.div5').show();
}
});
});
</script>
JSFiddle: http://jsfiddle.net/YNnCw/
If you are willing to use jQuery, I wrote a little script to do just that.
This is just a simple little function to show the data which matches the chosen option in the select with choose Option. First it hides all the option class items, then is shows the items with the class which equals the chosen option. The id is the class of all the options used for this instance. This allows you to have more than one of these on a page.
You can look at the example below.
The rows in the form show or don't show based on the classes. For example . The "optionName" in the div class is the same as the ID of the master selector, and thus gets hidden. If the selection value
is option3 then that div will show.
Option Type:
<select name="optionName" id="optionName" class="chooseOption">
<option value = "" >Select a Type</option>
<option value = "option1">option1</option>
<option value = "option2">option2</option>
<option value = "option3">option3</option>
</select>
<div class = "optionName option1"> option1 stuff</div>
<div class = "optionName option2"> option2 stuff</div>
<div class = "optionName option3"> option3 stuff</div>
<script type="text/javascript">
$(".optionName").hide();
$("document").ready(function() { /// have to wait till after the document loads to run these things
$("select.chooseOption").change(function(){
$("."+this.id).hide();
var thisValue = $(this).val();
if (thisValue != "")
$("."+thisValue).show();
});
});
</script>
You make a mistake it should be:
$('#select option:selected').text()
here the updated fiddle
I use this javascript to display different div classes upon selection. I need to display one div class if nothing is selected, for example when page is loaded, and that replace it with one of the divs according to the selection...
<script type="text/javascript"><!--
var lastDiv = "";
function showDiv(divName) {
// hide last div
if (lastDiv) {
document.getElementById(lastDiv).className = "hiddenDiv";
}
//if value of the box is not nothing and an object with that name exists, then change the class
if (divName && document.getElementById(divName)) {
document.getElementById(divName).className = "visibleDiv";
lastDiv = divName;
}
}
//-->
</script>
css:
<style type="text/css" media="screen"><!--
.hiddenDiv {
display: none;
}
.visibleDiv {
display: block;
border: 1px grey solid;
}
--></style>
HTML:
<form id="FormName" action="blah.php" method="get" name="FormName">
<select name="selectName" size="1" onChange="showDiv(this.value);">
<option value="">Choose One...</option>
<option value="one">first</option>
<option value="two">second</option>
<option value="three">third</option>
</select>
</form>
<p id="one" class="hiddenDiv">This is paragraph 1.</p>
<p id="two" class="hiddenDiv">This is paragraph 2.</p>
<p id="three" class="hiddenDiv">This is paragraph 3.</p>
Can anyone please help?
<select onChange="showDiv(this.value);">
The <select> element doesn't have a value attribute. The value is sitting in its <option> children. To get the value of the currently selected option of a <select> element you need the following:
var selected = dropdown.options[dropdown.selectedIndex].value;
So your onchange call needs to be altered as follows:
<select onchange="showDiv(this.options[this.selectedIndex].value);">
That said, the onchange attribute should be spelt all lowercase and a paragraph is not a div.
Assign id to select list
<select name="selectName" id="selectName" size="1" onChange="showDiv(this.value);">
call window.onload function
window.onload =function (){
showDiv(document.getElementById("selectName").value);
}