1

I am dynamically setting the options of my select-fields. Every time the form changes, new data is received from a Servlet and the current selections are overwritten.

Problem here is, that if I select an option, the form loads the javascript function, and I loose my selection / focus.

var capacityOptionsAsString = "";
for(var i = 0; i < capacityArray.length; i++) {
  capacityOptionsAsString += "<option value='" + capacityArray[i] + "'>" + capacityArray[i] + "</option>";
  console.log('capacity option: ' + capacityOptionsAsString);
}
$("select[name='inptCapacity']").find('option').remove().end().append($(capacityOptionsAsString));

Any idea how to keep the selection?


Edit: Maybe I was not clear enough. I want to keep the selection. So it has to be validated, if the option is selected, if it is, we have to select it again.

nimrod
  • 5,595
  • 29
  • 85
  • 149

2 Answers2

0

Just set the focus again:

$("select[name='inptCapacity']").focus();

Update

get selected option:

var selected_value = $("select[name='inptCapacity'] option:selected").val()

Do your changes

$("select[name='inptCapacity']").find('option').remove().end().append($(capacityOptionsAsString));

Select it again:

$('select[name='inptCapacity'] option[value="' + selected_value + "]').attr('selected', 'selected');

You totally need an id for your select ;)

PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
0
$('select[name="inptCapacity"]').is(':focus');

$('form[name="formName"] :input').change(function() {

   // keep the select focus always on input change

   $('select[name="inptCapacity"]').focus(); 

});
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164