Get input html filled with jQuery

Asked

Viewed 202 times

1

I need to take html from input as text, like this:

var exemplo = 'input type="text" name="input" id="input"';

However, I need to get the input filled, would be like this:

var exemplo = 'input type="text" name="input" id="input" value="VALOR QUE ESCREVI"';

It is possible to do?

1 answer

2


You can do it this way:

function tag(){
   var exemplo = $("#input")  // pega o elemento
   .attr("value", function(){ return this.value }) // insere o atributo com o valor atual inserido
   .prop('outerHTML'); // retorna o HTML em forma de string

   console.log(exemplo);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Escreva alguma coisa no campo:
<br>
<input type="text" name="input" id="input">
<br>
<button onclick="tag()">Pegar string</button>

If you want without the delimiters < and >, use exemplo.replace(/<|>/g, "");:

function tag(){
   var exemplo = $("#input")  // pega o elemento.
   .attr("value", function(){ return this.value }) // insere o atributo com o valor atual inserido
   .prop("outerHTML"); // retorna o HTML em forma de string

   exemplo = exemplo.replace(/<|>/g, "");

   console.log(exemplo);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Escreva alguma coisa no campo:
<br>
<input type="text" name="input" id="input">
<br>
<button onclick="tag()">Pegar string</button>

  • top bro, thanks! And if I want a form all filled in this way, I will need to input by input?

  • Then I’d have to see how.

Browser other questions tagged

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