How to pass a form input value into a JavaScript function

后端 未结 6 1349
野的像风
野的像风 2020-12-24 08:01

I have a generic JavaScript function which takes one parameter

function foo(val) { ...} 

and I want to call the function when submit a form

相关标签:
6条回答
  • 2020-12-24 08:27

    Use onclick="foo(document.getElementById('formValueId').value)"

    0 讨论(0)
  • 2020-12-24 08:28

    Well ya you can do that in this way.

        <input type="text" name="address" id="address">
            <div id="map_canvas" style="width: 500px; height: 300px"></div>
        <input type="button" onclick="showAddress(address.value)" value="ShowMap"/>
    

    Java Script

    function showAddress(address){
    
        alert("This is address :"+address)
    
    }
    

    That is one example for the same. and that will run.

    0 讨论(0)
  • 2020-12-24 08:34

    There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.

    HTML:

    <form>
        <input type="text" id="formValueId" name="valueId"/>
        <input type="button" id="myButton" />
    </form>
    

    JavaScript:

    $(document).ready(function() {
        $('#myButton').click(function() {
          foo($('#formValueId').val());
        });
    });
    
    0 讨论(0)
  • 2020-12-24 08:39

    More stable approach:

    <form onsubmit="foo($("#formValueId").val());return false;">
    <input type="text" id="formValueId"/>
    <input type="submit" value="Text on the button"/>
    </form>
    

    The return false; is to prevent actual form submit (assuming you want that).

    0 讨论(0)
  • 2020-12-24 08:40

    Give your inputs names it will make it easier

    <form>
    <input type="text" id="formValueId" name="valueId"/>
    <input type="button" onclick="foo(this.form.valueId.value)"/>
    </form>
    

    UPDATE:

    If you give your button an id things can be even easier:

    <form>
    <input type="text" id="formValueId" name="valueId"/>
    <input type="button" id="theButton"/>
    </form>
    

    Javascript:

    var button = document.getElementById("theButton"),
    value =  button.form.valueId.value;
    button.onclick = function() {
        foo(value);
    }
    
    0 讨论(0)
  • 2020-12-24 08:45

    It might be cleaner to take out your inline click handler and do it like this:

    $(document).ready(function() {
        $('#button-id').click(function() {
          foo($('#formValueId').val());
        });
    });
    
    0 讨论(0)
提交回复
热议问题