En este post veremos algunar formas para manipular un  “select”  mediante jQuery.

Agregando mediante html.

Una  de las formas mas sencillas es agregar la opción mediante codigo HTML como tal, y agregarselo a select mediante append.

$('#example').append('<option value="foo" selected="selected">Foo</option>');

 

Mediante la forma “new option”

Una forma un poco más  adecuada es usando la el metodo new option(). a un que esta forma podria no funcionar muy bien en internet explorer ¬¬.

$('#example').append(new Option('Foo', 'foo', true, true));

 

Agregando multiples options.

En el siguiente codigo estaremos agregando 4 optiones al select con id = #example.

var newOptions = {
    'red' : 'Red',
    'blue' : 'Blue',
    'green' : 'Green',
    'yellow' : 'Yellow'
};
var selectedOption = 'green';

var select = $('#example');
if(select.prop) {
  var options = select.prop('options');
}
else {
  var options = select.attr('options');
}
$('option', select).remove();

$.each(newOptions, function(val, text) {
    options[options.length] = new Option(text, val);
});
select.val(selectedOption);

 

Limpiar nuestro select

$('#exampleSelect').html('');

 

Seleccionando una opción median Js

Con esta funcion vamos  a setear el valor que queremos se seleccione en un determinado select.

bastara con enviar como parametros el nombre del Id, y el value que queremos seleccionar.

    function setValueSelect(SelectId, Value) {
        SelectObject = document.getElementById(SelectId);
        for(index = 0;  index < SelectObject.length;  index++) {
            if(SelectObject[index].value == Value) SelectObject.selectedIndex = index;
        }
    }

 

Código del formulario

By govani

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *