Lamloumi Afif
Lamloumi Afif

Reputation: 9081

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?

Upvotes: 0

Views: 69

Answers (4)

Michelangelo
Michelangelo

Reputation: 5948

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.

Upvotes: 0

J Spring
J Spring

Reputation: 492

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

Upvotes: 1

redsam
redsam

Reputation: 145

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.

Upvotes: 0

DrunkWolf
DrunkWolf

Reputation: 1004

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.

Upvotes: 1

Related Questions