简体   繁体   中英

How do I pass a function as parameter in HTML?

Im new to web development, I apologize in advance. I have a form where the user can write a simple message and then the browser will open whatsapp web containing the message previously written. I need to pass a function to the action="" of the form to make this work. I can't figure it out.

What I tried and worked so far:

<form id="user_form" action="https://api.whatsapp.com/send?phone=123456789&text=Hello" method="post" enctype="text/plain">
            <textarea id="msg" cols="30" rows="10" placeholder="Message ..."></textarea>
            <input type="submit" value="connect us" class="btn">
</form>

It works just fine, but i want the text parameter (https://api.....text=VARIABLE) to be the message that the user writes.

I tried to do this, but doesn't seem to work:

<form id="user_form" onSubmit="return sendMsg()" method="post" enctype="text/plain">
            <textarea id="msg" cols="30" rows="10" placeholder="Message ..."></textarea>
            <input type="submit" value="connect us" class="btn">
</form>

<script>
        function sendMsg(){
            var actualMsg = document.getElementById("msg").value;
            document.user_form.action = "https://api.whatsapp.com/send?phone=123456789&text=Hello";
            return false;
        }
</script>

What you need is an event listener that updates the value of your action attribute.

 const url = 'https://api.whatsapp.com/send?phone=123456789&text='; document.getElementById('msg').addEventListener('keyup', (e) => { document.getElementById('user_form').setAttribute('action', url + e.target.value); console.log(document.getElementById('user_form').getAttribute('action')); })
 <form id="user_form" action="" method="post" enctype="text/plain"> <textarea id="msg" cols="30" rows="10" placeholder="Message..."></textarea> <input type="submit" value="connect us" class="btn"> </form>

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