Search code examples
javascriptformshyperlinkclickfill

Fill 2 Form Input Fields With 1 Hyperlink Using Javascript


I'm sorry if this has been answered somewhere as it's quite a simple issue but I can't seem to find anything which is completely relevant and I'm very new to coding and javascript.

I have a form like this:

<form name="myform" method="post" action="">
<input type="text" name="word" id="word" value="" />
<input type="text" name="url" id="url" value="" /> 
</form>

and I'm currently using some inline javascript on a hyperlink to fill the 'word' input with a database value like this (this is within a php function):

<a id="fill" href="#" onclick="document.myform.word.value=  &apos;'. $aMessages['name'] .'&apos; ">fill form</a>

However I also want this hyperlink to fill the 'url' input with a different database value which would be with this javascript:

onclick="document.myform.url.value=  &apos;'. $aMessages['url'] .'&apos;

but I'm not sure how to make that one hyperlink fill both form inputs at the same time. If this is the wrong way of achieving what I want and there is another better way to do this then please let me know.

Thank you for your time!

Matt


Solution

  • You can write two javascript codes in one onclick. Like:

    <a id="fill" href="#" onclick="javascript:document.myform.word.value=  &apos;'. $aMessages['name'] .'&apos; document.myform.url.value=  &apos;'. $aMessages['url'] .'&apos;">fill form</a>
    

    But I'd recommend doing it this way:

    function doUpdate()
    {
    document.myform.word.value=  "'. $aMessages['name'] .'";
    document.myform.url.value=  "'. $aMessages['url'] .'";
    }
    

    And on your link do this:

    <a id="fill" href="#" onclick="javascript:doUpdate()">fill form</a>