How to reset dropdown box in jquery (select2)? - javascript

I have the following code:
https://jsfiddle.net/rmxpq2z0/
<div class="swiper-pagination"></div>
<div id="quote-form" class="quote-form">
<div class="container">
<div class="range range-xs-center range-lg-right">
<div class="cell-xs-10 cell-sm-8 cell-lg-5 text-left offset-top-0">
<div class="inset-lg-left-70">
<div class="quote-form-body">
<div>
<h3 class="text-bold">Get a FREE Quote!</h3>
</div>
<div class="offset-top-25">
<p>Please select your repair from the drop down boxes for an instant quote.</p>
</div>
<div class="offset-top-20">
<div class="form-group">
<select data-minimum-results-for-search="Infinity" class="form-control select-filter" id="console">
<option value="selectconsole">Select My Console</option>
<option value="ps4">PS4</option>
<option value="xboxone">Xbox One</option>
</select>
</div>
<div class="form-group">
<select data-minimum-results-for-search="Infinity" class="form-control select-filter" id="model">
</select>
</div>
Get My Quote
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
ps4models = new Array("Select My Model", "PS4 (Release Model)", "PS4 Slim", "PS4 Pro");
xboxonemodels = new Array("Select My Model", "Xbox One (Release Model)", "Xbox One Slim", "Xbox One Scorpio");
populateSelect();
$(function() {
$('#console').change(function() {
populateSelect();
});
});
function populateSelect() {
console = $('#console').val();
$('#model').empty();
$('#model').html('');
if (console == 'ps4') {
ps4models.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
$('#model').trigger("chosen:updated");
$('#model').find('option:first').attr('selected', 'selected');
});
}
if (console == 'xboxone') {
xboxonemodels.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
$('#model').trigger("chosen:updated");
$('#model').find('option:first').attr('selected', 'selected');
});
}
</script>
It works perfectly in the jsfiddle, but when I post the code to the website, it doesn't work.
It DOES populate the dropdown box, but it won't auto select the first option in the second box, and it won't remove any previous option that was selected.
For example, if I select an option in the first box, the second box stays empty until I select something. The first option should be auto selected. Also if I select something in the second box, and then change the selection in the first box, the second box option stays there, instead of being reset.
It is the EXACT same code, no changes at all. Is it possible the CSS is interfering with it?
Any help would be greatly appreciated.
UPDATE
Thanks to DanielH! It turns out the template was using Select2 jquery plugin. His code worked perfectly.

Solution 1:
Since you are using select2, add $('#model').change(); at the end of your console dropdown's select2 config should trigger the update every time you update the model dropdown list.
Solution 2:
If you have no control over the select2 or not sure where to find it, the following also gonna work, add a onchange event to the parent dropdown console:
$( document ).ready(function() {
$('#console').on('change', function(){
$('#model').val('selectmodel');
$('#model').change();
})
});

Related

jQuery show/hide div based on select option

So I know this has been asked a bunch and I've cycled through several posts and have done, it seems, exactly what has been said, but can't get it to work. You can see my page here.
Essentially I want to show a div and make its inputs/selects required (once shown; if hidden, they are not required). Obviously the div should show/hide depending on the selection.
$('#table-meals, .product-addon-please-choose-your-meal').hide();
$('#purchase').change(function(){
if($(this).val()=="Individual") {
$('#table-meals').show();
$('select').prop('required',true);
}
if($(this).val()=="Table of 10") {
$('.product-addon-please-choose-your-meal').show();
$('input').prop('required',true);
}
});
I figured it out, instead of using $('#purchase').change(function(){ I need to use $('form').on('change', '#purchase', function(){
The following code does work for me on your test page.
It looks like you had the individual/table of 10 elements mixed up.
// Using jQuery instead of $ because it looks like there's some sort of conflict on the site
jQuery('#purchase').change(function(){
// Reset required fields and hide fields
jQuery('select, input').prop('required', false);
jQuery('#table-meals, .product-addon-please-choose-your-meal').hide();
if(jQuery(this).val() == "Individual") {
jQuery('.product-addon-please-choose-your-meal').show();
jQuery('input').prop('required', true);
}
if(jQuery(this).val() == "Table of 10") {
jQuery('#table-meals').show();
jQuery('select').prop('required', true);
}
});
Based on dropdown list selection
jQuery(function () {
$("select").change(function () {
$(this).find("option:selected").each(function () {
window.onunload = unloadPage;
function unloadPage(){
$('#dropdown').find('option:first').attr('selected', 'selected');
}
if ($(this).attr("value") == "user") {
$(".box").not(".user").hide();
$(".user").fadeIn(3000);
}
else if ($(this).attr("value") == "group") {
$(".box").not(".group").hide();
$(".group").fadeIn(3000);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="col-sm-12" >
<select class="selectpicker" id="dropdown">
<option value="default" selected="selected">Select Module..</option>
<option value="group">Group Management</option>
<option value="user">User Management</option>
</select>
</div>
<div class="group box" style="display:none">
<h4>Group Management</h4>
<p>Div 2.</p>
</div>
<div class="user box" style="display:none">
<h4>User Management</h4>
</div>

how to get currently selected values from material_select() with jquery

The latest version of materialize has a nice looking multi-select implementation with checkboxes next to the options that are currently selected. But once an item has been selected, I don't seem to be able to un-select it again. The visible check mark goes away, but jquery still thinks it's selected. Here's the short example below (it doesn't look like materialize0.97.2's material_select works at all in jsfiddle, sorry). Once you show one of the two divs, you can't hide it again.
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.2/css/materialize.min.css">
</head>
<body>
<div class="container">
<div class="row">
<form>
<div class="input-field col s3" style="margin-left: 50px">
<select multiple id="column-selector">
<option value="" selected disabled>your choice</option>
<option value="first">first</option>
<option value="second">second</option>
</select>
</div>
</form>
</div>
<div class="row col s1">
<div class="first hide">first</div>
<div class="second hide">second</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.2/js/materialize.min.js"></script>
<script>
$(document).ready(function() {
/* this activates the "which columns to display" selectbox */
$('#column-selector').on('change',function() {
var selectedList = $(this).val();
var currentlySelected = {};
for (i in selectedList){
var colName = selectedList[i];
currentlySelected[colName] = true;
}
var colNames = [ "first", "second" ];
for (var i in colNames){
colname = colNames[i];
if (currentlySelected[colname]){
console.log('showing ' + colname);
$( '.' + colname).removeClass('hide');
}else{
console.log('hiding ' + colname);
$( '.' + colname).addClass('hide');
}
}
});
$('#column-selector').material_select();
});
</script>
</body>
</html>
Is there a better/more correct/working way to get the currently selected values of the material_select selectbox?
I did this, but it's not necessarily the best way.
Updating/Destroying Select
$('select').material_select('destroy');
Reinitialization
$('select').material_select();
Hopefully this helps ;)

Hide/show div section - select option

Thanks to this post I've achieved to hide a dropdown menu when a value from a selectfield it's selectd:
$(function () {
var selectField = $('#id_type_contract'),
verified = $('#id_mod_contracts');
function toggleVerified(value) {
value == 'Modification' ? verified.show() : verified.hide();
}
// show/hide on load based on pervious value of selectField
toggleVerified(selectField.val());
// show/hide on change
selectField.change(function() {
toggleVerified($(this).val());
});
});
})(django.jQuery);
But it doesn't work as I wanted: Image , because still remains its label and 'Add' button (green cross). So, I think the best way to proceed is to hide the entire div, am I right?
html
<div class="form-row field-mod_contracts">
<div>
<label for="id_mod_contracts">Modification:</label>
<select id="id_mod_contracts" name="mod_contracts" style="display: none;">
<option value="" selected="selected">---------</option>
<option value="4">Contract foo</option>
<option value="7">Contrato bar</option>
<option value="8">contract CCCC</option>
</select> <img src="/static/admin/img/icon_addlink.gif" width="10" height="10" alt="Add another">
</div>
</div>
How could I adapt the above JavaScript function? Is there any other better option?
Either do as #Aumo suggest, unless you have the class field-mod_contracts on more elements (then it would hide them all).
If so you can instead use:
verified = $('#id_mod_contracts').parent();
This will select the inner most div
or:
verified = $('#id_mod_contracts').closest('.field-mod_contracts');
This will select the outer most div
Two hide the whole input section, change:
verified = $('#id_mod_contracts');
to
verified = $('.field-mod_contracts');

jQuery how to dynamically add select element and reset choice?

I am writing a dynamic form in the Play Framework, but I'm not very experienced with javascript. I'm trying to build off of this jQuery example that allows the dynamic addition of fields. Instead of adding only a text field, I want to add a text field and a select box each time. The tricky part is that even if there is a selected item, I want the dynamically added select box to be reset.
Here is my attempt to do this, using this answer
$('.multi-field-wrapper').each(function() {
var $wrapper=$('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
var obj=$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
// This following line is incorrect...
obj.find('.blank').prop('selected', true).end().trigger('chosen:updated');
}
);
$('.multi-field .remove-field',
$wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1) $(this).parent('.multi-field').remove();
}
);
}
);
<form role="form" action="/wohoo" method="POST">
<label>Stuff</label>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<div>
<input type="text" name="stuff[]"/>
</div>
<div>
<select>
<option class="blank" value="">Select a car</option>
<option value="saab">Saab</option>
<option value="mercedes" selected>Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
<button type="button" class="remove-field">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
Since it uses the clone() function, if "Mercedes" is selected, then dynamically added select dropdowns will also have "Mercedes" selected. How can I make the new selects display the blank choice?
Thanks!
EDIT - updated my code to reflect the fact that my input and select tags are encapsulated by divs
The "obj" variable becomes the input node selected in the end of this expression:
var obj = $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
But you should do the trick with select node, in your case it is "obj"`s sibling.
obj.siblings('select').find('.blank').prop('selected', true).end().trigger('chosen:updated');});
http://jsfiddle.net/xogeufa2/1/
Also, if "input" and "select" nodes are enveloped in div tags, they loose their sibling relations. So in this case, you should find another way, to get the "select". For example, through parents:
obj.closest('.multi-field').find('select').find('.blank').prop('selected', true).end().trigger('chosen:updated');
});
http://jsfiddle.net/2ymd7ug7/2/
You just needs to remove the attribute selected from the option tag.
For that you can use removeAttr method
Here is the complete code that does what you described.
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
var obj = $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').end().find('option').removeAttr('selected').focus();
});
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});
Just added .end().find('option').removeAttr('selected') to your code :)
I hope I helped..
Find the code here : https://jsfiddle.net/yrchyndk/

Onchange inside onchange jquery

Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});

Categories