Selection from dropdownlist javascript event - javascript

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.

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.

jQuery Autopopulate Multiple Select uses text instead of value

I've got a multiple select like this configured to auto-populate:
<select id="multiple-select-box" class="selectivity-input" data-placeholder="Type to search condos" multiple>
<option id="Alabama Grove Terrace" value="Alabama Grove" >Alabama Grove Terrace</option>
<option id="Alden Pines" value="Alden Pines" >Alden</option>
</select>
Upon select I realized the script is submitting the visible Text for each option instead of the value="" for each option chosen.
I tried to change var t=$(this).text(); to var t=$(this).value(); thinking that would grab the value instead of the option text but had the same results. What am I missing?
<script>
$(document).ready(function() {
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).text();
//if()
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
})
$('#multiple-select-box').selectivity();
});
</script>
Ok, so I went to check this selectivity plugin you're using and it converts your select into a series of divs as
<div class="selectivity-results-container">
<div class="selectivity-result-item highlight" data-item-id="Alabama Grove">Alabama Grove Terrace</div>
<div class="selectivity-result-item" data-item-id="Alden Pines">Alden</div>
</div>
you have to change your submit function to get the data-item-id property which corresponds to your original select value like
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).data("item-id");
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
edit
fiddle example
In this line, you are appending options to the select, but you have set no value attribute:
$(".ml").append("<option selected='selected'>"+t+"</option>");
As stated in the comments, the "fetch value" method of a form element in jQuery is:
$(this).val()
You might be confusing it with the JavaScript property:
this.value
...which also works. Both return an array of strings if something is selected and set to "multiple"
To follow up on your comment, I don't see your markup for the selected element with class="ml" thus it's almost impossible to debug why your form isn't submitting the values without seeing the bigger picture (i.e. it may be outside the form element). You could try adding the value property to the select element however jQuery should be able to pick up selected options missing the value property by using the text value instead.

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.

Displaying hidden text-box on particular option won't work when it is the only option present

I have the following javascript to display a hidden textbox onchange when a certain option is selected. It works fine when multiple options are present. But when the only option is the one that makes the text-box appear, it won't work. I tried onload too for no results.
function showOther(fieldObj, otherFieldID)
{
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue=='other') ? '' : 'hidden';
return;
}`
Here's the working fiddle http://jsfiddle.net/8bm9R/2/ Look at the first select field
If it has only one option in the list then onchange event doesn't fire . Use onclick instead:
<select name="task" onclick="showOther(this, 'new');">
(JSFiddle please: http://jsfiddle.net/8bm9R/7/).
To prevent this behaviour and be able to use onchange may be it will be good to add some default option to the list , something like "Choose a Job"..
The onchange Event trigges only, if something changed. You could do something like this:
Please choose...
or maybe:
<select name="jobs" onmouseup="showOther(this,'new');">

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