I'm facing an issue in selecting the dropdown first value after selecting it for the first time. When the dropdown options slidedown to select, the first value would be selected by default,bcoz of which I'm not able to select the first value. I'm using JQuery mobile framework and I'm writing custom JS to change the dropdown. I need to handle this dropdown only using custom JS and cannot make the dropdown work with this custom logic due to some other issue with my project.
Here first value im referring as 'US' from dropdown
The solution for this issue would be really appreciated. Thanks in advance.
HTML:
<select id="drpDwn">
<option value="" disabled="disabled">select</option>
<option value="US">US</option>
<option value="AU">AU</option>
<option value="NZ">NZ</option>
</select>
JS:
$(document).on('change', '#drpDwn', function () {
var index = $(this)[0].selectedIndex;
$(this).attr('selectedIndex', index);
$(this).find('option').removeAttr('selected');
$(this).find('option').eq(index).attr('selected', 'selected');
$(this).siblings('span').html($(this).find('option').eq(index).text());
});
http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js
http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css
Check out this JSFiddle
The difference maker was modifying:
$(this).find('option').removeAttr('selected');
Into:
$(this).find('option:not(:selected)').removeAttr('selected');
When 'change' was triggered, the selected attribute is added to the new option, so you were stripping it away from everything even the new selection. That's why the option never changed.
Using :not(:selected) came in handy then since it will only strip away the attribute from things that weren't the current selected option.
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');
});
I am trying to utilize the JQuery if statement to create a form that will allow employees to create a custom verbal script for their customers. Basically the JQuery Plugin will simply append input field values to a dialogue to be read by the employee to the customers.
I've had no issue with the JS written to append the contents of text-fields and select boxes to the dialogue but seem to be unable to figure out the most crucial part. I want to be able to show or hide information relevant to specific states based upon the value of a select box input field.
Below is a single example of my attempt at utilizing the if/else statement to do so.
HTML:
<select name="state_select" class="state_select">
<option value="CT">Connecticut</option>
</select>
<p class="ct_opt">Lorem Ipsum</p>
Css:
.ct_opt {
display:none;
}
JQuery:
$(document).ready(function(){
if ($("select.state_select").val() == "CT") {
$("ct_opt").show();
} else {
if ($("select.state_select").val() != "CT")
$("ct_opt").hide();
}
});
From what I understand, this should allow the targeted text to stay hidden unless its corresponding state is selected. However, it seems to do nothing at the current moment :(
Any suggestions would be greatly appreciated.
$(document).ready(function() {
$('.state_select').val('CT');
$('.state_select').on('change', function() {
console.log('click');
if($(this).val() == 'CT') {
$('.ct_opt').show();
}
else if ($(this).val() == 'noshow') {
$('.ct_opt').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="state_select" class="state_select">
<option value="CT">Connecticut</option>
<option value="noshow">Dont Show</option>
</select>
<p class="ct_opt">Lorem Ipsum</p>
$('select.state_select') will select an array of select objects with the class state_select. If you only have one state_select you should change this selector to $('#state_select'). There is no point in using $('select#state_select') (although valid) since there can only be a single id per page. You could use your current selector but you will need to call .first() to get the first item in the array of elements matching that selector.
Additionally as Ragnar pointed out there is no element named 'ct_opt' so you need to change your selector to $('.ct_opt') to target the class.
Use .ct_opt because it's a class and execute your code when selection changes:
$(document).ready(function(){
$("select.state_select").change(function(){
if ($(this).val() == "CT")
$(".ct_opt").show();
else $(".ct_opt").hide();
});
$("select.state_select").change(); //call change event when page loads
});
You can use $() because it's equivalent to document ready:
$(function(){
$("select.state_select").change(function(){
if ($(this).val() == "CT")
$(".ct_opt").show();
else $(".ct_opt").hide();
});
$("select.state_select").change(); //call change event when page loads
});
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();
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');
}
});
});