2015-09-05 72 views
0

我有一个form象下面这样:通过输入值发送给javascript函数

<form onsubmit="doSomething(this.form);"> 
    <input type="text" name="groupName" /> 
    <input type="text" name="groupColour" /> 
</form> 

现在,这并不有一个提交按钮,我知道了。相反,当用户点击输入键时,我希望它触发一个功能。在这个例子中doSomething

现在在函数中,我将执行一个AJAX请求来向数据库插入一条记录,但是我不确定如何访问在我的AJAX函数doSomething的文本字段中输入的值。

如何在提交时将表单的值传递给我的函数?

+0

取决于如果你正在使用jQuery或没有,但查询你想拉从,数据文本框,然后要么使用纯JavaScript有方法.value或jquery有.val()获取输入值 –

回答

1

不要使用onsubmit属性。 Divide your HTML and javascript并使用jQuery处理表单提交。

$("form").on('keypress', function(event){ 
    // if the key is "enter": 
    if(event.which == 13) { 
     // trigger AJAX: 
     $.ajax({ 
      url  : 'post-page.php', 
      type : 'post', 
      // serialize the form (all the form fields will be posted to PHP): 
      data : $(this).serialize(), 
      success : function(response){ 
       // handle server response... 
      } 
     }); 
    } 
}); 
1

HTML & JQuery fiddle

因为你使用jQuery和你想使用Ajax请求,你可以用它代替形式keypress功能,并提交:

HTML:

<input type="text" id="groupName" /> 
<input type="text" id="groupColour" /> 

JS:

$(document).keypress(function(e) { 
    if(e.which == 13) { //When you pressed enter! 
     var name = $('#groupName').val(); 
     var color = $('#groupColour').val(); 

     $.post('insert.php',{name: name, color: color}); 
    } 
}); 

PHP(insert.php):

$name = $_POST['name']; //Get name 
$color = $_POST['color']; //Get color 

//Now you can use $name & $color in insert Query here 

希望这有助于。

1

尝试this它的工作原理..做这个棘手的:-)

<form onsubmit="doSomething();"> 

    <input type="text" name="groupName" /> 

    <input type="text" name="groupColour" /> 

    <input type="submit" 
    style="position: absolute; left: -9999px; width: 1px; height: 1px;" 
    tabindex="-1" /> 

</form> 
1

继承人一个简单的方法..

document.onkeypress =function (e) { 
 
    if (e.keyCode == 13) { 
 
     alert(document.forms['myform'].elements['myinput'].value); 
 
    } 
 
}; 
 
<body> 
 
    <form name="myform"> 
 
    <input name="myinput" type="text" value="awesome"> 
 
    </form> 
 
    </body>