Hi I have HTML bootstrap code:
$(document).ready(function() {
$("#us-state").find('select').change(function() {
var $val = $(this).val();
if ($val === 'US') {
$('.us-state-select').show();
} else {
$('.us-state-select').hide();
}
});
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="col-sm mb-5 us-state-select">
<label>USA STATE</label>
<select name="order_from_address_state" class="form-select">
<option>Choose country</option>
<option value="AL" name="<AL>" selected>Alabama</option>
<option value="AK" name="AK">Arkansas</option>
</select>
</div>
<div class="col-sm mb-5" id="us-state"><label>Send from country</label>
<select name="order_from_address_country" class="form-select">
<option>Send from</option>
<option value="US" name="US">USA</option>
<option value="CA" name="CA" selected>Canada</option>
</select>
</div>
(Also available on JSFiddle)
My problem is simple.
I am using foreach to show all countries and statesm but...
check the jsfiddle.
if country is selected different to the US and its load with this different country, it shows div us-state-select and if u click on different countries, it dissapears and works as expected.
But I dont want to show div with states in the case that page is loaded and its selected different country than US. How to do that?
its obvious on fiddle, I selected canada and on page load there is div with states and when click on different value for example: Send from at country box, states dissapear and it works as expected then.
Please, can you give me some advice?
I am newbie at jquery, thx.
Change your JS to be like this:
I am basically checking this logic once the page is ready and I also added some refactor in your code to help readability
$(document).ready(function() {
const checkValues = () => {
var value = $("#us-state").find('select').val();
console.log(value)
if(value === 'US'){
$('.us-state-select').show();
}else{
$('.us-state-select').hide();
}
}
$("#us-state").ready(checkValues);
$("#us-state").find('select').change(checkValues);
});
Related
I have to incorporate a Healcode widget (through Mind Body) into the site I'm working on. My goal is to have a button on that page change the dropdown selection of the Healcode widget and reload the widget to reflect the dropdown change.
So far I've been able to create a button that changes the dropdown selection to the desired value when clicked. However it does not reload the widget to reflect the change. I still have to manually click the dropdown to make that happen.
Any help is appreciated!! Here's what I have so far:
HTML FOR THE HEALCODE DROPDOWN FILTERS:
<div class="filters">
<select name="mbo_class" id="mbo_class">
<option value="">All Classes</option><option value="58">200 hour Teacher Training</option>
<option value="3">Basics</option>
<option value="59">Basics/Power</option>
<option value="85">Basics/Restore + Meditation</option>
<option value="156">Cozy Winter YIN & Restore</option>
<option value="23">Deep Stretch/YIN</option>
<option value="154">Express Power</option>
<option value="140">HIIT Power Yoga</option>
<option value="12">Music & Power Yoga</option>
<option value="5">Power Yoga </option>
<option value="46">Power Yoga/Restore </option>
<option value="138">Simply Stretch</option>
<option value="30">Tween Yoga</option>
<option value="139">YOD (Yoga + HIIT)</option></select>
</div>
HTML & JS FOR BUTTON TO CHANGE THE SELECTION:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn3").click(function(){
$("#mbo_class").val("3");
});
});
</script>
<button id="btn3">Set Value</button>
I'm thinking a working solution might be somehow capturing what the dropdown is changed to and then reloading the page, but my attempts have not worked thus far. Here's my latest attempt:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn3").click(function(){
$("#mbo_class").val("3");
});
var selectedProduct = sessionStorage.getItem("product");
if(selectedProduct != undefined || selectedProduct != null){
$("mbo_class").first().find(":selected").removeAttr("selected");
$("mbo_class").find("option").each(function () {
if ($(this).val() == selectedProduct) {
$(this).attr("selected", true);
}
});
}
$('mbo_class').change(function () {
sessionStorage.setItem("product", $("mbo_class").first().val());
location.reload();
});
</script>
<button id="btn3">Set Value</button>
So I found a solution! It isn't quite the direction I was planning to go, but it works! Since I can't actually change the HTML of the widget–the research I was doing led me to a lot of dead ends.
In the HealCode widget app, I created a version of the schedule widget for each class type (the filter options mentioned above).
Then I set the button to change the entire div id to display the correlated schedule widget. (Rather than just filtering the current schedule widget.)
We'll use the example of filtering for the "Basics Class".
Here's my HTML code:
<div id="widget-container">
<healcode-widget data-type="schedules" data-widget-partner="object" data-widget-id="3c106917a43" data-widget-version="0">
</healcode-widget>
<a id="schedule-basics" class="button">Basics schedule</a>
Here's the script–which changes the schedule displayed to the "Basics Class" schedule (much like the filter selection would):
$(document).ready(function() {
var scheduleWidgetMarkup = '<healcode-widget data-type="schedules" data-widget-partner="object" data-widget-id="3c1218147a43" data-widget-version="1" ></healcode-widget>';
$('body').on('click', '#schedule-basics', function(e) {
e.preventDefault();
$('#widget-container').html(scheduleWidgetMarkup);
});
});
When I clone a bootstrap-select dropdown, the cloned dropdown seems to offset selections by 1. I.e., if I click the second option, the first one is selected.
For example:
If I click "New Castle" in the original dropdown, then "New Castle" is selected
If I click "New Castle" in the cloned dropdown, then "Kent" is selected
The error I get is:
bootstrap-select.js:2727 Uncaught TypeError: Cannot read property 'firstChild' of undefined
Why might this be happening?
A JSFiddle of the error is here: http://jsfiddle.net/jh4wztab/1/
Below is my code:
var count = 2;
$(document).on("click", "#clonejurisdiction", function() {
addselectpicker(count);
count++;
});
function addselectpicker(juriscount) {
juriscount = parseInt(juriscount)
var picker = $('#jurisdictionpicker');
var clone = picker.clone();
var pickercount = juriscount + 1;
clone.attr("id",'jurisdiction' + juriscount);
clone.find(".selectpicker").attr("id",'jurisdictionpicker' + juriscount);
clone.find("[data-id='jurisdiction_']").hide();
clone.appendTo(".juris_name");
clone.find('.selectpicker').selectpicker();
clone.find(":input").attr("placeholder", "Enter a State, County");
}
HTML
<div id="jurisdictionpicker">
<select class="selectpicker jurisdiction" data-live-search="true" data-size="8" title="Select County, State" id="jurisdiction_">
<optgroup label="Popular">
<option value='317'>Kent</option>
<option value='318'>New Castle</option>
<option value='1859'>New York</option>
</optgroup>
<optgroup label="Jurisdictions">
<option value='1'>Autauga</option>
<option value='2'>Baldwin</option>
<option value='3'>Barbour</option>
<option value='4'>Bibb</option>
</optgroup>
</select>
</div>
<button id="clonejurisdiction">
Clone
</button>
<BR><B>Cloned version:</B>
<div class="juris_name">
</div>
Your main problem is when trying to do var clone = picker.clone();, that code is not actually cloning your original HTML markup for your select element. When using Bootstrap and writing your HTML markup for a select element like <select class="selectpicker">, when you use the class selectpicker the bootstrap javascript transforms your original markup into bootstraps select markup using parts of your original HTML. Once the DOM is rendered, the select element you are interacting with in your browser is not code that you originally wrote at all, it is boostrap's transformation of your HTML. So when you trying to clone() the bootstrap select element and then calling selectpicker() on it, it was trying to force bootstrap to transform HTML that was not in a state that it expected it to be to transform it, and was causing your unexpected behavior.
One way to solve this problem is to make your original HTML markup reusable. An easy way to do this is templating. When doing this you can get your template and add whatever view data you need to it and then have bootstrap transform your template HTML on the fly using selectpicker()
Here is a modified version of you originally posted code using Mustache.js for templating purposes. This performs what you wanted without your original select picker bug:
Here is the updated JSFiddle.
javascript:
var count = 1;
$(document).ready(function() {
$("#someDiv").append(getJurisdictionPicker(count));
});
$(document).on("click", "#clonejurisdiction", function() {
var picker = getJurisdictionPicker(count);
$("#jurisName").append(picker);
});
function getJurisdictionPicker(juriscount) {
var template = $("#jurisdictionPickerTemplate").html();
var data = { counter : juriscount };
var templatedText = Mustache.render(template, data);
var temp = $(document.createElement("div")).html(templatedText);
temp.find(".selectpicker").selectpicker();
count++;
return temp;
}
HTML:
<script id="jurisdictionPickerTemplate" type="text/template">
<div id="jurisdictionpicker{{ counter }}">
<select class="selectpicker" data-live-search="true" data-size="8" title="Select County, State">
<optgroup label="Popular">
<option value='317'>Kent</option>
<option value='318'>New Castle</option>
<option value='1859'>New York</option>
</optgroup>
<optgroup label="Jurisdictions">
<option value='1'>Autauga</option>
<option value='2'>Baldwin</option>
<option value='3'>Barbour</option>
<option value='4'>Bibb</option>
</optgroup>
</select>
</div>
</script>
<div id="someDiv">
</div>
<button id="clonejurisdiction">
Clone
</button>
<BR><B>Cloned version:</B>
<div id="jurisName">
</div>
<BR><BR>
If I click "New Castle" in the original dropdown, then "New Castle" is selected<BR>
If I click "New Castle" in the <B>cloned</B> dropdown, then "Kent" is selected<BR>
I am using Select2 jQuery Plugin.
https://select2.github.io/ for reference
When I am using the multiple dropdown option. The result of selected items is shown as tags in a box but, I just want to show the number of items selected.
Is it possible with Select2 jQuery plugin
HTML
<select multiple style="width:100%">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
<option value="5">Name5</option>
<option value="6">Name6</option>
<option value="7">Name7</option>
</select>
JS
$('select').select2();
I want output as below
instead of tag like output.
Example working Fiddle
You can add this code after initializing select2
$('select').on('select2:close', function (evt) {
var uldiv = $(this).siblings('span.select2').find('ul')
var count = $(this).select2('data').length
if(count==0){
uldiv.html("")
}
else{
uldiv.html("<li>"+count+" items selected</li>")
}
Ref: jsfiddle
Reference to select2 events: Here
Edit: If you want to display a blank when user deselects everything,
Use this fiddle: here
Edit: Updated to remove flaw in deselection of data and changed it to main answer.
Fiddle: here
Selectors can certainly be improved, but as a blueprint, adding a counter element on change and hiding the tags like this seems to work as asked.
$('select').select2({closeOnSelect: false}).on("change", function(e) {
$('.select2-selection__rendered li:not(.select2-search--inline)').hide();
$('.counter').remove();
var counter = $(".select2-selection__choice").length;
$('.select2-selection__rendered').after('<div style="line-height: 28px; padding: 5px;" class="counter">'+counter+' selected</div>');
});
.counter{
position:absolute;
top:0px;
right:5px;
}
.select2-search--inline{
background-color:Gainsboro;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select multiple style="width:100%" id="mySelect">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
<option value="5">Name5</option>
<option value="6">Name6</option>
<option value="7">Name7</option>
</select>
although the answer is given.
you can try this code. first initialize than on close call it.
jQuery('.multi-select-pbwp').select2();
$('.multi-select-pbwp').on('select2:close', function() {
const $select = $(this);
const numSelected = $select.select2('data').length;
$select.next('span.select2').find('ul').html(function() {
return `<li class="class="select2-selection__choice">${numSelected} selected</li>`;
})
});
I'm working on a new website based on CodeIgniter. I'm trying to hide some elements to my form depending on an input value, but the field doesn't hide but stays disabled.
Here's the code I have :
HTML :
<div class="clearfix">
<label for="form-timezone" class="form-label">Filters<small>Options</small></label>
<div class="form-input">
<?php
echo form_dropdown('filter', $filters,'', 'id="form-timezone"');
echo form_dropdown('city', $cities, '', 'id="city"');
echo form_dropdown('country', $countries, '', 'id="country"');
?>
</div>
</div>
Which basically gives something like :
<div class="clearfix">
<div class="form-input">
<select name="filter" id="form-timezone">
<option value="city">City</option>
<option value="country">Country</option>
</select>
<select name="cities" id="city">
<option value="Paris">Paris</option>
<option value="London">London</option>
</select>
<select name="countries" id="country">
<option value="fr">France</option>
<option value="en">England</option>
</select>
</div>
</div>
JS :
$(function() {
$("#city").hide();
$("#country").hide();
$("#form-timezone").change(function() {
if ( $("#form-timezone").val() == "city"){
$("#city").show();
$("#country").hide();
}
else if ( $("#form-timezone").val() == "country"){
$("#city").hide();
$("#country").show();
}
});
});
I tried to add an <input> field to my html, and to hide it in the js, and it worked well. I don't know why, but it seems that only the form_dropdown doesn't hide...
Do someone has an idea of what I'm doing wrong please ?
Thanks.
I don't know what you mean by not working. But your code can be a lot simpler with no if statements.
$("#form-timezone").change(function() {
var el = $('#' + $(this).val()); // <-- store matched element
el.show(); // <-- show matched element
$("#country,#city").not(el).hide(); // <-- hide unmatched element
});
And they work fine in this fiddle (they hide and not disable) - tested in Firefox/Chrome/IE9
http://jsfiddle.net/5LNWr/1/
It works for me in this fiddle.
The Javascript code you posted was missing a closing }); after the DOM ready handler. I've assumed the output is a <select> element for each PHP echo statement.
You mention that the form field "stays disabled." Does this mean they're disabled to begin with? Disabled form elements don't capture events in all browsers (Firefox).
If that isn't the case, can you provide a jsfiddle?
<div class="clearfix">
<div class="form-input">
<select name="filter" id="form-timezone">
<option value="city">City</option>
<option value="country">Country</option>
</select>
<!-- Here a select foreach city and country -->
</div>
</div>
See how there is no id's for City and Country? You cannot select on ID's here.
$("#city").show();
$("#country").hide();
Won't work. Maybe try
var $firstOption= $(“#form-timezone option:first”)
UPDATE: The original question asked was answered. However, the code revealed for all. So, I've modified my question below:
So I have the following dynamically generated html via php
<div class="image-link link-posttypes mainSelector1">
<select id="wp_accordion_images[20110630022615][post_type]" name="wp_accordion_images[20110630022615][post_type]">
<option value="">default</option>
<option value="post" class="post-type">Post</option><option value="page" class="post-type">Page</option><option value="dp_menu_items" class="post-type">Menu Items</option>
<option value="wps_employees" class="post-type">Employees</option><option value="custom-link">Custom Link</option>
</select>
</div>
<div class="image-link link-pages1">
<select id="wp_accordion_images[20110630022615][page_id]" name="wp_accordion_images[20110630022615][page_id]">
<option value="50" class="level-0">About</option>
<option value="65" class="level-0">Contact</option>
<option value="2" class="level-0">Sample Page</option>
<option value="60" class="level-0">Staff</option>
</select>
</div>
<div class="image-link link-posts1">
<select onchange="javascript:dropdown_post_js(this)" id="wp_accordion_images[20110630022615][post_id]" name="wp_accordion_images[20110630022615][post_id]">
<option value="http://localhost/tomatopie/?p=1" class="level-0">Hello world!</option>
</select>
</div>
<div class="image-link link-custom1">
<input type="text" size="25" value="" name="wp_accordion_images[20110630022615][image_links_to]">
</div>
***THEN IT REPEATS four times: where the #1 goes to 2..3...4 (max to 4 at this time).
I have the ability to label div .classes, select #ids, and option classes. However, what I want to be able to do is based on the option selected from div .link-posttypes, I want to reveal .link-pages (if page is selected) or .link-posts (if post is selected) and .link-custom for all others (except the default).
So as written on the screen there should only be the initial div, and once the user selects an item, the appropriate div appears.
I have never developed anything in jQuery or javascript. This is my maiden voyage. Any help will be greatly appreciated!
***Also, this will be loaded via an external js file.
Here is the final answer that worked:
jQuery(document).ready(function($) {
$(".link-posttypes select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="post"){
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").slideDown('slow');
$(this).parent().nextAll(".link-custom").hide();
}else if(selectedVal=="page"){
$(this).parent().nextAll(".link-pages").slideDown('slow');
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().nextAll(".link-custom").hide();
}else if(selectedVal!=""){
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().next().nextAll(".link-custom").slideDown('slow');
}else{
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().nextAll(".link-custom").hide();
}
});
});
jQuery(document).ready(function($) {
$(".image-content select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="content-limit"){
$(this).parent().next().nextAll(".content-limit-chars").slideDown('slow');
$(this).parent().nextAll(".content-custom").hide();
}else if(selectedVal=="custom-content"){
$(this).parent().nextAll(".content-limit-chars").hide();
$(this).parent().next().nextAll(".content-custom").slideDown('slow');
}
});
});
Thanks for your help!
Assuming that you're outputting proper IDs, you can do something like this (note I replaced the id):
$(window).load(function(){
// hide all the divs except the posttypes
$('.image-link').not('.link-posttypes').hide();
$('#wp_accordion_images_20110630022615_post_type').change(function() {
var divSelector = '.link-' + $(this).val();
$('.image-link').not('.link-posttypes').hide();
$(divSelector).show();
});
});
Also, consider changing your options like this:
<option value="posts" class="post-type">Post</option>
<option value="pages" class="post-type">Page</option>
<option value="menu_items" class="post-type">Menu Items</option>
<option value="wps_employees" class="post-type">Employees</option>
<option value="custom">Custom Link</option>
Here's a jsfiddle for this: http://jsfiddle.net/JrPeR/
There's my understandable jquery script
jQuery(document).ready(function($) {
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").hide();
$(".link-posttypes select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="post"){
$(".link-pages").hide();
$(".link-posts").show();
$(".link-custom").hide();
}else if(selectedVal=="page"){
$(".link-pages").show();
$(".link-posts").hide();
$(".link-custom").hide();
}else if(selectedVal!=""){
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").show();
}else{
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").hide();
}
});
});
Demo here. Take me couple minute to make you easy to understand. Have fun.
http://jsfiddle.net/JrPeR/3/
added a conditional so if its not the two variables it defaults to the custom.