Javascript concatenated into input name

Asked

Viewed 459 times

2

Is there any way to concatenate a variable javascript next to a input?

That one input hidden i would submit together to an HTML form

For example:

<script type="text/javascript">
    var strConcatenada = "STR_VARIAVEL.";
</script>

<input type="hidden" name="<%=strConcatenada%>W_TESTE_AUTO" value="1">
  • What is this template language?

  • @Sergio this example would be in an html page

  • Okay, and where does it come from <%=? are using some template-engine?

  • Just this is my doubt, I looked for some examples and saw that used this format <%= to present variables javascript, but I really didn’t succeed in this way

  • Leonardo’s answer already explains how you can do it. Regarding this syntax <%=%> this is used in templates. Often on the server. But now I realize you don’t know what it is, so you can take it out of the question because it only confuses :)

2 answers

2


You first have to create an ID for your input, assign it to a variable:

var element = document.getElementById("inputConcatenar");

Then you assign to the name a new value, in which case I used the Replace that will search for a string that you pass and replace with another.

element.name = element.name.replace("strConcatenada", strConcatenada)
console.log(element.name);

I made it as simple as possible, the result is this, follows the console.log name. If you want to remove the "<% %>" just pass <%strConcatenated%> to the Replace , getting like this:

replace("<%strConcatenada%>", strConcatenada)

<input id="inputConcatenar" type="hidden" name="<%=strConcatenada%>W_TESTE_AUTO" value="1">

<script type="text/javascript">
    var strConcatenada = "STR_VARIAVEL.";
    var element = document.getElementById("inputConcatenar");
    element.name = element.name.replace("strConcatenada", strConcatenada)
    console.log(element.name);
    
</script>

  • understood and it worked! hehe, thanks!

1

You can run a javascript code to change the name when loading the page:

    <form onsubmit="myFunction()">
      <input type="hidden" name="_TESTE_AUTO" ID="_TESTE_AUTO" value="1">
      <input type="submit">
    </form>
<script>
   var strConcatenada = "STR_VARIAVEL.";
   var input = document.getElementById("_TESTE_AUTO");
   input.name = strConcatenada + input.name;
</script>

Browser other questions tagged

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