Add option to select

Asked

Viewed 62 times

0

Good afternoon!

HTML

<label class="labelPequeno">Cidade</label>
<select class="typeTextMedio" name="cidade" id="cidade" required>
    <option value="" selected>Selecione a cidade</option>
</select>

Javascript

option = document.createElement( "option" );
option.value = "28510";
option.text = "Muriaé";
option.selected;
$("#cidade").add( option );

The idea is to create a option in the select with id="cidade", but it is not adding.

What is wrong?

I tried that too but it didn’t work:

$('#cidade').append($("<option></option>")
            .attr("value","<?php echo $cidade["id"]; ?>")
            .text("<?php echo $cidade["nome"]; ?>")
            .attr("seleted","selected");

Also so:

$("#cidade").append('<option value="<?php echo $cidade["id"]; ?>"><?php echo $cidade["nome"]; ?></option>');

Didn’t work!

1 answer

0

Try it this way:

$('#cidade').append('<option value="<?php echo $cidade["id"]; ?>"><?php echo $cidade["nome"]; ?></option>');

Or

$('#cidade').append($('<option>', {value:<?php echo $cidade["id"]; ?>, text:'<?php echo $cidade["nome"];?>'}));

Or

$('#mySelect').append($("<option></option>").attr("value",<?php echo $cidade["id"]; ?>).text(<?php echo $cidade["nome"];?>)); 

Take this example: http://jsfiddle.net/wBrLa/82/

  • worked out but I need to send him Selected

  • @Carlosrocha See the other examples and if you still can’t see the link

  • I found the error: was writing seleted instead of Selected.

  • :) .. happens rsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.