Cyberlacs
Cyberlacs

Reputation: 201

How to concatenate fields in the middle of a string url

In a jquery onclick function I want to be assigned to an api, but first I have to perform the concatenation of the address with some fields value, as in the example below.

The problem is that I am not performing concatenation correctly.

This concatenation is incorrect.

var url = "https://api.whatsapp.com/send?phone=55"+ document.getElementById('Phone').value +" &text=Hellow,%20" + document.getElementById('Copy').value;

JQuery function

    $("#fidelizar").click(function () {

        var url = "https://api.whatsapp.com/send?phone=55"+ document.getElementById('Phone').value +" &text=Hellow,%20" + document.getElementById('Copy').value;

        window.open(url, '_blank');
    });

Upvotes: 0

Views: 1954

Answers (2)

Jakub Kawalec
Jakub Kawalec

Reputation: 69

Another issue you might be having is that the elements you are retrieving don't have the value attribute. You might want to try console logging those values to make sure they're not actually undefined first. If those aren't input text node types that might be the issue. You'll have to use nodeValue or textContent instead if you want to get the current text value of the element.

Upvotes: 1

Kiran Shahi
Kiran Shahi

Reputation: 7970

Try some thing like this var url =https://api.whatsapp.com/send?phone=55${$('#Phone').val()} &text=Hellow,%20${$('#Copy').val()}; . It is string interpolation here you can embed expressions within normal strings.

$("#fidelizar").click(function () {

        var url = `https://api.whatsapp.com/send?phone=55${$('#Phone').val()}&text=Hellow,%20${$('#Copy').val()}`;

        window.open(url, '_blank');
        console.log(url);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Phone" type="text">
<br/>
<input id="Copy" type="text">
<br/>
<button id="fidelizar">Click Me</button>

Upvotes: 3

Related Questions