.val() does not work on the textarea tag

Asked

Viewed 63 times

0

I’m taking a data that is in an attribute of my select-option (date-observation), so far so good, however when I try to pass this value to my textarea the value is not printed, just on the console, anyone knows explain to me why that? Follows the code:

 <select name="modelo" id="modelo" class="form-control">
   <option value="" selected disabled>Selecione</option>
   @foreach($modelos as $modelo)
    <option value="{{ $modelo->id }}" data-observacao="{{ $modelo->corpo}}"> {{ $modelo->titulo }} 
    </option>
   @endforeach
 </select>

 <div class="col-md-12 col-sm-12 mt-3" id="div-observacao">
  <label for="">Observação</label>
  <textarea class="form-control" name="observacao" id="observacao" rows="3"></textarea>
 </div>
function removeTag(dataObservacao){
    dataObservacao = dataObservacao.replace("<p>","");
    dataObservacao = dataObservacao.replace("</p>","");
    return dataObservacao;

};

$("#modelo").on("change", function (event) { 
    let dataObservacao = $("#modelo").find("option:selected").data("observacao");
    dataObservacao = removeTag(dataObservacao);
    console.log(dataObservacao);
    console.log($("textarea[name='observacao']").val(dataObservacao));
    $("textarea[name='observacao']").val(dataObservacao);

});
  • 1

    Here it worked normal. Now, since the textarea has an id, you can use it in the selector: $("#observacao") instead of $("textarea[name='observacao']").

  • Remembering that the script should be at the end of body... See this Fiddle how it works properly.

  • I agree with Sam. If in the console you are printing the value and not in the field. He is not finding the textarea object[name=note]

1 answer

1


The value is not printing because the textarea is not an input, but an element, you cannot simply set a $('textarea').val(); you need to exchange what is inside your content that way.

//Arqivo JavaScript
$(document).ready(function(){

	var valor = "Algum texto somente para completar a text area";
    
        //Eu estou pegado elemento pelo ID do textarea que eh #alpha
	$('#alpha').text(valor);


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<textarea id="alpha"></textarea>

Stack Overflow Brasil staff...

stop denying questions that you cannot answer, have more patience with those who are learning.

  • It worked, thank you very much!!!!

  • You can close this topic by evaluating this answer as correct. I’m glad it worked.

Browser other questions tagged

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