Working in html inside a variable

Asked

Viewed 74 times

0

I have a variable that contains a string with an HTML code, within that code I have some <input type="text">. What I need and I couldn’t find a solution, is to change the value of those inputs(quantity of inputs varies) within this variable.

I basically wanted to do something like this:

$("input[type=text][name=" + i + "]").val();

the only difference is that I want to do this with the HTML that is inside the variable var html

  • You selected this html with jquery or it is a string with html code?

  • @Wictorchaves is a string that contains HTML, pull this html from the database

  • 1

    It would be a good idea for you to post a question like the HTML that is in this variable and what may vary in it, because there may be Ids classes or attributes that indicate a more appropriate answer to your case.

1 answer

2


You can do this way, the code is commented explaining its operation.

//String com o html
var html = '<input type="text" name="fname"><input type="text" name="fname"><input type="text" name="fname"><br>dfsdfs sdf sdf sdfsd fsdf sdfd sdfsfds';

//Coloca a string com o html dentro de uma div de uma forma que o jquery consiga manipular como se estivesse selecionado algum elemento da pagina
var $html = $('<div />',{html:html});

//Pecorre todos os elementos do tipo "text" dentro da selecao
$html.find('[type="text"]').each(function(i) {
  $(this).attr('name', i);//Coloca a numeracao a cada elemento
});

//Joga o html na div "inputs" que criei como exemplo
$('#inputs').append($html.html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputs">
</div>

Browser other questions tagged

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