Resetting Select2 value in dropdown with reset button - javascript

What would be the best way to reset the selected item to default? I'm using Select2 library and when using a normal button type="reset", the value in the dropdown doesn't reset.
So when I press my button I want "All" to be shown again.
jQuery
$("#d").select2();
html
<select id="d" name="d">
<option selected disabled>All</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

I'd try something like this:
$(function(){
$("#searchclear").click(function(){
$("#d").select2('val', 'All');
});
});

You can also reset select2 value using
$(function() {
$('#d').select2('data', null)
})
alternately you can pass 'allowClear': true when calling select2 and it will have an X button to reset its value.

version 4.0
$('#d').val('').trigger('change');
This is the correct solution from now on according to deprecated message thrown in debug mode:
"The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead"

According to the latest version (select2 3.4.5) documented here, it would be as simple as:
$("#my_select").select2("val", "");

you can used:
$("#d").val(null).trigger("change");
It's very simple and work right!
If use with reset button:
$('#btnReset').click(function() {
$("#d").val(null).trigger("change");
});

The best way of doing it is:
$('#e1.select2-offscreen').empty(); //#e1 : select 2 ID
$('#e1').append(new Option()); // to add the placeholder and the allow clear

I see three issues:
The display of the Select2 control is not refreshed when its value is changed due to a form reset.
The "All" option does not have a value attribute.
The "All" option is disabled.
First, I recommend that you use the setTimeout function to ensure that code is executed after the form reset is complete.
You could execute code when the button is clicked:
$('#searchclear').click(function() {
setTimeout(function() {
// Code goes here.
}, 0);
});
Or when the form is reset:
$('form').on('reset', function() {
setTimeout(function() {
// Code goes here.
}, 0);
});
As for what code to use:
Since the "All" option is disabled, the form reset does not make it the selected value. Therefore, you must explicitly set it to be the selected value. The way to do that is with the Select2 "val" function. And since the "All" option does not have a value attribute, its value is the same as its text, which is "All". Therefore, you should use the code given by thtsigma in the selected answer:
$("#d").select2('val', 'All');
If the attribute value="" were to be added to the "All" option, then you could use the code given by Daniel Dener:
$("#d").select2('val', '');
If the "All" option was not disabled, then you would just have to force the Select2 to refresh, in which case you could use:
$('#d').change();
Note: The following code by Lenart is a way to clear the selection, but it does not cause the "All" option to be selected:
$('#d').select2('data', null)

If you have a populated select widget, for example:
<select>
<option value="1">one</option>
<option value="2" selected="selected">two</option>
<option value="3">three</option>
...
you will want to convince select2 to restore the originally selected value on reset, similar to how a native form works. To achieve this, first reset the native form and then update select2:
$('button[type="reset"]').click(function(event) {
// Make sure we reset the native form first
event.preventDefault();
$(this).closest('form').get(0).reset();
// And then update select2 to match
$('#d').select2('val', $('#d').find(':selected').val());
}

Just to that :)
$('#form-edit').trigger("reset");
$('#form-edit').find('select').each(function(){
$(this).change();
});

What I found works well is as follows:
if you have a placeholder option like 'All' or '-Select-' and its the first option and that's that you want to set the value to when you 'reset' you can use
$('#id').select2('val',0);
0 is essentially the option that you want to set it to on reset. If you want to set it to the last option then get the length of options and set it that length - 1. Basically use the index of whatever option you want to set the select2 value to on reset.
If you don't have a placeholder and just want no text to appear in the field use:
$('#id').select2('val','');

To achieve a generic solution, why not do this:
$(':reset').live('click', function(){
var $r = $(this);
setTimeout(function(){
$r.closest('form').find('.select2-offscreen').trigger('change');
}, 10);
});
This way:
You'll not have to make a new logic for each select2 on your application.
And, you don't have to know the default value (which, by the way, does not have to be "" or even the first option)
Finally, setting the value to :selected would not always achieve a true reset, since the current selected might well have been set programmatically on the client, whereas the default action of the form select is to return input element values to the server-sent ones.
EDIT:
Alternatively, considering the deprecated status of live, we could replace the first line with this:
$('form:has(:reset)').on('click', ':reset', function(){
or better still:
$('form:has(:reset)').on('reset', function(){
PS: I personally feel that resetting on reset, as well as triggering blur and focus events attached to the original select, are some of the most conspicuous "missing" features in select2!

Select2 uses a specific CSS class, so an easy way to reset it is:
$('.select2-container').select2('val', '');
And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.

Sometimes I want to reset Select2 but I can't without change() method. So my solution is :
function resetSelect2Wrapper(el, value){
$(el).val(value);
$(el).select2({
minimumResultsForSearch: -1,
language: "fr"
});
}
Using :
resetSelect2Wrapper("#mySelectId", "myValue");

For me it works only with any of these solutions
$(this).select2('val', null);
or
$(this).select2('val', '');

// Store default values
$('#filter_form [data-plugin="select2"]').each(function(i, el){
$(el).data("seldefault", $(el).find(":selected").val());
});
// Reset button action
$('#formresetbtn').on('click', function() {
$('#filter_form [data-plugin="select2"]').each(function(i, el){
$(el).val($(el).data("seldefault")).trigger('change');
});
});

If you want to reset forms in edit pages, you can add this button to forms
<button type="reset" class="btn btn-default" onclick="resetForm()">Reset</button>
and write your JS code like this:
function resetForm() {
setTimeout(function() {
$('.js-select2').each(function () {
$(this).change();
/* or use two lines below instead */
// var oldVal = $(this).val();
// $(this).select2({'val': oldVal});
});
}, 100);
}

Lots of great answers, but with the newest version none worked for me. If you want a generic solution for all select2 this is working perfectly.
Version 4.0.13 tested
$(document).ready(function() {
$('form').on('reset', function(){
console.log('triggered reset');
const $r = $(this);
setTimeout(function(){
$r.closest('form').find('.select2-hidden-accessible').trigger('change');
}, 10);
});
});

$(function(){
$("#btnReset").click(function(){
$("#d").select2({
val: "",
});
});
});

to remove all option value
$("#id").empty();

Related

Javascript to select option in dropdown list with VALUE

JSFiddle Demo of My Code
I need to change the selected OPTION in a dropdown & Also Trigger the onChange of the dropdown.
$('#type').val('option 1');
$('#type').val('option1');
I tried the above to select
<option value="option1">option 1</option>
However no luck so far!
Use the following:
$('#type').val('option1').change();
You should pass the value of the value attribute to the .val() function.
You can trigger the change event by calling .change() (with no arguments) on the jQuery object that represents the <select> element.
Note: Calling .change() with no arguments is a shortcut for calling .trigger('change').
jsfiddle
you can use your code like this. #openvz is not present in your html code that's why its not working.and you need to use option1 instead option 1
$('#change').click(function(){
$('#type').val('option1');
});
js fiddle
You need to cancel the click and use the correct ID
$('#change').on("click",function(e){
e.preventDefault();// cancel
$('#type').val('option1').change(); // must be the value, not the text
});
Also you cannot submit a select. If you want, you can submit the form if it does not have a field with name="submit"
You will need to tell us what you want to have happen when you change the select too. for example change the select and have it submit the form it is in
$(function() {
$('#change').on("click",function(e){
e.preventDefault();// cancel
$('#type').val('option1').change(); // assuming you want to trigger the change
});
$('#type').on('change',function() {
$(this).closest("form").submit();
});
});
try this Demo
<option value="option 1">option 1</option>
$('#change').click(function(){
$('#type').val('option 1');
});

set some specific options in multiselect as disabled and selected

I have a multiselect box having some options which i am able to select or disable via jquery, but i am not able to make them do both at the same time. How can i do that via jquery ??
Here's what i was doing - JSFiddle
In this example i am selecting an option on load and after that disabling it, but the option is still de selectable. I want to keep it selected and disabled all the time.
For now i am using click method to keep it selected by adding this line:
$('#multiSelect').click(function()
{$('#multiSelectoption[value="three"]').attr('selected',true);});
EDIT:
People are posting the solution where we select the option again on click, which i already have posted in my question. What i wanted to know is that if there exist some better solution as this one does not look good.
js fiddle:
http://jsfiddle.net/Tf5ZZ/5/
jquery:
//disabling on load:
$('#multiSelect option[value="three"]').prop('disabled', true);
$("#multiSelect option").on('click',function() {
$('#multiSelect option[value="three"]').prop('selected',true);
});
If the point is to prevent the value of the select box from being changed after it's set then you should disable the select box instead of just the option item.
$('#multiSelect option[value="three"]').prop('selected',true);
$('#multiSelect').prop('disabled',true);
See this fiddle for demonstration: http://jsfiddle.net/zKbVm/1/.
Also, the difference between prop() and attr() is that attr() gets/sets the element's attributes (which reflect the inital state of the element) and prop() gets/sets its properties (which represent the current state of the DOM node). See https://stackoverflow.com/questions/5874652/prop-vs-attr for more information.
Here is a small piece of jQuery to solve your problem.
$("#multiSelect option").click(function()
{
$("#multiSelect option[value='three']").prop("selected", true);
});
<select multiple="multiple" size="3">
<option value="1" selected>One</option>
<option value="2" disabled>Two</option>
<option value="3" disabled>Three</option>
</select>
I guess you could handle that in the create event of multiselect which is called after the widget gets created.
Below is the code snippet which I am using in the current application I am working on;
create: function (event, ui) {
$(this).multiselect("widget").find(":checkbox").each(function () {
var checkBoxValue = $(this).val();
// Using linq.js to query the fields and determine whether
// the field is required in my case.
// Replace this if statement with your own logic here
if (Enumerable.From(CHAMP.cache.fields).Count(function (x) {
return x.Id.toString() == checkBoxValue && x.IsRequired == true;
}) > 0) {
$(this).attr("checked", "checked");
$(this).attr("disabled", "disabled");
}
});
}

Change option value based on it's current value in jQuery

I have the following HTML:
<select class="file_image_type" name="file_image_type">
<option>Gallery</option>
<option>Feature</option>
<option>Thumbnail</option>
</select>
This is generated dynamically and is repeated for each item. Since there can only be one Feature image, I want to reset the option value of any labeled as "Feature" whenever a new image is selected as being a "Feature".
I've tried this jQuery but it doesn't seem to be responding:
current.find(".file_image_type option[value='Feature']").val("Gallery");
I'm able to set the image as Feature just fine using this:
current.find(".file_image_type").val("Feature");
"Gallery" is not the val(), it's the text().
People, people, you do not need to select the options directly in jQuery. I can't believe how many times I see this mistake.
$('.file_image_type').change(function() {
$('.file_image_type').not(this).each(function() {
var $this = $(this);
if ($this.val() === 'Feature') {
$this.val('Gallery');
}
});
});​

Jquery plugin bind change event

I just created a selectbox plugin.It is very simple and I am trying to modify it.
Actually what it is doing is to hide the select and add some ul,li after that select.
Say that I have these options available
<select id="test">
<option>1</option>
<option>2</option>
</select>
Now I can do
$("#test").selectBox(); //to make it my selectBox
I have setter and getter options
$("#test").selectBox("changeValue",["changed option",index]);
On my plugin I am using methods ..
var methods = {
init :function(options){},
changeValue:function(value){
//some code to change the value ...
}
};
I can change the value ,but how can I catch the change event?
change means that a change in select or ul,li
What I really need is
$("#test").selectBox(); //initialise
$("#test").change(function(){ //attach change event
//my codes.....
});
or
$("#test").selectBox({
onChange : function(){
console.log("changed....");
}
});
Hope that the question is clear now.
Thank you.
EDIT : HERE IS THE FIDDLE link http://jsfiddle.net/jitheshkt/rBjqq/3/
Please note that i am not a expert on this and just trying to make it.
*Edit : i wrote events inside the each function ,so i think that that will be the problem. i changed it and working well *
Try this...
$("#test").on('change',function(){
// Write your code here.
});
For Older version of jQuery Use this
$("#test").change(function() {
console.log('HI');
});
This should work as it is.
I suppose you are setting the value using val() method. The change event doesn't trigger if you are changing the value using jQuery API/JavaScript, so you have to trigger it manually, like this:
$('#test').change()
or
$('#test').trigger('change');
I hope that would do the trick!!
You can depend on the original select box change rather than your customized select box.
When you select an li item, you update the corresponding value in original selectbox so that change get's fired..

jQuery serialize remove empty Select

I have a big form, that will be serialized by a jQuery function.
The problem is that I need to remove from this form before being serialized all the empty values.
I found a way to successfully remove all the empty input text fields, but not the selections.
It does not work properly with select dropdowns.
Ceck below:
echo "<script type=\"text/javascript\">
$(document).ready(function() {
$('#submForm').validate({
submitHandler: function(form) {
// Do cleanup first
$('input:text[value=\"\"]', '#submForm').remove();
$('select option:empty', '#submForm').remove();
var serialized = $('#submForm').serialize();
$.get('".$moduleURL."classes/DO_submission.php', serialized);
window.setTimeout('location.reload()', 8000);
return false;
form.submit();
}
})
});
It should completely remove the dropdown selections where the values are empty. Not only the options but the entire select box should not be included in the serialize function.
How do I achieve this?
$('select option:empty', '#submForm').remove();
This code is not working as it should..
First, a select can not have an empty value. It will default to the first option if the selected attribute is not set.
Second, $('select option:empty') selects the empty options. To do something, an option should have a value, so afaik the selector will never work.
What you need to do is check all selects to see if they have a different value than their default, and if it is not the case, remove them.
If with 'empty select' you mean that the user has not chosen a 'valid' option (for example the fist option of a select is <option value=''>Select your value</option> )why don't you iterate on the select and check their value?
$('select').each(function(){
if ($(this).val() === ''){//this assumes that your empty value is ''
$(this).remove();
}
});
EDIT - sorry for the error, i missed the last parenthesis, i tried it and it works for me
I would just instead of serlizing the the whole form I would use jquery Form and then all you have to do is call
$('#submForm').ajaxSubmit({/.../});
Try
$('select option:selected:empty').parent().remove();
Edited after reading Nicola's comment.

Categories

Resources