有时候,我们需要去实现选择下拉选之后,页面上的内容根据选择的不同而进行不同的变化。我在这里需要实现的是下拉选选择的是公司,公司有客服人员,选择完公司之后,把客服人员的信息打印出来。
页面的内容代码如下:
<section> <form id="customerForm"> <ul class="page-content"> <li class="inputBox"> <label for="customerId">公司名称:</label> <select class="customerIds"></select> </li> <li class="inputBox"> <label for="customerName">联系人:</label> <input type="text" class="text_add" id="customerName" /> </li> <li class="inputBox"> <label for="customerMobile">联系电话:</label> <input type="text" class="text_add" id="customerMobile"/> </li> <li class="inputBox"> <label for="customerAddress">联系地址:</label> <input type="text" class="text_add" id="customerAddress"/> </li> <li class="inputBox"> <label for="customerWeb">公司官网:</label> <input type="text" class="text_add" id="customerWeb"/> </li> </ul> <div class="btnBox"> <input type="button" class="btn btn-primary ok" onclick="saveOrUpdate()" value="提交"/> <input type="button" class="btn btn-primary btn-warning cancel" value="返回"/> </div> <input type="text" style="display: none;" id="customerId" value="0"> </form> </section>
交互我们使用的是ajax异步请求去加载数据,数据格式为json
页面的ajax代码如下:
$(function () { $.ajax({ type: "get", url: "/test/initData", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { if(data.statusCode==100) { var options = "<option>--请选择公司--</option>"; for (var i = 0; i < data.data.length; i++) { options+="<option>"+data.data[i].companyName+"</option>"; } $(".customerIds").html(options); //活动名称下拉选改变事件: $(".customerIds").change(function () { $(this).removeClass("redFrame"); console.log("活动名称下拉选改变事件:"+$(this).children('option:selected').val()); console.log("选择的具体是哪一个:"+$(this).get(0).selectedIndex); var selectedIndex = $(this).get(0).selectedIndex; if(selectedIndex==0){ console.log("没有进行选择"); $("#customerName").val(""); $("#customerMobile").val(""); $("#customerAddress").val(""); $("#customerWeb").val(""); } else{ $("#customerName").val(data.data[selectedIndex-1].customer.customerName); $("#customerMobile").val(data.data[selectedIndex-1].customer.customerMobile); $("#customerAddress").val(data.data[selectedIndex-1].customer.customerAddress); $("#customerWeb").val(data.data[selectedIndex-1].customer.customerWeb); } }); } else{ console.log("获取数据失败"); } }, error:function (XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); });以上,我们在页面加载的时候去请求数据,返回数据之后,设置下拉选的change事件,来对应的改变下面表单当中的内容,并且当选择的内容不是公司的名称的时候,把下面表单当中的内容全部设置为空。