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

govani

14 comentarios en “Manipulando un select con jQuery”

  1. Ok funciona pero con valor pre-determinado, y si lo que deseo es tomar los datos de una base de datos, mostrarlos en el Select, y cuando doy click al boton agregar, me deje escribir la opcion y la muestre en el select (Sin borrar la info anterior)

    1. Bueno en este caso necesitaras un poco mas de código JS para mandar un promp o la ventana de dialogo, y después usar la linea $(‘#example’).append(‘Foo’);

      Con esto se agregara pero no se eliminan las anteriores.

  2. ¿Y para poner yo desde el formulario el valor que quiero?
    Me explico, estoy haciendo una base de datos de películas y para los géneros quiero que se vayan añadiendo según se vayan incluyendo al insertar las fichas de películas.

  3. Hey there terrific blog! Does running a bog such as this taie a massive
    amount work? I’ve no understanding of computer programming however I was
    hoping to start my own blog in tthe near future. Anyway, should
    you have any suggestions or tips for new blog owners
    please share. I understand this is offf topic however I simkply needded to ask.
    Appreciate it!

  4. You ll see pretty quickly that with just a few shapes and knowing the names of the notes on your guitar you ll be able to play pretty much any chord you ll ever need.
    PLAYBOY Then you re not wary about ill-informed performers affecting politics.
    I care for you very much.
    http://moathsadartojaktilar.info Erlewene, Michael, Vladimir Bogdana, Chris Woodstra, and Cub Koda.They have, through the mails and hired emissaries, sent seditious pamphlets and papers among us to stir up servile insurrection and bring blood and carnage to our firesides.

  5. Artculo 19 En presencia del Gobernador.
    I dont think Jimi has something to do with Aleister Crowley, seriously,.
    Curtains Up Skit Evil Deeds Never Enough featuring 50 Cent and Nate Dogg Yellow Brick Road Like Toy Soldiers Mosh Puke My 1st Single Paul Skit Rain Man Big Weenie Em Calls Paul Skit Just Lose It Ass Like That Spend Some Time featuring Obie Trice , Stat Quo and 50 Cent Mockingbird Crazy in Love One Shot 2 Shot featuring D12 Final Thought Skit Encore Curtains Down featuring Dr.
    http://tegesharnuazar.info/zip/oglyanis-vo-gneve-rashid-beybutov-instrumentalniy-ansambl-pod-upravleniem-rafika-babaeva-azerb.php Р§ , Led Zeppelin The Nobs.
    They instead finesse the wordsto perfection and add a little irony to boot.
    We are full of MondayMotivation after a great weekend of L ondon Groove R B parties in the city, and our DJs enjoyed spinning a great mix of current club bangers and old skool party anthems, of course one of the biggest UK R B classics is Mark Morrison s Return of The Mack released in 1996, and now Stockholm produced Nevada has created a remake which is flying high in the charts.

  6. They may be very helpful in giving you essential information on debt management. When the personal respect is hurt, we all lose peace of mind and our own worth. Stretching plus mobility work can help a person moving like a well oiled machine.

  7. Pre-gap length 0 00 00.
    Woodstock Improvisation Villanova Junction 16.
    Musicians wrote and performed in a shortlived genre in the 1960s called psychedelic rock which was sometimes referred to as acid rock.
    http://ladoramoonshaperarashakar.info/rar/rainy-days-and-mondays-carpenters-carpenters.php His debut single, Farandulera was released on radio stations Colombia.
    Kalau fc yang belum diputar, berapa lama tahan simpan kat dalam freezer.
    Despus de que le fuera firmada el alta mdica, el muchacho reemprendi su carrera solista con la valiosa ayuda de Bowie.

  8. Thanks for stopping by my page! I’m Kelsie.
    Even though I jokingly credit my aunt for my writing talent, I know that it is a talent I have fostered from childhood. Though my aunt is a writer, I also started out young.
    I’ve always had a way with words, according to my favorite professor . I was always so excited in English when we had to do a research paper .
    Now, I help current pupils achieve the grades that have always come easily to me. It is my way of giving back to students because I understand the obstacles they must overcome to graduate.

    Kelsie – Academic Writing Professional – supportthedandelionschool.com Confederation

Responder a Juan Carlos Montenegro Cancelar la respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *