如何在输入键按下事件中获取输入值?

时间:2014-03-26 06:16:20

标签: javascript php jquery

我想在没有页面刷新的情况下按Enter键提交表单。

这是我的代码。

php code。

<form action="profile/update_profile" method="post" id="business_name_data">
 <input type="hidden" name="business_name" id="business_name"/>
</form>

update_profile函数

public function update_profile()
{
  json_encode($this->input->post('business_name'),true);
}

js code

 jQuery(document).keyup(function(e){

   e.preventDefault();

    if(e.which == 13){
    jQuery.ajax({
                    type : "post",
                    url :  "../profile/update_profile",
                    data : "business_name="+jQuery("#business_name").val(),
                    dataType: "json",
                    success : function(msg) 
                    {    
                        console.log(msg);
                            //jQuery("div").find(".category_view").html(msg);
                            //jQuery("#1").css("visibility","visible");
                    }
          });
             }
          });

我正在尝试传递输入值。但它会输出null。 请帮忙。

4 个答案:

答案 0 :(得分:0)

试试这个

您必须将值设置为隐藏元素

<input type="hidden" value="busineesname" name="business_name" id="business_name"/>

jQuery(document).keyup(function(e){
    e.preventDefault();
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 13){
    jQuery.ajax({
               type : "post",
               url :  "../profile/update_profile",
               data : {"business_name":jQuery("#business_name").val()},
               dataType: "json",
               success : function(msg) 
               {    
                        console.log(msg);
               }
             });
           }
        });

DEMO

答案 1 :(得分:0)

首先是第一件事 在if条件之前提醒值为:

alert(jQuery("#business_name").val());// check this if it gives the value

如果它给出了值并放置echo,因为您没有echoprint_r

update_profile函数中的

public function update_profile()
{
   echo json_encode($this->input->post('business_name'),true);
   //add the echo and check  

}

希望这会有所帮助!

答案 2 :(得分:0)

首先,您需要回显update_profile()方法

中的值
public function update_profile()
{
  echo json_encode($this->input->post('business_name'),true);
}

下一步是检查输入密钥是否已按下,或尝试此操作,同时尝试将输入字段business_name中的值打印到控制台以查看其是否有值或不

jQuery(document).keyup(function (e) {
    e.preventDefault();
    if (e.keyCode == 13) {
        jQuery.ajax({
            type: "post",
            url: "../profile/update_profile",
            data: {
                "business_name": jQuery("#business_name").val()
            },
            dataType: "json",
            success: function (msg) {
                console.log(msg);
            }
        });
    }
});

答案 3 :(得分:0)

如果您犯了一个错误,并且想要一个可见的文本框,当您点击它时,您想要提交表单而不刷新页面,您可以订阅提交事件

  $(function(){
      $('#business_name_data').submit(function(event){
        alert('your ajax call');
        event.preventDefault();
      });
   });

http://plnkr.co/edit/tbHTjyRKEV0cxraP3R6n?p=preview

相关问题