Reputation: 85
I used pure HTML to compose a text message SMS by simply adding a special href value where normally regular URLs go like below:
<a href="sms:+33xxxxxxxx?body=Hello!">
Compose SMS!
</a>
I created a text field to enter the phone number.
<input type="text" id="numPhone" style="width: 203px;">
I want the SMS HTML code use the value of this field so I tried like this:
<script type="text/javascript">
var phone = $('#numPhone').val();
</script>
<a href="sms:${phone}?body=Hello!">
Compose SMS!
</a>
But when I click to compose SMS, I get a empty recipient. Please any help to use the field value in SMS code!
Upvotes: 2
Views: 3278
Reputation: 1636
You can only do things like "${phone}
" in JS template literals. That syntax is not part of HTML. Additionally, it would have to use an event listener to update the link whenever the user updates the input field, and not just when the page initially loads. You would have to do something like this.
<a id="composeSMS">
Compose SMS!
</a>
<script type="text/javascript">
$('#numPhone').on('input', function() {
$('#composeSMS').attr('href', 'sms:' + this.value + '?body=Hello!');
});
</script>
Upvotes: 2
Reputation: 68923
You can use data-
attribute to set the known part of the href
. Then set the value of href
in JavaScript with the value of data-
and dynamic part:
function updateLink(input){
var phone = $(input).val();
$('#compose').attr('href', $('#compose').attr('data-href1') + phone + $('#compose').attr('data-href2'));
}
updateLink('#numPhone');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="compose" href="" data-href1="sms:" data-href2="?body=Hello!">
Compose SMS!
</a>
<input type="text" id="numPhone" style="width: 203px;" value="+33xxxxxxxx" oninput="updateLink('#numPhone')">
Upvotes: 1