jQuery: Showing a div if a specific a <select> option is selected? - javascript

I'm working on the address page for a shopping cart. There are 2 <select> boxes, one for Country, one for Region.
There are 6 standard countries available, or else the user has to select "Other Country". The <option> elements all have a numeric value - Other Country is 241. What I need to do is hide the Region <select> if the user selects Other Country, and also display a textarea.

You need to bind a function to the select list so that when it changes, your function decides if the div should be shown. Something like this (untested, hopefully syntactically close). Here's a live example.
$(document).ready( function() {
$('#YourSelectList').bind('change', function (e) {
if( $('#YourSelectList').val() == 241) {
$('#OtherDiv').show();
}
else{
$('#OtherDiv').hide();
}
});
});

It's the same principle as this question. You just need to connect to the change on the select , check the val() and hide()/show() the div.

In my opinion, you don't really need jQuery for this.
This simple JavaScript code will do the trick:
document.getElementById('country_id').onchange = function()
{
if (this.options[this.selectedIndex].value == 241) {
document.getElementById('region_id').style.display = 'block';
} else {
document.getElementById('region_id').style.display = 'none';
}
}
value works for most browsers, but yes, for older browsers you need select.options[select.selectedIndex].value. I updated my script.

Related

Filter as you type, search for name of Div ID

Any expert out there know if there is any search jquery plugin that allows you to filter as you type in the search box and the search is based on the name of Div ID?
Also if it will instant refresh filter it will be best.
Very broad question and not sure what you mean. The input is meant to actually search for a div itself? In any case, you could just use a few lines of jquery to search. I have included an example below.
https://jsfiddle.net/cshanno/m0pchv1j/1/
JQUERY
$('#search').keyup(function(){
var input = $(this).val();
$('div').each(function(i) {
if (input === $(this).attr('id')) {
$(this).addClass('show'); // run your code after you find the div
} else {
$(this).removeClass('show'); // else do whatever
}
});
});

detect select value with jquery if statement

I am trying to utilize the JQuery if statement to create a form that will allow employees to create a custom verbal script for their customers. Basically the JQuery Plugin will simply append input field values to a dialogue to be read by the employee to the customers.
I've had no issue with the JS written to append the contents of text-fields and select boxes to the dialogue but seem to be unable to figure out the most crucial part. I want to be able to show or hide information relevant to specific states based upon the value of a select box input field.
Below is a single example of my attempt at utilizing the if/else statement to do so.
HTML:
<select name="state_select" class="state_select">
<option value="CT">Connecticut</option>
</select>
<p class="ct_opt">Lorem Ipsum</p>
Css:
.ct_opt {
display:none;
}
JQuery:
$(document).ready(function(){
if ($("select.state_select").val() == "CT") {
$("ct_opt").show();
} else {
if ($("select.state_select").val() != "CT")
$("ct_opt").hide();
}
});
From what I understand, this should allow the targeted text to stay hidden unless its corresponding state is selected. However, it seems to do nothing at the current moment :(
Any suggestions would be greatly appreciated.
$(document).ready(function() {
$('.state_select').val('CT');
$('.state_select').on('change', function() {
console.log('click');
if($(this).val() == 'CT') {
$('.ct_opt').show();
}
else if ($(this).val() == 'noshow') {
$('.ct_opt').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="state_select" class="state_select">
<option value="CT">Connecticut</option>
<option value="noshow">Dont Show</option>
</select>
<p class="ct_opt">Lorem Ipsum</p>
$('select.state_select') will select an array of select objects with the class state_select. If you only have one state_select you should change this selector to $('#state_select'). There is no point in using $('select#state_select') (although valid) since there can only be a single id per page. You could use your current selector but you will need to call .first() to get the first item in the array of elements matching that selector.
Additionally as Ragnar pointed out there is no element named 'ct_opt' so you need to change your selector to $('.ct_opt') to target the class.
Use .ct_opt because it's a class and execute your code when selection changes:
$(document).ready(function(){
$("select.state_select").change(function(){
if ($(this).val() == "CT")
$(".ct_opt").show();
else $(".ct_opt").hide();
});
$("select.state_select").change(); //call change event when page loads
});
You can use $() because it's equivalent to document ready:
$(function(){
$("select.state_select").change(function(){
if ($(this).val() == "CT")
$(".ct_opt").show();
else $(".ct_opt").hide();
});
$("select.state_select").change(); //call change event when page loads
});

How To Select A Certain Option Field

Jquery is not my main language PHP is.
Anyway,
What I am trying to do is detect if a field has been selected my code almost works but the issue is that when it selects the certain option I get a alert which is good but then when I select the dropdown again [since its being selected] I get another alert which I don't want. What I do want is once the user select the dropdown then clicks the option again I want another alert
$('#_privacy_selection').click(function() {
if($("#_privacy_selection option:selected").text() == 'Certain Users'){
alert(9);
return false;
}
});
Thanks
Instead of click function use change function on <option>
It will be fired only when you change selected option.
$('#_privacy_selection').change(function() {
if($("#_privacy_selection option:selected").text() == 'Certain Users'){
alert(9);
return false;
}
});

How to abstract this single case (showing text field based on selection of a drop down list) into a general function in jQuery?

This is my first detailed question on SO.
Hi, so I have a form and have many instances where I want to show a text field after a drop down list when the user selects the "Other" option in the drop down list.
I am using a standard naming convention and am wondering, do I have to have as many functions as DDL/text field pairs in the document, or can I have a single function I can call on a class of DDLs? Here's the HTML:
<label for="spotter">Spotter:</label>
<select id="spotter" required>
<option value="Snoop Dogg">Snoop Dogg</option>
<option value="MC Escher">MC Escher</option>
<option value="Linus Thorvalds">Linus Thorvalds</option>
<option value="Other">Other</option>
</select>
<br/>
<div id="spotter_other_div"><label for="spotter_other">Other Spotter:</label><br><input type="text" name="spotter_other" id="spotter_other" size="50" required/></div>
and here's the jQuery/javascript:
$(document).ready(function(){
$("#spotter").change(function () {
//alert("You just changed the value of the #spotter drop down menu.");
if ($(this).val() == "Other" )
//alert("You just changed the value of the #spotter drop down menu to 'Other.'");
$("#spotter_other_div").css("visibility", "visible");
else
$("#spotter_other_div").css("visibility", "collapse");
});
});
The initial state of the div containing the text field is "collapse" in css.
I am learning jQuery and I'm at the point where I know how to do something for a general case, and I'd like to see if this is a function I can write, or if I have to do it explicitly.
Note that the page is a work in progress so any suggestions are welcome (e.g. use a span instead of a div to contain the text field, etc.
Thanks!
I see two options here.
Create a function and parametrize it out. This is what Sethen Maleno's answer shows.
Make your function a more general function.
For example:
$(document).ready(function(){
// Apply this to every select element
$("select").change(function () {
// Dynamically build up the selector to show/hide
var secondMenuId = '#' + $(this).attr(id) + '_other_div'
if ($(this).val() == "Other" )
$(secondMenuId).css("visibility", "visible");
else
$(secondMenuId).css("visibility", "collapse");
});
});
Note that this approach requires discipline when you generate your HTML, and that the ids are assigned appropriately (which you seem to be doing since you mention using a standard naming convention).
This approach has the advantage that this is the only code you would have, and you wouldn't need to write lots of handlers.
Sethen's gives you a little more flexibility in that your ids wouldn't need to follow strict conventions (you could pass whatever you wanted as arguments), but does require you to write a function call to attach it to every item you want.
Both techniques are valid and have their time and place.
You can just use a single function with some code and call it multiple times (or once if you're using the same id or class)... Hence the purpose of functions: Reusable bits of code. Here's what it might look like.
$(function () { //shorthand for ready in jQuery
//set up your function
function dropDownOther(spotter, spotterDiv) { //function takes two args
$(spotter).change(function () {
if ($(this).val() == "Other") {
$(spotterDiv).css("visibility", "visible");
} else {
$(spotterDiv).css("visibility", "collapse");
}
});
}
dropDownOther("#spotter", "#spotter_other_div"); //call your function
dropDownOther("#otherSelector", "#otherSelectorTwo"); //call it again if necessary
});

Manually selecting a multiple drop down option if value is matched in JQuery

I need to manually select a dropdown option if a value is matched. Here is the code:
if($("#hiddenMyField").val() != "") {
$("#dropdown").each(function(i){
$('option', this).each(function() {
if($(this).html() == $("#hiddenMyField").val()) {
// code to select the option
} else {
alert('not matched');
}
});
});
}
How can I select the current option located in the drop down if that if condition is met?
Thanks
Options have a selected property:
this.selected = true;
$(this).attr('selected', true);
should do the magic.
All right I managed to find a workaround for this.
Since the options were being translated to divs with checkboxes with the ui.dropdownchecklist.js I first loaded the multiple dropdown with its normal view, then selected the necessary items with the this.selected = true and then I loaded the ui.dropdownchecklist.js function so the items will be translated back to divs with checkboxes. The user doesn't even see the actual multiple checkboxes so this worked out well for me. When they are translated to checkboxes, the selected items are kept and are also ticked when they are transferred.

Categories

Resources