How to rename an input from a selector?

Asked

Viewed 32 times

0

I would like to know which script is able to rename an input by choosing a selector. My input name is THUMB, if the person marks the first option, but I would need the input name to change if I selected the second option for something like THUMB 2, how can I do that? Thank you very much

<form method="post">
    <input type="text" class="restrict" name="thumb">
    <input type="submit" onclick="replaceURL()" >
<select name="seletor">
    <option value="op1">Opção Um</option>
    <option value="op2">Opção2</option>
    </select>
    </form>

 

2 answers

1


You can do so (I will leave commented in the code what was done):

// aqui associa o evento "change" do select. Para facilitar o seletor do elemento select, adicionei a ele um id "nomes
document.getElementById('nomes').addEventListener('change', function() {
   // obtem o elemento do botão. Para facilitar, adicionei um id "btn"
   var botao = document.getElementById("btn");

   // muda a propriedade "name". "this" representa o select, dentro da function associada ao evento change, o "value" é o valor selecionado no option
   botao.setAttribute("name", this.value);

   // aqui só para mostrar que o valor foi alterado
   alert("Name alterado para " + botao.getAttribute("name"));
});
<input type="text" id="btn" class="restrict" name="thumb" />
<input type="submit" onclick="replaceURL()"/>

<select id="nomes" name="seletor">
    <option value="op1">Opção Um</option>
    <option value="op2">Opção2</option>
</select>

0

You must do in the change of the value of select, following example

function alterarNomeInput() {
  const { value } = event.target;
  const inputAlvo = document.querySelector("#inputAlvo");
  inputAlvo.name = value === "op1" ? "thumb" : "thumb1";
  
  alert(inputAlvo.name);
}
<body>
  <form method="post">
    <input type="text" class="restrict" id="inputAlvo" name="thumb">
    <input type="submit">
    <select name="seletor" onchange="alterarNomeInput()">
        <option value="op1">Opção Um</option>
        <option value="op2">Opção2</option>
    </select>
  </form>
</body>

Browser other questions tagged

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