我有两个选择选项和一个按钮验证,第一个按城市,国家和地区填写,第二个按名称,数字和薪水填写,我想当我单击按钮时验证以将第二个选择的数据显示为以上: 名称: 注册号码 : 工资: 但就我而言,它会显示第一个选择数据。
$(document).ready(function() {
$("#hide").click(function() {
let selectOption = $('.form-control').val();
let optionSplits = selectOption.split('-');
let name1 = optionSplits[0];
let matricule1 = optionSplits[1];
let salary1 = optionSplits[2];
$('#nam').text(name1);
$('#mat').text(matricule1);
$('#sal').text(salary1);
$("#form1").hide();
$("#form2").show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form1">
<div class="form-group col-md-3">
<select class="form-control">
<option value="city1-country1-color1">city1 country1 color1</option>
<option value="city2-country2-color2">city2 country2 color2</option>
<option value="city3-country3-color3">city3 country3 color3</option>
</select>
</div>
<div class="form-group col-md-3">
<select class="form-control">
<option value="name1-22-6000">name1 22 6000</option>
<option value="name2-24-8000">name2 24 8000</option>
<option value="name3-27-5000">name3 27 5000</option>
</select>
</div>
<div class="form-group col-md-offset-5 ">
<button class="btn btn-success " id="hide">valider</button>
</div>
</div>
<!--form 2-->
<div id="form2">
<h4>name : <span id="nam"></span></h4>
<h4>matricule : <span id="mat"></span></h4>
<h4>salary : <span id="sal"></span></h4>
</div>
答案 0 :(得分:2)
因为您使用了与两个选择都匹配的选择器.form-control
。您应该将id添加到第二选择中,并使用该id获得价值。
$(document).ready(function() {
$("#hide").click(function() {
let selectOption = $('#second_select').val();
let optionSplits = selectOption.split('-');
let name1 = optionSplits[0];
let matricule1 = optionSplits[1];
let salary1 = optionSplits[2];
$('#nam').text(name1);
$('#mat').text(matricule1);
$('#sal').text(salary1);
$("#form1").hide();
$("#form2").show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form1">
<div class="form-group col-md-3">
<select class="form-control">
<option value="city1-country1-color1">city1 country1 color1</option>
<option value="city2-country2-color2">city2 country2 color2</option>
<option value="city3-country3-color3">city3 country3 color3</option>
</select>
</div>
<div class="form-group col-md-3">
<select class="form-control" id="second_select">
<option value="name1-22-6000">name1 22 6000</option>
<option value="name2-24-8000">name2 24 8000</option>
<option value="name3-27-5000">name3 27 5000</option>
</select>
</div>
<div class="form-group col-md-offset-5 ">
<button class="btn btn-success " id="hide">valider</button>
</div>
</div>
<!--form 2-->
<div id="form2">
<h4>name : <span id="nam"></span></h4>
<h4>matricule : <span id="mat"></span></h4>
<h4>salary : <span id="sal"></span></h4>
</div>