how to access an attribute of a select with jquery?

0

I have a select that I fill from my database, all right up there but I fill three parameters in my select: one is the value, another parameter 2 and another what is shown. What I need is to get what is shown so create the parameter 2 so you can get it by jquery.

I give you an image of how I load my select

I need to get what is displayed or the parameter 2

I pass the jquery

 function elegirsaldo(){
        var saldo = $(this).attr("parametro2");
        alert(saldo);
     }  

but I get undefined

I hope your help thanks

    
asked by ingswsm 22.11.2017 в 18:29
source

2 answers

1

To obtain this attribute, you will have to access the selected option, but not the select itself, although this is necessary to perform the previous action. In addition, in its example the this does not refer to the select element. if you want to make reference you could pass this from the html and receive it in the function

function elegirsaldo(el){ // recibimos por parametro el elemento select
   // obtenemos la opción seleccionada .
  var saldo = $('option:selected', el).attr('parametro2');
  console.log(saldo);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="idgiftpro" onchange="elegirsaldo(this);">
  <option value="0" parametro2="0">Seleccionar</option>
  <option value="1"  parametro2="10">50</option>
  <option value="2"  parametro2="20">100</option>
  <option value="3"  parametro2="30">200</option>
</select>

Another form without reference from the html to the event.

$('#idgiftpro').change(function(e){
  var saldo = $('option:selected',this).attr('parametro2');
  console.log(saldo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="idgiftpro" >
  <option value="0" parametro2="0">Seleccionar</option>
  <option value="1"  parametro2="10">50</option>
  <option value="2"  parametro2="20">100</option>
  <option value="3"  parametro2="30">200</option>
</select>
    
answered by 22.11.2017 / 18:41
source
0

To load info to an HTML element, it is best to assign it to its data property.

<select id="idgifftpo" onchange="elegirsaldo(this)">
    <option value="0" data-parametro2="0">--Selecionar--</option>
    <option value="1" data-parametro2="50.00">Uno</option>
    <option value="2" data-parametro2="100.00">Dos</option>
</select>

Using jQuery you can directly access data by means of its data name , in this case parametro2.

function elegirsaldo(sel){
        var saldo = $('option:selected', sel).data("parametro2");
        alert(saldo);
     }  

Or as an attribute as you are looking for it, it must work.

function elegirsaldo(sel){
            var saldo = $('option:selected', sel).attr("data-parametro2");
            alert(saldo);
         } 
    
answered by 22.11.2017 в 18:42