Question:
An alert is displayed (with the sweetalert plugin) and this alert has a select
with names. After selecting the name, the person has to click on the Add button, when the person clicks the function
of the code below is executed and in it I put a code to capture the selected option
, but the result is always that of the first option
.
$("a#AddListaPresentes").click(function(){
var conteudoListaPresente = $("#contentLP").html();
var id_produto = $(this).attr('ref');
var baseURL = $("#baseURL").val();
swal({
title: "Adicionar a Lista de Presentes",
text: conteudoListaPresente,
html: true,
showCancelButton: true,
closeOnConfirm: false,
closeOnCancel: true,
cancelButtonText: 'Cancelar',
confirmButtonText: 'Adicionar'
},function(){
var selecionado = $("#ListaPresenteSelect option:selected");
alert(selecionado);
if($.trim(selecionado) != false){
$.ajax({
url: baseURL+'ajax/adicionaritemlistadepresentesx',
type: 'POST',
data:{id:selecionado, produto:id_produto},
success:function(callback){
if(callback){
swal("Adicionado!", "Produto adicionado a sua lista de casamento (:", "success");
}else{
swal("Opss", "Ocorreu um erro ao adicionar o produto: "+callback, "error");
}
}
});
}
});
})
Answer:
There are a few ways to get the value, as you don't have your HTML, I'll name a few:
If your form doesn't have the value
attribute, something like:
<select id="ListaPresenteSelect">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</select>
You can take it directly, like this:
$('#ListaPresenteSelect').val();
If you have a value
attribute and want to access it, just use the example described above.
If you have a value
and you want to get the selected text, you can do this:
$('#ListaPresenteSelect option:selected').text();
In your example above, you seem to be missing just getting the text with the .text()
method.