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


How to fill automatically another text box value from one text box value using ajax

嗨,当我们输入公司名称时,我想放置搜索框,就像拨号站点一样,它会自动在另一个文本框中填写城市名称

" 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_company左侧选择select_company.COMPANY_NAME,select_city.CITY加入select_city ON(select_company.CITY=select_city.ID),其中select_company.COMPANY_NAME如".$this->db->escape($company"。%'").'"限制 10"

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

你可以做的是,你可以在第一个文本框的键上、键下或模糊上触发 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 文件

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

相关文章: