Load an element in ajax as the user chooses

1

I have a code that inserts a textearea field as a choice of input radius. I would like to simplify this code making it use only JavaScript. It's possible? Follow below:

HTML

<p>2.3 - Você estuda? </p>
<input type="radio" name="estuda" id="estuda" value="1" required=""> Sim 
<input type="radio" name="estuda" id="estuda" value="2" required=""> Não 
<div id="ret-ajax"></div>

JavaScript

$('#estuda').change(function () {
  var chars = (this.value);
  $.post(URL + 'Ajax/pesquisa', {val: chars}, function (busca) {
  $('#ret-ajax').html(busca);
 });
});

Ajax

$char = $_POST['val'];
$body = '';
if($char == 1){
     $body .= '<textarea name="curso" rows=4></textarea>';
  }
   elseif($char == 2){
     $body .= '';
}

$retorno = $body;
    
asked by anonymous 22.11.2016 / 12:55

3 answers

1

You had a serious error in your html, there can not be two identical id's ( #estuda ), you can put it as a class ( .estuda ), do the following:

$('.estuda').change(function () {
  var chars = parseInt(this.value);
  if(chars === 1) {
    $('#ret-ajax').html('<textarea name="curso" rows=4></textarea>');
    return;
  }
  $('#ret-ajax textarea').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>2.3-Vocêestuda?</p><inputtype="radio" name="estuda" class="estuda" value="1" required=""> Sim 
<input type="radio" name="estuda" class="estuda" value="2" required=""> Não 
<div id="ret-ajax"></div>
    
22.11.2016 / 13:00
1

You should not use the same id for two different elements. link

That said, I suggest you remove the $.post function and make the comparison in the JavaScript itself. Something like:

$('#estuda').change(function () {
  var chars = (this.value);
  if(chars == 1)
     $('#ret-ajax').html('<textarea name="curso" rows=4></textarea>');
  else
     $('#ret-ajax textarea').remove();
});
    
22.11.2016 / 13:03
1
The id attribute must be unique, but you can get the entries by name , add a listener for each radio button and create a textarea if it is option 1. With pure Javascript can be Something more or less ..

// obtém todas os elementos com name estuda
var entradas = document.getElementsByName("estuda");

// adiciona um listener change para cada um 
for (var i = 0; i < entradas.length; i++) {
  entradas[i].addEventListener("change", criar);
}

// funcao que verifica o valor do radio 
function criar() {
  if (this.value == 1)
    document.getElementById("ret-ajax").innerHTML = '<textarea name="curso" rows=4></textarea>'; // innerHTML adiciona um conteudo HTML ao elemento
  else
    document.getElementById("ret-ajax").innerHTML = '';
}
<p>2.3 - Você estuda?</p>
<input type="radio" name="estuda" id="estudaS" value="1" required="">Sim
<input type="radio" name="estuda" id="estudaN" value="2" required="">Não
<div id="ret-ajax"></div>
    
22.11.2016 / 13:09