Jquery plugin bind change event - javascript

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..

Related

How to get the value in a select change event in angular2

I want to navigate useing a dynamically generated select drop down.
It doesn't appear I can do that directly, so I'd simply like to make a function call when the select changes.
To do that, I have this:
---In the template---
<select (change)="navSelected($event)">
<option *ngFor="let button of navButtons;"
value="button.route" >{{button.label}}</option>
</select>
suffice it to say that 'navButtons' is an array of objects that have a 'label' field.
---In the class---
navSelected(navName) {
console.log(navName + " Clicked!");
}
This actually works fine.
I got to this point from the great help of Mark Rajcok and his answer in this older question:
How can I get new selection in "select" in Angular 2?
That said, I'd like to be able to pass the selected value in the navSelected() function call. I'm unsure how to do that.
I have tried adding [ngValue]="button" on a wild guess from other searches to the option tag and then referencing the button variable in the (change) event handler (so: (change)="navSelected(button.label)" and other combos, to no avail. I've seen a lot of references to ngModel but they seem old and I'm not entirely sure they apply anymore (and I couldn't get them to work anyway in RC4).
I could probably pull some jquery or whatever out to find the select and get it's value, but that seems very rinky-dink compared to simply being able to call the function correctly.
The value you are looking for is on the $event.target and you can get it with $event.target.value, see my example below.
navSelected($event) {
console.log($event.target.value + " Clicked!");
}
If you are looking to get the selected text of the option you can do this
navSelected($event) {
let selectElement = $event.target;
var optionIndex = selectElement.selectedIndex;
var optionText = selectElement.options[optionIndex];
console.log(optionText + " Clicked!");
}
As a shortcut for #eltonkamami 's answer, you can pass your object like this:
<select (change)="navSelected(navButtons[$event.target.selectedIndex])">
<option *ngFor="let button of navButtons;">{{button.label}}</option>
</select>
And capture it like this:
navSelected(button: [type of navButtons]){
console.log(button);
}
Instead of $event. Try using the below typecast function.
$any($event.target).value
Which will stop the type checking in the template.

How can I set the Text of a DropDownList using jQuery?

I have seen some answers on how to set the value for a dropdown using jQuery. However in my case, I want to know how to use jQuery to set the text for a dropdown.
This example uses jQuery to set the value for my dropdown:
var trimvalue ="345";
$("#Trim").val(trimvalue);
In my current code Logic, I want to set the displayed text as well, which I tried to do in this way:
var trimtext ="samsung";
$("#Trim").text(trimtext);
This is not a correct syntax. Please provide any suggestions on whether we can set the the text using jQuery or not.
You should be able to set the text with something like
$('#Trim option:selected').text(trimtext);
https://jsfiddle.net/yzgbk1fj/:
Or if you mean to add it, perhaps:
$('#Trim').append($('<option />').text(trimtext)).val(trimtext);
https://jsfiddle.net/yzgbk1fj/1/
First Create a html tag in your html page
<select id='sampleSelect'>
<select>
Second in your Jquery target the select function using an ID
$(document).ready(function(){
var trimtext ="samsung";
$("#sampleSelect").append(
"<option value="+trimtext+">"+trimtext+"</option>"
);
});
And if you have alot of values for your drop down use a For loop. Hope this help.

Resetting Select2 value in dropdown with reset button

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();

how to set the selected option of a select element without triggering a change event?

I'm currently using this on a select:
var sortNo = $('select[name=anzahl_eintraegeSEL]');
sortNo
// set selected based on hidden input default value
.find('option[value="'+ $('input[name=anzahl_eintraege]').val() +']')
.attr('selected', 'selected').attr('set',true)
// set up change listener
.on('change', function(){
// do sth
});
I want to set the default option to selected without triggering an initial change event.
How can I get this to work? The above seems to trigger a change event right away.
Thanks for help!
You can try:
sortNo
.on('change', function(){
// do sth
})
.val($('input[name=anzahl_eintraege]').val()); // set the default value get from hidden field
DEMO
for once: In this line:
.find('option[value="'+ $('input[name=anzahl_eintraege]').val() +']')
You are missing the closing '"'. Should be:
.find('option[value="'+ $('input[name=anzahl_eintraege]').val() +'"]')
Next your .on() is executed while jQuery has your tag on top... I guess you want the change of the , not on the .
And you don't need to find the option tag yourself, jQuery can do that for you, using sortNo.val().
I believe that is what you want?: http://jsfiddle.net/KadrG/

set value to jquery autocomplete combobox

I am using jquery autocomplete combobox
and everything is ok. But I also want to set specific value through JavaScript like $("#value").val("somevalue") and it set to select element, but no changes in input element with autocomplete.
Of course, I can select this input and set value directly, but is it some other ways to do that? I try set bind to this.element like this.element.bind("change", function(){alert(1)}) but it was no effects. And I don't know why.
Edit
I found a workaround for this case. But I don't like it. I have added the following code to _create function for ui.combobox
this.element.bind("change", function() {
input.val( $(select).find("option:selected").text());
});
And when I need to change the value I can use $("#selector").val("specificvalue").trigger("change");
Is this demo what you are looking for?
The link sets the value of the jQuery UI autocomplete to Java. The focus is left on the input so that the normal keyboard events can be used to navigate the options.
Edit: How about adding another function to the combobox like this:
autocomplete : function(value) {
this.element.val(value);
this.input.val(value);
}
and calling it with the value you want to set:
$('#combobox').combobox('autocomplete', 'Java');
Updated demo
I cannot find any available existing function to do what you want, but this seems to work nicely for me. Hope it is closer to the behaviour you require.
I managed a quick and dirty way of setting the value. But, you do need to know both the value and the text of the item that you want to display on the dropdown.
var myValue = foo; // value that you want selected
var myText = bar; // text that you want to display
// You first need to set the value of the (hidden) select list
$('#myCombo').val(myValue);
// ...then you need to set the display text of the actual autocomplete box.
$('#myCombo').siblings('.ui-combobox').find('.ui-autocomplete-input').val(myText);
#andyb,
i think rewrite:
autocomplete: function (value) {
this.element.val(value);
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input.val(value);
}
I really like what andyb did, but I needed it to do a little more around event handling to be able to handle triggering the a change event because "selected" doesn't handle when hitting enter or losing focus on the input (hitting tab or mouse click).
As such, using what andyb did as a base as well as the latest version of the jQuery Autocomplete script, I created the following solution: DEMO
Enter: Chooses the first item if menu is visible
Focus Lost: Partial match triggers not found message and clears entry (jQuery UI), but fully typed answer "selects" that value (not case sensative)
How Change method can be utlized:
$("#combobox").combobox({
selected: function (event, ui) {
$("#output").text("Selected Event >>> " + $("#combobox").val());
}
})
.change(function (e) {
$("#output").text("Change Event >>> " + $("#combobox").val());
});
Hopefully this helps others who need additional change event functionality to compensate for gaps that "selected" leaves open.
http://jsfiddle.net/nhJDd/
$(".document").ready(function(){
$("select option:eq(1)").val("someNewVal");
$("select option:eq(1)").text("Another Val");
$("select option:eq(1)").attr('selected', 'selected');
});
here is a working example and jquery, I am assuming you want to change the value of a select, change its text face and also have it selected at page load?
#
Attempt 2:
here is another fiddle: http://jsfiddle.net/HafLW/1/ , do you mean that you select an option, then you want to append that value to the autocomplete of a input area?
$(".document").ready(function(){
someString = "this,that";
$("input").autocomplete({source: someString.split(",")});
$("select").change(function(){
alert($(this).val()+" appended");
someString = someString+","+$(this).val();
$("input").autocomplete({source: someString.split(",")});
});
});

Categories

Resources