By the specifications, the attribute name
is invalid in an element <p>
. If your HTML structure is shown in the question, you don’t even need id
nor name
, even because you are repeating the id’s, so you will only get the first one because you should not repeat id’s on the same page. At most you could use the same class
in the elements, if this is of any use. But on the buttons you must convert the id="pegar"
in class so you can differentiate these buttons from others you may have on the page.
Then the HTML of the button would look like this, removing the id
and adding the "catch" class to the list of classes:
<button onclick="pegarDiv()" class="btn btn-primary pegar">Pegar</button>
See that each button is inside a div with the <p>
before, then just use some jQuery methods to get to paragraph text.
Instead of using the attribute onclick
, use a Event Handler, thus:
$(function(){ // aguarda o DOM ser carregado
$(".pegar").on("click", function(){
var valorDaDiv = $(this).closest("div").prev("p").text().trim();
$("#fato").val(valorDaDiv);
$('#modal').modal('hide');
$('#fato').attr('rows','3');
});
});
The .trim()
serves to eliminate blank spaces on text borders.
Testing:
$(function(){ // aguarda o DOM ser carregado
$(".pegar").on("click", function(){
var valorDaDiv = $(this).closest("div").prev("p").text().trim();
console.log(valorDaDiv);
$("#fato").val(valorDaDiv);
// $('#modal').modal('hide');
$('#fato').attr('rows','3');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>desc1</p>
<div>
<button class="btn btn-primary pegar">Pegar</button>
</div>
<hr>
<p>desc2</p>
<div>
<button class="btn btn-primary pegar">Pegar</button>
</div>
<hr>
This foreach is generating
N
elementsp
with the same id. Exchange forclass
. Then you can make onedocument.querySelectorAll('.pegardiv')
and iterate on the result. Look that– DaviAragao