javascript passing text input to a onclick handler

2019-02-03 09:09发布

Lets say I have a form as below. How do I pass the value in the textbox named "configname" to the onclick function handler??

<form id="loadconfigform">
        Config Name: <input type="text" name="configname" />
        <input type="button" value="Submit" onclick="onLoadConfigPress(configname)" />
    </form>

3条回答
Bombasti
2楼-- · 2019-02-03 09:29
<form id="loadconfigform">
        Config Name: <input type="text" name="configname" />
        <input type="button" value="Submit" onclick="onLoadConfigPress(document.getElementsByName('configname')[0].value)" />
    </form>

Simply call it using its name. I'd recommend using ID though.

This won't work if you have other elements with the same name, so do use ID like the other answers have suggested.

查看更多
倾城 Initia
3楼-- · 2019-02-03 09:42

Give an id to input field:

<input type="text" id="configname" name="configname" />

Now modify click handler as follows:

<input type="button" value="Submit" 
  onclick="onLoadConfigPress(document.getElementById('configname').value)" />

Or if you have only one form on that page, you could also use forms array:

<input type="button" value="Submit" 
  onclick="onLoadConfigPress(document.forms[0].configname.value)" />
查看更多
甜甜的少女心
4楼-- · 2019-02-03 09:48
<form id="loadconfigform">
   Config Name: <input type="text" id="configname" name="configname" />
   <input type="button" value="Submit"
     onclick="onLoadConfigPress(document.getElementById('configname').value);" />
</form>
查看更多
登录 后发表回答