Exchange the value of a radio button input for the differentiated value typed by the user

Asked

Viewed 42 times

0

Good night, I have a problem, I am creating a donation form and I need to create a radio input with differentiated value that the user would type it.

Ex:

<form action="#" method="post" class="donate" id="donate">
<div class="group">
<input type="radio" name="amount" id="30" value="30"/>
<label for="30">R$30</label>
<input type="radio" name="amount" id="50" value="50"/>
<label for="50">R$50</label>
<input type="radio" name="amount" id="100" value="100"/>
<label for="100">R$100</label>
<input type="radio" name="amount" id="250" value="250"/>
<label for="250">R$250</label>
<input type="radio" name="amount" id="500" value="500"/>
<label for="500">R$500</label>
<labe><input type="radio" name="amount" id="amount_outro" value="other" >Outro Valor:</input>
<input type ="text" name="other" id="amount_texto"/></label>
</div>

In case I would need the value that the person type in the text input next to the "other value:" to replace the value="other".

Thank you in advance!

1 answer

0


You can add an event from onchange in his input#amount_texto and when the event is triggered change the value of input#amount_outro. Something +/- like this example below:

/// ; Adicionar evento no input[type='text'] #amount_texto
$("#amount_texto").on("change",function(){
    
    /// ; `this` aqui dentro é o #amount_texto

    /// ; quando evento é disparado ele altera o valor
    /// ; do input[type='radio'] #amount_outro
    $("#amount_outro").val( this.value );
});


/// ; PARA MOSTRAR NO CONSOLE
$("button").click(function(){
  /// ; Pega os dados do formulário
  let fdata = new FormData( $("#donate")[0] ),
      dados = {};
  /// ; transforma em um objeto
  for( let e of fdata.entries() ){ dados[e[0]]=e[1]; }
  
  console.log( dados );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="post" class="donate" id="donate">
  <div class="group">
    <input type="radio" name="amount" id="30" value="30" />
    <label for="30">R$30</label>
    <br/>
    <input type="radio" name="amount" id="50" value="50" />
    <label for="50">R$50</label>
    <br/>
    <input type="radio" name="amount" id="100" value="100" />
    <label for="100">R$100</label>
    <br/>
    <input type="radio" name="amount" id="250" value="250" />
    <label for="250">R$250</label>
    <br/>
    <input type="radio" name="amount" id="500" value="500" />
    <label for="500">R$500</label>
    <br/>
    <input type="radio" name="amount" id="amount_outro" value="other"/>
    <label>Outro Valor:</label>
    <input type="text" name="other" id="amount_texto" />

  </div>
</form>
 <br/>
<button type='button'>MOSTRA NO CONSOLE</button>

  • Thank you very much friend, that’s exactly what I needed!

Browser other questions tagged

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