I have an array of Bootstrap Selectpickers for filtering results from a database. I need a way of resetting all the selectpickers to 'Nothing Selected', this is my code:
HTML
<div class="row">
<div class="col-md-3">
<label>By Group</label>
<select id="groups" name="group" class="form-control selectpicker" multiple></select>
</div>
<div class="col-md-3">
etc...
</div>
</div>
JS
ajax_fetch('build_group_options', {groupno:groupno}).done(function(html) {
//var html is a list of options in html format
$('#groups').html(html).find('option[value=""]').remove();
//refresh the selectpicker to make sure options are registered in the picker
$('.selectpicker').selectpicker('refresh');
});
Try to reset all the pickers:
$('#reset_filters').click(function() {
$('.selectpicker').selectpicker('deselectAll');
$('.selectpicker').selectpicker('render');
$('.selectpicker').selectpicker('refresh');
$(this).closest('form').find('.selectpicker').each(function() {
$(this).selectpicker('render');
});
});
As you can see I have tried all the functions to reset but to no avail so am obviously doing some wrong further up the logic.
I got solution from following code.Try it
$("#listID").val('').trigger('change');
And also you can try this
$("#listID").val('').selectpicker('refresh');
Maybe it's a little late, but maybe it'll help someone someday. For me the solution was this:
$("#listID").val([]).selectpicker('refresh');
I had the multiselect option and with this you replace your chosen items for an empty array, otherwise you'll choose the option where the value is empty val('').
So I looked in the selectpicker.js file, the deselectAll and selectAll functions both filter their respective options by a few arguments (see line 884):
deselectAll: function () {
this.findLis();
this.$lis.not('.divider').not('.disabled').filter('.selected').filter(':visible').find('a').click();
}
A little breakdown:
.not('.divider') //prevents the divider receiving a click event!
.not('.disabled') //ignore any disabled elements
.filter('.selected') / .not('.selected') //depending if its selectAll() or deselectAll()
.filter(':visible') //prevent any non-visible element receiving a click event!?
My problem was the .filter(':visible'), the list was not visible when the click event was triggered so these options were filtered out and therefore did not get 'clicked'/'deselected'.
I amended my version of the plugin and now my 'reset' button works as expected. The new line is:
this.$lis.not('.divider').not('.disabled').filter('.selected').find('a').click();
Related
We have a bootstrap select (Phasentyp) that is added dynamically via a template.
The template looks like this:
<div class="form-group">
<div class="form-row">
<div class="col-4">
<form-group asp-for="#projektphaseTemplate.PhasenTypId" asp-horizontal="true" asp-label-suffix=" *" data-none-selected-text required></form-group>
</div>
</div>
</div>
When adding the template, the select is processed via JavaScript:
// Process the bootstrap selects
projektphase.find('select').each(function(index, element) {
const el = $(element);
// Replace name
let newName = el.attr('name').replace(/projektphaseTemplate/, `Projekt.PPMProjektPhase[${newIndex}]`);
el.attr('name', newName);
// Replace ID
let newId = $(element).attr('id').replace(/projektphaseTemplate/, `Projekt_PPMProjektPhase_${newIndex}_`);
el.attr('id', newId);
// Remove all bootstrap-select DOM Stuff for prune select-elements
el.closest('.bootstrap-select').replaceWith($(element));
// Reinitialize bootstrap-select
el.selectpicker({
noneSelectedText: ''
});
});
But unfortunately, when saving with the empty option selected, the validation doesn't work.
What is "funny" is, that when I fill out the other required fields and save again, then the validation seems to trigger but with the wrong message:
The HTML looks like this:
What am I doing wrong, that the validation isn't triggered by the first save?
Thanks in advance
You have to reapply jquery's validation to your element, after you changed the name of it.
See here: jQuery - How to dynamically add a validation rule
I have a div which shows result of a quotation form. Results changes if user change form value instantly. I want to display or copy the same results of that div to another div or more like a "second version" of that div.I know this below sort of code will work.
$("div1").clone().appendTo("div2");
But it works only for the 1st time page loads. After that it doesn't change the results with the div1 results.
Does anyone have a hint on what to do here?
Many thanks in advance!
Use the onchange event in your html on the form. Then call your code from it somewhat like:
onchange="$('div1').clone().appendTo('div2');"
or
onchange="someJSfuncion();"
also dont forget to delete the old copy. Further information:
https://www.w3schools.com/jsref/event_onchange.asp
You need to setup your event handlers on form changes and then copy the output to other div. Example:
// Original js
(function() {
$('.inp_name').on('change', function() {
$('.original-output .name_text').text($(this).val());
});
})();
// Your js
(function() {
var version = 0;
$('.inp_name').on('change', function() {
version++;
// Don't use clone as your events starts working in cloned code also which you don't expect
//$('.original-output').clone().appendTo('.copied-output');
$('.copied-output').append($('.original-output').html());
$('.copied-output').append(`<div>Version: ${version}</div>`);
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: Focus out see text getting change.
<div class="original-form">
Enter text here: <input type="text" class="inp_name" placeholder="enter your name" />
</div>
<div class="original-output">
Entered name: <span class="name_text">Entered Name</span>
</div>
<div class="copied-output">
</div>
I have been stuck on this problem for hours and I am going mad ! I need a dropdown of checkboxes - which I populate dynamically into a select tag. I also need to append each multiselect dropdown that I deep-clone with jquery to a number of <div> elements. However, every time I do this the cloned element is rendered as a list of multiselectable items (and not as a dropdown and loses all its styling). This is the multiselect container that I would like to add my checkboxes to:
<select class="multiselect1" multiple="multiple">
</select>
I finally initialize each cloned dropdown by calling .multiselect(); The library I am using for this is: http://davidstutz.github.io/bootstrap-multiselect/
$('.multiselect1').multiselect();
var filterClone = $('.multiselect1').clone(true);
//filterClone.multiselect();
$('body').append(filterClone[0]);
When the above lines execute, the select element is indeed present in the body but is invisible. When I remove the style attribute the element becomes visible but is rendered as a list of multiselectable items (which is expected). But why is the cloned multiselectable dropdown not displayed at all in the first place ?
Any suggestions that could lead me to a solution (or the solutions itself!) using javascript or jquery would be most appreciated.
Well to make this work you need JQuery. Did you include JQuery? If you didn't you can use this: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> Did you upload all the files to your server?
Try this code on your website. Does it work?
HTML:
<select id="SOExample" multiple="multiple">
<option value="Love it!">Love it!</option>
<option value="Hate it!">Hate it!</option>
<option value="I don't know...">I don't know...</option>
</select>
JS:
<script type="text/javascript">
$(document).ready(function() {
$('#SOExample').multiselect();
});
</script>
I'm starting with AngularJS, and I'm building a multi-step form where user has to fill different pages. When finished a page, he's allowed to press a next button and fill the following page.
For the first page, I've built in the HMTL a form (named pageOneForm), with different text input fields, marked as required, and in the relative controller I'm doing this watch:
$scope.$watch('pageOneForm.$valid', function(validity) {
ModelData.actualPageCompleted = validity;
})
And it works like a charme. My model (ModelData) is updated.
I was trying to apply the same logic to the following part of the app, the second page. Instead of input text, the user has to select two options from 2 different radio buttons groups.
So I built in the html a list of buttons via ng-repeat :
<div ng-Controller="PageTwo" ng-show='data.actualPage == 2'>
<form name="pageTwoForm">
<h3>General Information > Knowledge About </h3>
<div>
<b>User</b>
<div ng-repeat="option in userOptions">
<input type="radio" name="userGroups" ng-model="data.knowledgeAboutUser" ng-value="option.id" id="{{option.id}}" required>{{option.text}}
</div>
<div ng-repeat="option in targetGroupUserOptions">
<input type="radio" name = "targetUserGroup" ng-model="data.knowledgeAboutTargetGroup" ng-value="option.id" id="{{option.id}}" required>{{option.text}}
</div>
</div>
</form>
and I've implemented the same code as above in its controller:
$scope.$watch('pageTwoForm.$valid', function(validity) {
ModelData.actualPageCompleted = validity;
})
but apparently it doesn't work, and in my model actualPageCompleted is always true...
What am I doing wrong?
Thanks
I did my best to create a controller with some dummy data to get a fiddle working with your example code. Here is the fiddle You need to force the $digest cycle to update your form's validity state on ng-click for the radio buttons (see this SO post for more details), which is why the method
$scope.forceDigest = function(){
setTimeout(function(){ $rootScope.$$phase || $rootScope.$apply(); });
};
is necessary. Alternatively, you can get rid of the method call and uncomment the html code
<h3 ng-show="false">{{data.knowledgeAboutTargetGroup}}</h3>
<h3 ng-show="false">{{data.knowledgeAboutUser}}</h3>
in the fiddle to force the form object to update as well.
And I would make sure that ModelData.actualPageCompleted is not retaining its true value from when pageOneForm.$valid became true and it was set.
I hope that this helps!
This is a bit of a long question so please bear with me guys.
I needed to make a form submit automatically when a checkbox was ticked. So far I have the code below and it works perfectly. The form must submit when the check box is either checked or unchecked. There is some PHP that reads a database entry and shows the appropriate status (checked or unchecked) on load.
<form method="post" id="edituser" class="user-forms" action="--some php here--">
<input class="lesson" value="l101" name="flesson" type="checkbox" />
</form>
<script>
$('.lesson').change(function() {
$('.user-forms').submit();
});
</script>
However, when I introduce a fancy checkbox script which turns checkboxes into sliders it no longer works. The checkbox jQuery script is below:
<script src="'.get_bloginfo('stylesheet_directory').'/jquery/checkboxes.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("input[type=checkbox]").tzCheckbox({labels:["Enable","Disable"]});
});
</script>
The contents of the checkboxes.js called to above is as follows:
(function($){
$.fn.tzCheckbox = function(options){
// Default On / Off labels:
options = $.extend({
labels : ['ON','OFF']
},options);
return this.each(function(){
var originalCheckBox = $(this),
labels = [];
// Checking for the data-on / data-off HTML5 data attributes:
if(originalCheckBox.data('on')){
labels[0] = originalCheckBox.data('on');
labels[1] = originalCheckBox.data('off');
}
else labels = options.labels;
// Creating the new checkbox markup:
var checkBox = $('<span>',{
className : 'tzCheckBox '+(this.checked?'checked':''),
html: '<span class="tzCBContent">'+labels[this.checked?0:1]+
'</span><span class="tzCBPart"></span>'
});
// Inserting the new checkbox, and hiding the original:
checkBox.insertAfter(originalCheckBox.hide());
checkBox.click(function(){
checkBox.toggleClass('checked');
var isChecked = checkBox.hasClass('checked');
// Synchronizing the original checkbox:
originalCheckBox.attr('checked',isChecked);
checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
});
// Listening for changes on the original and affecting the new one:
originalCheckBox.bind('change',function(){
checkBox.click();
});
});
};
})(jQuery);
There is also some CSS that accompanies this script but I am leaving it out as it is not important.
Finally, this is what the jQuery script does to the checkbox:
<input id="on_off_on" class="lesson" value="lesson11-1" name="forexadvanced[]" type="checkbox" style="display: none; ">
<span classname="tzCheckBox checked" class=""><span class="tzCBContent">Disable</span><span class="tzCBPart"></span></span>
When the checkboxes are changed into sliders the .change() function no longer detects the change in the checkboxes status.
How can I make the .change() function work or is their an alternative function I can use?
This plugin changes your checkboxes to span elements and hides the actual checkboxes themselves. Thus, when you click on them, nothing happens. Since span elements don't have onchange events, you can't bind change events to these.
However, span elements do have click events, meaning that you could instead bind a click event to the generated spans, using Firebug or Chrome Debugger to locate the correct element to bind to.
Your click-handler can then take the same action your change event would normally take if the plugin weren't being used.
Here is an example:
HTML (Source):
<!-- This is a checkbox BEFORE running the code that transforms the checkboxes
into sliders -->
<li>
<label for="pelda1">OpciĆ³ 1:</label>
<input class="pelda" type="checkbox" id="pelda1" name="pelda1" />
</li>
HTML (Generated From Chrome Debugger):
NOTE: This is the generated HTML after running the JavaScript that converts checkboxes to sliders! You must bind your click event AFTER this code is generated.
<li>
<label for="pelda1">Option 1:</label>
<!-- The hidden checkbox -->
<input class="pelda" type="checkbox" id="pelda1" name="pelda1" style="display: none; " />
<!-- the "checked" class on the span gets changed when you toggle the slider
if it's there, then it's checked. This is what you're users are actually
changing.
-->
<span class="tzCheckBox checked">
<span class="tzCBContent">active</span>
<span class="tzCBPart"></span>
</span>
</li>
JavaScript:
NOTE: This must be bound AFTER converting the checkboxes to sliders. If you try it before, the HTML won't yet exist in the DOM!
$('.tzCheckBox').click(function() {
// alert the value of the hidden checkbox
alert( $('#pelda1').attr("checked") );
// submit your form here
});
Listen for change like this:
$('.lesson').bind("tzCheckboxChange",function() {
$('.user-forms').submit();
});
Modify the plugin by adding the line:
$(originalCheckBox).trigger("tzCheckboxChange");
after
checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
This way, anytime you use this plugin, you can listen for tzCheckboxChange instead of just change. I don't really know what's going on with the plugin, but seems kinda funky for it to be listening for a change event when it would only be fired through trigger (unless it doesn't hide the original checkbox).