Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
Javascript passing variable from on change to outside function using setAttribute and dropdown Select

I'm converting a field in one of my tables from Free text to a dropdown with a set list of options. I then assign the selected value inside an onchange function, which is working correctly, however when I then try to assign this variable to the value element, using setAttribute, it isn't able to find it. I tried researching how to access variables outside of the scope of a function, but I wasn't able to link this to the set attribute method I'm using. If there is a better way to do this I will try this also.

The code below is called when the edit button is clicked on a form, if I remove all of the dropdown stuff and just use the free hand text of x.setAttribute("value",role) then it will pass the value through to the AJAX call no problem. What am I doing wrong? Thanks.

  function editProcess(row,id,name,username,email,role){
      //WORKING
      $( "#name"+id+"" ).empty();
      var x = document.createElement("input");
      x.setAttribute("type", "text");
      x.setAttribute("class", "form-control");
      x.setAttribute("value", name);
      x.setAttribute("required", "true");
      x.setAttribute("style", "padding:0");
      x.setAttribute("name","name");
      x.setAttribute("onInput","clearPopUps()");
      $( "#name"+id+"" ).append(x);


      //NOT WORKING
      myParent = document.body;
      //Create array of options to be added
      var roleArray = ["Admin","Officer","Manager"];
      $( "#role"+id+"" ).empty();
      //Create and append select list
      var x = document.createElement("select");
      myParent.appendChild(x);

      //Create and append the options
      for (var i = 0; i < roleArray.length; i++) {
          var option = document.createElement("option");
          option.value = roleArray[i];
          option.text = roleArray[i];
          x.appendChild(option);       
      }
      $('#role').on('change', function() {
          role = $('#role option:checked').val();
          this.selectedOptions[0].setAttribute('value', role);
          x.setAttribute("value", role);
          console.log(x);
      });
      x.setAttribute("type", "text");
      x.setAttribute("class", "form-control");
      //x.setAttribute("value", selectedRole);
      x.setAttribute("required", "true");
      x.setAttribute("style", "padding:0");
      x.setAttribute("name","role");
      x.setAttribute("onInput","clearPopUps()");
      $( "#role"+id+"" ).append(x);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You set the value of a dropdown using the val() method in jQuery or the value property in vanilla javascript.

$("#using-jQuery").on("click", () => $("#test").val("2") )


document.getElementById("using-vanilla").addEventListener("click", 
     () => document.getElementById("test").value = "3" )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>


<button id="using-jQuery">Set to 2 using jQuery</button>
<button id="using-vanilla">Set to 3 using Vanilla JS</button>

Using setAttribute will not have the same effect!

document.getElementById("using-vanilla").addEventListener("click", 
    () => document.getElementById("test").setAttribute("value","3") )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>


<button id="using-vanilla">Set to 3 using Vanilla JS + setAttribute</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda