I need to fill 2 fields using select

Asked

Viewed 297 times

3

I have a select with the following values in option:

<select id="frutas" name="frutas" >
     <option value="">Selecione...</option>
     <option value="Maçã - 10.00"> Maçã </option>
     <option value="Banana - 15.00"> Banana </option>                      
</select>

When selecting an option, the data is populated in a field text with the ID: nome_preco:

<input type="text" id="nome_preco"  name="nome_preco" value="" />                                                                                        

I need to fill another field but only with the price of fruit:

<input type="text" id="preco"  name="preco" value="" />  

So if I select "Maçã", my fields would be filled with data:

Fruit: Maçã - 10.00

Valor: 10.00

How can I do that? Would it be possible to do that using jQuery? Could you help me? Thank you

1 answer

2


See below the code in operation:

$('#frutas').change(function(){
     
     $('#preco').val($('#frutas').val());
  
     $('#nome').val($('#frutas option:selected').text());
  
     $('#nome_preco').val($('#frutas option:selected').text() + ' - ' + $(this).val());
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="frutas" name="frutas" >
     <option value="">Selecione...</option>
     <option value="10.00">Maçã</option>
     <option value="15.00">Banana</option>                      
</select>
<br/>
<br/>
Preço<br/>
<input type="text" id="preco"  name="preco" value="" />

<br/>
<br/>
Nome<br/>
<input type="text" id="nome"  name="nome" value="" />     

<br/>
<br/>
Nome + preço:<br/>
<input type="text" id="nome_preco"  name="nome_preco" value="" />     

  • thank you so much! It worked great!

Browser other questions tagged

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