Search code examples
javascripthtmlfunction-parameter

html sending parameters to function from id


I'm an absolute beginner and tried to find similar questions but couldn't. Apologies if this has been answered previously. In my assignment we need to create a form with 2 text fields and 1 button. The fields are for height and width and the idea is that onclick on the button will send the 2 parameters to a function that will change the height + width attributes for a photo. I know I'm doing something wrong because the picture simply disappears. Ideas? Thanks!

<html>
    <head>
        <script>

            function borderResize(height1, width1)
            {
                document.getElementById('Amos').height = height1;
                document.getElementById('Amos').width = width1;
            }
        </script>

    </head>

    <body>

        <img src="Amos.jpg" id="Amos" />
        <form>
            <input type="text" id="height" placeholder="Height" />
            <input type="text" id="width" placeholder="Width" />
            <input type="button" value="click!" onclick="borderResize('height.value', 'width.value')"/>
        </form>
    </body>
</html>

Solution

  • When you write

    onclick="borderResize('height.value', 'width.value')"
    

    in means that on click borderResize function will be invoked with two string arguments, literally strings "height.value" and "width.value". In your case you want something like this

    onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
    

    In above case you are selecting element from DOM using getElementById method and then read its value property.