How to trigger select change with Materialize - javascript

On a normal select tag I'm able to trigger a change event with jQuery using $('select').val(2).change(). This does not work with Materialize select tags.
$(document).ready(function() {
$('select').formSelect();
$('button').on('click', function() {
//$('select').val(Math.floor(Math.random() * 3) + 1).change(); // Does not work
$('select').val(Math.floor(Math.random() * 3) + 1).formSelect();
});
});
.wrapper {
display: flex;
justify-content: space-around;
padding: 2rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<div class="wrapper">
<select>
<option value="">Selecione</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<button class="btn">Change</button>
</div>
I was able to make this work using $('select').val(2).formSelect() but I don't know if this is the correct way as this function is used to initialize the selects on Materialize and I haven't found documentation about it. Is this the "correct" way to achieve this or there are better solutions?
Thank you.

I think its the correct way, you will have to re-initialise the select element after changing its value
If you want to update the items inside the select, just rerun the initialization code from above after editing the original select. Or you can destroy the material select with this function below, and create a new select altogether Materializecss Docs
var select = $('select');
// initialize
select.formSelect();
$('button').on('click', function() {
// change
select.val(2);
// re-initialize material
select.formSelect();
});

var select = $("select#TeamListId");
// initialize
select.formSelect();
console.log(select);
$(select).on("change", function(e) {
teamNameId = $(this).val();
console.log("\n\nteamNameId", teamNameId);
myTable.search(teamNameId).draw();
});

Related

My plugin doesn't work with multiple selectors

Maybe it's something simple but I have a problem.
I created a plugin, but it only works well with a single selector, if I put several, that's where the problem comes from.
Although I use $(this) to select the current select, it ends up selecting all and replaces the value in all the selects where it finds them.
I leave my jsfiddle for review.
Look at the select # 1 and # 3.
$(document).ready(function() {
$("#sel1, #sel2, #sel3").SelectPopup();
});
See my jsfiddle
I'm not going to rewrite your plugin for you but will show you the basics of isloating the element instances within your plugin.
this inside the plugin function is a jQuery object that includes all of the matching elements from the selectors.
You want an internal each to loop over and isolate each of those element instances.
Following is a very crude plugin that just wraps each of the selects in a parent container and adds a change event listener to each instance. It is not very practical by itself but should give you the foundation to rebuild the one you are working on
$.fn.mySelect = function(options) {
// `this` is jQuery object that contains all elements in collection
// we return it so the plugin can be chained to other jQuery methods if needed
// also use `each` to isolate individual elements in the collection
return this.each(function() {
// `this` is instance of element in collection
var $currentSelect = $(this);
// wrap each element and add a change event listener
$currentSelect.wrap('<div class="select-wrapper">')
.change(function() {
console.log('Select id "' + this.id + '" changed')
});
});
}
$("#sel1, #sel2, #sel3").mySelect()
.select-wrapper {
display: inline-block;
border: 1px solid #ccc;
margin-right: 20px;
padding: 1em
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel1">
<option value="1">A1</option>
<option value="2">A2</option>
<option value="3">A3</option>
</select>
<select id="sel2">
<option value="10">B1</option>
<option value="20">B2</option>
<option value="30">B3</option>
</select>
<select id="sel3">
<option value="1">C1</option>
<option value="2">C2</option>
<option value="3">C3</option>
</select>

Trying to update the DOM with dropdown select

I want the content displayed to be manipulated by selecting a dropdown option. Here's what I have so far. It doesn't work.
HTML - here's an example of my dropdown.
<select id="dropdown">
<option value="Week1" id="Week1drop">Week 1 - Greetings, Common Adjectives & Planets</option>
</select>
The div below will be hidden by default using {display: none} in CSS.
<div id="week1">
<h1>Greetings, Common Adjectives & Planets</h1>
</div>
JavaScript - Below I've got an event listener to check for a change to the dropdown, which whill call the UpdateDom Function.
The function should be identifying that the user has selected Week1 on the dropdown and using Jquery .show() to make the Div visible.
document.getElementById("dropdown").addEventListener("change", updateDom);
function updateDOM () {
if (document.getElementById('dropdown').value == "Week1") {
$("#week1").show();
}
}
I hope this makes sense, does anyone know where I'm going wrong?
Apart from the typo you found yourself, if you have jQuery, USE it.
Also options do not have IDs
$("#dropdown").on("change", function() {
$("#week1").toggle(this.value == "Week1"); // same as $(this).val()
}).change(); // initialise on load
#week1 {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown">
<option value="">Please select</option>
<option value="Week1">Week 1 - Greetings, Common Adjectives & Planets</option>
</select>
<div id="week1">
<h1>Greetings, Common Adjectives & Planets</h1>
</div>

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>

Get value of jQuery chosen element

I'm trying to get value of jQuery Chosen element, but not getting anything. I think it could be because there is no value yet when I am searching for it, but not sure with that, because when the page loads, I can already see the value, which I need to get, on page. I've searched some threads here, but no solution worked for me. If anyone would know how to move with this, I would be so glad, thanks!
(I have to get value of <span> inside of <a class="chosen-single"> ) and it's not because I don't have included jQuery library. I have, but I haven't pasted it here.
FIDDLE: https://jsfiddle.net/camm8yLj/
<a class="chosen-single" tabindex="-1">
<span>I/37 Chrudim - obchvat, úsek křiž. I/17 - Slatiňany</span>
</a>
$(document).ready(function(){
$('.chosen-single').chosen().change(function () {
$(this).find('span').each(function(){
alert('Text : '+$(this).text());
alert('Value : '+$(this).val());
});
});
});
You can take the text using find method.
$('select').find('option:selected') retrieves you all the options which are selected.
$('select').chosen();
$('select').change(function(){
$(this).find('option:selected').each(function(){
alert('value:'+$(this).val()+' text: '+$(this).text());
});
});
$(document).ready(function() {
// Chosenify every multiple select DOM elements with class 'chosen'
$('select.chosen').chosen();
$('select.chosen').change(function(){
$(this).find('option:selected').each(function(){
alert('Value:'+$(this).val()+', Text: '+$(this).text());
});
});
});
* { font-family: arial; }
h1 { font-size: 1.5em; }
h2 { font-size: 1.3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.css" rel="stylesheet"/>
<h1>The Chosenified multiple <select></h1>
<p>
<select name="fruits" class="chosen" multiple style="width: 500px;">
<option value="banane">Banane</option>
<option value="pomme">Pomme</option>
<option value="poire">Poire</option>
<option value="ananas" selected>Ananas</option>
<option value="kiwi" selected>Kiwi</option>
<option value="goyave">Goyave</option>
<option value="abricot">Abricot</option>
<option value="fraise" selected>Fraise</option>
<option value="framboise">Framboise</option>
<option value="avocat" selected>Avocat</option>
</select>
</p>

Bootstrap breaks multiple children drowdown by main dropdown Javascript

I have done a bit of Jquery to change multiple children drowdown by main dropdown.
Image here
The issue I am having is as soon as I add the bootstrap styles "form-control select picker" it breaks as it converts the code to be in a different format.
The code for the Jquery to change multiple children drowdown by main dropdown is below. I would also like to add a save to save the relevant children when the relevant main dropdown has been selected:
<select class="search_top_options">
<option class="saleButton">property sales</option>
<option class="rentalButton">long lets</option>
</select>
$('.saleButton').click(function () {
$('.rentalSearch').hide();
$('.saleButton').removeClass("search_top_tab").addClass("search_top_tab_selected");
$('.rentalButton').removeClass("search_top_tab_selected").addClass("search_top_tab");
$('.saleSearch').fadeIn('fast');
});
$('.rentalButton').click(function () {
$('.saleSearch').hide();
$('.rentalButton').removeClass("search_top_tab").addClass("search_top_tab_selected");
$('.saleButton').removeClass("search_top_tab_selected").addClass("search_top_tab");
$('.rentalSearch').fadeIn('fast');
});
How can I do this? Code which is getting formatted by bootstrap sin below screenshot (won't let me attach it onto this ticket):
image here of broken bootstrap select code
The problem you are facing is, that the "click" event you are listening won't work on options.
In your case you can try to get the value of your select. The code provided is a little change to yours, but should give you a hint on how to solve your problem.
<select class="search_top_options">
<option disabled selected> -- select an option -- </option>
<option class="saleButton">property sales</option>
<option class="rentalButton">long lets</option>
</select>
<div class="saleSearch">
saleSearch content
</div>
<div class="rentalSearch">
rentalSearch content
</div>
$('.search_top_options').on('change', function() {
$(this).find('option:not(selected)').hide();
if ($(this).val() == 'property sales') {
$('.rentalSearch').hide();
$('.saleSearch').fadeIn();
} else if ($(this).val() == 'long lets') {
$('.saleSearch').hide();
$('.rentalSearch').fadeIn();
}
});
.rentalSearch {
display: none;
}
https://jsfiddle.net/tw0g5jeh/

Categories

Resources