如何使用ajax从一个文本框值自动填充另一个文本框值

时间:2013-11-13 05:55:35

标签: javascript php jquery html5 codeigniter

您好我想在我们输入公司名称时将搜索框设置为只拨打网站,它会自动填写另一个文本框中的城市名称

                                                     “onfocus =”javascript:this.value ='';“onblur =”javascript:if(this.value ==''){this.value ='';}“onKeydown =”javascript:if(event.keyCode = = 13)serachProduct();“/>                                              
                <div class="textCurve1" style="float:left;margin-left:10px;">
                    <div class="selectsSR">
                        <input type="text" id="cityname" name="cityname" onKeydown="javascript: if (event.keyCode==13)serachProduct();" value="<?php if(isset($cityName)){echo ucfirst($cityName);}else{echo"City";} ?>" onfocus="javascript:this.value='';" onblur="javascript: if(this.value==''){this.value='<?php if(isset($cityName)){echo ucfirst($cityName);}else{echo"City";} ?>';}"/>
                    </div>
                </div>

SELECT select_company.company_name,select_city.city FROM select_company LEFT JOIN select_city ON(select_company.city = select_city.id)WHERE select_company.company_name LIKE“。$ this-&gt; db-&gt; escape($ company。”%“ )“。限制10“

想要自动更新城市字段文本框

1 个答案:

答案 0 :(得分:1)

你可以做的是你可以在第一个文本框的keyup,keydown或onblur上发出ajax调用。

将第一个文本框数据传递给ajax php文件

现在搜索您的公司数据库,查找公司是否在那里,以及数据库中是否有相关城市。

选择城市名称并在ajax.php文件中回显它以发送响应。

获得响应时,只需将第二个文本框的innerHtml替换为响应中的城市名称。

我已经给你基础逻辑自己尝试了,你也可以在网上找到例子,如果你不能达到结果,请发布你试过的代码,我肯定会帮你的。

以下是ajax功能

function loadcity(val) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            var res = xmlhttp.responseText;// The response contain the city name returned from the php file from the query result 
            document.getElementById('citytextbox').value=res;// insert the city name in the city text box
            document.getElementById('loaderdivid').style.display='none';//hide loader when you got the response  
        }
    }
    var url = 'ajax.php'; // Url for the ajax.php file where you will fire query to get the city name 

    //Before response
    //Write the code if you want to add some loder image untill the response comes
    document.getElementById('loaderdivid').style.display='block';// show the loader when the request is made 

    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("data=" + val);
}

您已经将查询写入ajax.php文件

并传递函数中的第一个文本框值,您可以通过代码中的注释来理解