简体   繁体   中英

How to connect a Javascript/Jquery function with a html form?

i want to create a form that extracts email addresses from input text , i know there is a lot of scripts which do this easily , but i want to create one by myself .
So i read , searched and tried but i couldn't see a result . here is my code , what is the problem ?

<html>
  <head>
    <script type="text/javascript">

    function extractEmails ( text ){
    return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
    }

    // EXAMPLE #1
    var emails = extractEmails ( HugeListWithBulkTextIncludingEmailAddresses );
    document.write ( emails.join('\n') );


    // EXAMPLE #2 (jQuery)
    $(function(){
    $('#eform').submit(function(){
    $('#extractedemails').val( extractEmails($('#input').val() ).join('\n'));
    return false;
    });
    });

    </script>
  </head>

<body>
    <form name="myform" id="eform" action="javascript:extractEmails()">
        <input type="text" name="firstname">
        <input name="Submit"  type="submit" value="Update"/>
    </form>
    <textarea id="extractedemails">
    </textarea>
</body>
</html>

i suggest you should use this :

onsubmit="return extractEmails()"

cause i noticed that your submit button doesnt call your function.

instead of :

action="javascript:extractEmails()"

try this form, you should also have an id to your input field :

<form name="myform" id="eform" onsubmit="return extractEmails()">
   <input type="text" name="firstname" id = "input">
   <input name="Submit"  type="submit" value="Update"/>
</form>

below is a little program i created, i'm not quite sure of what you want to achieve in your function but hopefully this might help you a little. :)

    <html>

<head>
    <script type="text/javascript">

        function extractEmails(){

            var input = document.getElementById('input').value;
            input.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);

            var textarea = document.getElementById('extractedemails');
            textarea.value = input;

        }

    </script>
  </head>

<body>
    <form name="myform" id="eform" onsubmit = "return extractEmails()">
        <input type="text" name="firstname" id = "input">
        <input name="Submit"  type="submit" value="Update"/>
    </form>
    <textarea id="extractedemails">
    </textarea>
</body>
</html>

it is based on your html happy coding :D

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