Concatenate a link within a href attribute with a variable?

Asked

Viewed 8,073 times

2

I wanted to know how to concatenate a link inside an attribute href with a variable? Observation has to be something 'inline'. I use a platform that doesn’t let me use scripts inside the page so the reason of inline.

Example:

var teste = [x];
<a href="#" onclick="window.open('http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_COD_UNI=',teste)" target"_blank">vai</a>

The way out should be:

http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_COD_UNI=[x]

My code is wrong in the organization of elements or quotes in the wrong place so disregard that part. I need a hint of how I would put this together.

3 answers

7


Set a global variable and use the operator + to concatenate:

<script>
var teste = "blabla";
</script>

<a href="#" onclick="window.open('http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_COD_UNI=' + teste)" target"_blank">vai</a>

Demonstration

Concatenation will occur at the moment of the click.

  • Can place an example in Jsfiddle?

  • Yes, I edited the answer with the link

  • Your answer was the one that got closer, so I’ll take it for granted. Thanks @bfavaretto

2

You can create an Hidden input and set a value something like:

<input type="hidden" name="teste" id="name" value="qualquer-valor"/>

Then you take value and concatenate in your link something like:

onclick="window.open('http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_COD_UNI=' + document.getElementById('teste').value)"

1

You can use "Eval", but its use is not recommended for security reasons.

Thus:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
        var teste = 'blah';
    </script>
    <a href="#" onclick="eval('window.open(\'http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_COD_UNI=\' + teste)')" target"_blank">vai</a>
</body>
</html>

Beware of using Eval. As I said, it brings security holes but, as you said the code has to be inline, it solves.

  • I have not thought about this method but it seems to be interesting this information goes straight to an email, it may have any problems?

  • 1

    No need to use Eval to make a simple concatenation!

  • @bfavaretto hahaha, you’re absolutely right, I traveled in mayonnaise! = D

Browser other questions tagged

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