set value to jquery autocomplete combobox - javascript

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(",")});
});
});

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.

Selection from dropdownlist javascript event

I have this html part code :
<p><label>Taxe </label>
<select id="id_taxe" name="id_taxe" style="width: 100px;" onchange="taxselection(this);"></select>
<input id="taxe" name="taxe" class="fiche" width="150px" readonly="readonly" />%
</p>
Javascript method :
function taxselection(cat)
{
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
I'd like to set the value of taxe input to the selected value from the dropdownlist.It works fine only where the dropdownlist contains more than one element.
I try onselect instead of onchange but I get the same problem.
So How can I fix this issue when the list contains only one element?
This works:
$('#id_taxe').change(function(){
var thisVal = $(this).val();
var curVal = $('#taxe').val();
if(thisVal != curVal)
$('#taxe').val(thisVal);
$('#select option:selected').removeAttr('selected');
$(this).attr('selected','selected');
});
Use the change method which is very efficient for select boxes. Simply check the item selected isn't currently selected then if not, set the value of the input to the selected value. Lastly you want to remove any option's attr's that are "selected=selected" and set the current one to selected.
Just include this inside a $(document).ready() wrapper at the end of your HTML and the change event will be anchored to the select field.
Hope this helps.
http://jsbin.com/populo
Either always give an empty option, or in your code that outputs the select, check the amount of options, and set the input value straight away if there's only 1 option.
A select with just 1 option has no events, since the option will be selected by default, so there's no changes, and no events.
As DrunkWolf mentioned add an empty option always or you can try onblur or onclick event instead, depending on what you are actually trying to do.
Ok, just to stay close to your code, do it like this: http://jsfiddle.net/z2uao1un/1/
function taxselection(cat) {
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
taxselection(document.getElementById('id_taxe'));
This will call the function onload and get value of the element. You can additionally add an onchange eventhandler to the element. I highly recommend not doing that in the HTML! Good luck.

jQuery 'change' method (for HTML attribute modify) working only once

I have this pair of functions affecting two inputs, and one select. These are exclusive so when inputs are filled, select must be modified to have option 3 selected, and when any option except 3 is selected, both inputs must be empty:
$('#ar_filter').on('change', '#ar_fromDate, #ar_toDate', function() {
if ($('#ar_fromDate, #ar_toDate').val!=""){
$('.lastDays').attr('readonly','readonly').find('option[value=3]').attr('selected', true);
}
});
$('#ar_filter').on('change', '#lastDays', 'select', function() {
if ($('.lastDays').val()!=3){
$('#ar_fromDate, #ar_toDate').val("");
}
});
This works, but only the first time. When I write some value on the inputs, it resets correctly select to value 3, but when I change manually selected options, after it resets and leaves inputs empty, it does not reset anymore the select, even when writing on any of those inputs.
JSFIDDLE EXAMPLE (try making 2 select resets by filling the inputs: it will only make the first one)
Based on your JSFiddle, I believe your second implementation of .on() is incorrect. The third optional argument can be passed as data to the handler function as denoted in the reference documentation.
Try changing:
$('#ar_filter').on('change', '#lastDays', 'select', function() {
to this:
$('#ar_filter').on('change', '#lastDays', function() {
Based on your comment above, I believe your selector is wrong. #lastDays is the id of the <select> element, which is where you want the change event bound. The extra select is not needed.
Updated Fiddle
Note:
The updated fiddle includes the .val() fix described by #tymeJV in his answer.
EDIT:
In addition to the .on() selector fix described above, you'll need to break out the two selectors in your .val() statement. This is because only the first input will be validated each time the change event occurs. This comes directly from the jQuery documentation for .val():
Get the current value of the first element in the set of matched elements.
The second value will not be fetched or validated.
Change this:
$('#ar_fromDate, #ar_toDate').val() != ""
to this:
$('#ar_fromDate').val() != "" || $('#ar_toDate').val() != ""
This should fix the problem. I've included an updated fiddle below. I've left the original fiddle in tact to show the progression of steps in solving this problem for the benefit of future visitors.
Complete Fiddle

Use jQuery to set select box value to first option

I am dynamically populating a select box with options. When I do this, I want the value of the select box to be the value of the first option (a 'default option', if you like). Sounds really simple, but I just can't get it to work.
var myElement = $('select[name="myName"]');
.... tried the following three variations
// myElement.find('option').first().prop('selected', 'selected');
// myElement.val(myElement.find('options').first().val());
myElement.prop('selectedIndex', 0);
...but the following line gives a blank alert
alert(myElement.val());
Where am I going wrong?
options should be option
myElement.find('option:eq(0)').prop('selected', true);
You can use the eq selector on the option to select the first option.
If you know the value of the first option. Then you could simply do
myElemeent.val('first value') // Which selects the option by default
The 2nd case you tried should work, unless you are not calling at the right point . i.e; waiting for the ajax response to be completed.
Try calling that inside the done or the success (deprecated) handler
You almost got it, drop the 's' in 'options':
myElement.val(myElement.find('option').first().val());
Working jsFiddle
You could also use next code:
myElement[0].selectedIndex = 0;
This get's the Dom element (not jQuery object), works with vanilla Javascript and uses it to set the first option as the selected one based on it's index.
If you want to be sure that your option has a value and is not a placeholder you can do:
$('select option').filter( function (index, option) {
return option.attributes.value
}).val()
That way you'll check if the HTML node has attribute value and is not 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/

Categories

Resources