pass javascript variables to form/input fields as onsubmit href link

jake picture jake · Jul 21, 2010 · Viewed 14.7k times · Source

id like to have an input box that a user can enter a search term into that gets passed to maybe a javascript function that then combines some url segments with the search term creating a full url. up until now its been working fine without a form around it, but i would like to add a form to it so users can just hit enter rather than clicking a submit button.

submit button code:

<a href="javascript: void(0)" onClick="this.href = i1 + document.getElementById('intranet').value + i3" target="_blank">
                    <div id="submit" class="out"
                        onMouseOver="document.getElementById('submit').className = 'over';"
                        onMouseOut="document.getElementById('submit').className = 'out';">
                        <span>Submit</span>
                    </div>
                </a>

faulty form/input code:

<form action="" onSubmit="this.href = i1 + document.getElementById('intranet').value + i3; return false;" method="get" target="_blank">
                <input type="text" id="intranet" size="15" value="Search Intranet.."
                    onFocus="document.getElementById('intranet').value = ''"
                    onBlur="document.getElementById('intranet').value = 'Search Intranet..'" / >    
                </form>

possible js function to create url:

<script language="javascript" type="text/javascript">
                    function urlGen(value)
                        {
                            var i1 = "seg1";
                            var i2 = document.getElementById('intranet').value;
                            var i3 = "seg2";

                            var fullURL = i1 + document.getElementById('intranet').value + i3;

                            return fullURL;
                        }
                </script>

Answer

dmitko picture dmitko · Jul 21, 2010

Use form's onSubmit event where set the appropriate data to the intranet's input - don't change this.href (form does not have such attribute). Remember though that JavaScript can be disabled at the client's side. Consider also placing hidden inputs into the form for i1 and i2 and do all combination logics at the server side.

<form action="" onSubmit="urlGen()">
...
</form>

<script language="javascript" type="text/javascript">
                    function urlGen()
                        {


                            var i1 = "urlSeg1";
                            var i2 = document.getElementById('intranet').value;
                            var i3 = "urlSef2";

                            document.getElementById('intranet').value = i1 + i2 + i3;


                        }
                </script>