How to pass a JSP-mounted list and traverse it in a JS function by extracting its values?

Asked

Viewed 32 times

0

I have a jsp page of a legacy code. A piece of it is as follows:

<form name="frm_pedido" method="post" action='<%=(flgPrimeiroPedido ? "/pedidoConfirmaEndereco.jsp" : "finaliza_pedido.jsp")%>' onsubmit="javascript: return false;">
    <input type="hidden" name="sem_inter2" value="<%=erro2%>">
    <input type="hidden" name="list_sem_inter2" value="<%=areasFuncionaisSemInter%>">
</form>

This variable areasFuncionaisSemInter is a Java ArrayList of Strings. The problem is that when clicking a button on the page, I need to pass this list to a JS function and extract its values. The function called when clicking the button is the VerificaInter(). I tried the following:

function VerificaInter() {

   if(document.frm_pedido.sem_inter2.value == 'true') {
      var iterator = document.frm_pedido.list_sem_inter2.values(); 
      alert('Os valores da lista sao:\n');
      iterator; // nao funcionou dessa forma...
      // logica pra iterar na lista e exibir os valores
      return false;
   }
   else {
      return true;
   }

}

This variable iterator didn’t work that way and I couldn’t iterate over the list and extract its values. What I’m doing wrong and how I could perform this operation?

1 answer

0

Assuming your Hidden "list_sem_inter2" is returning the list in this format:

<input type="hidden" name="list_sem_inter2" value="[P1, P2, P3]">

Your JS will get this list as a String, so just do:

var lista = document.frm_pedido.list_sem_inter2.value.replace("[","").replace("]","").split(",");
alert('Os valores da lista sao: '+lista.length);
let iterator;
for(let i=0; i < lista.length; i++) {
    iterator = lista[i];
    alert(iterator);
}
return false;

Browser other questions tagged

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