Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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&#8230;..text=VARIABLE) to be the message that the user writes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading