简体   繁体   中英

HTML & PHP - Type a telephone number, and call it

I wrote a code, but it doesn't work.

<?php
$number = $_GET["tel"];
echo '<form action="/" method="get">
         <a>Enter the phone number, what you want to call</a>
         <input type="tel" name="tel"/>
         <input type="submit" onclick="call()" value="Call"/>
      </form>
      <script>
          function call() {
              window.open("tel:$number");
          }
      </script>
';

In PHP, variables in strings are only allowed in double quotes . Change your single quotes to double quotes to make the $number work in the string.

See this SO post for more details.

Therefore, your code should look like:

<?php
    $number = $_GET["tel"];
    echo "<form action='/' method='get'>
                <a>Enter the phone number, what you want to call</a>
                <input type='tel' name='tel' />
                <input type='submit' onclick='call()' value='Call' />
            </form>
            <script>
                function call() {
                    window.open('tel:$number');
                }
            </script>
        ";
?>

But this code is strange. Here's how it flows:

  1. get $_GET variable tel (assuming form has already been sent)
  2. echo out the form
  3. on form submit, the number in the $_GET["tel"] is visited, not the number in the form
  4. then, the form gets submitted, but this doesn't work because the window.open() has occurred already

Here's an alternate solution without PHP (and without an actual form send):

<form action='/' method='get'>
<a>Enter the phone number, what you want to call</a>
    <input type='tel' name='tel' />
    <input type='submit' onclick='call();return false;' value='Call' />
</form>
<script>
    function call() {
        var number = document.querySelector("input[name=tel]").value;
        window.open('tel:' + number);
    }
</script>

See it working at JSFiddle.net .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM