在onclilck函数中,我必须从每个输入中获取值并使用该值进行搜索,在我的数组中匹配,然后在DIV“result”中报告。问题是我必须使用逻辑AND搜索,因此如果存在,则将所有值一起使用。我不能这样做,有人可以帮助我吗?我只能使用javascript或jQuery-没有PHP。谢谢。
$("#search").click(function(){
var pharmacies = [];
pharmacies[0] = ["Vaccaro", "Bagheria", "90011"];
pharmacies[1] = ["Greco", "Bagheria", "90011"];
pharmacies[2] = ["Timoneri", "Bagheria", "90011"];
var names = [];
var elem = document.getElementsByClassName("campi");
for (var i = 0; i < elem.length; ++i) {
if (elem[i].value !== "") {
names.push(elem[i].value);
}
}
});
HTML:
<input class="campi" id="nome" type="text" name="name">
<input class="campi" id="indirizzo" type="text" name="address">
<input class="campi" id="città" type="text" name="city">
<input class="campi" id="cap" type="text" name="zip">
<button id="search" type="submit">Cerca</button>
<div id="result"></div>
答案 0 :(得分:0)
你可以这样做:
pharmacies
数组复制到temp array
。<input>
元素。<input>
元素中搜索给定值。<强>结果:强>
var pharmacies = [
[ 'Vaccaro', '', 'Bagheria', '90011' ],
[ 'Greco', '', 'Bagheria', '90011' ],
[ 'Timoneri', '', 'Bagheria', '90011' ]
];
function search() {
var tempArr = pharmacies.slice( 0 ),
elem = document.getElementsByClassName( 'campi' );
for ( let i = 0; i < elem.length; ++i ) {
var value = elem[ i ].value
if ( value ) {
for ( var j = 0; j < tempArr.length; ++j ) {
if ( tempArr[ j ] != undefined ) {
if ( tempArr[ j ].indexOf( value ) == -1 ) delete tempArr[ j ]
}
}
}
}
tempArr = tempArr.filter( Boolean );
printResult( tempArr )
}
function printResult( arr ) {
if ( arr.length ) {
var result = '<table><tr><th>#</th><th>Nome</th><th>Indirizzo</th><th>Città</th><th>Cap</th></tr>';
for ( var x in arr ) {
result += '<tr><td>' + (+x + 1) + '</td>'
for ( var y in arr[ x ] ) {
result += '<td>' + arr[ x ][ y ] + '</td>'
}
result += '</tr>'
}
result += '</table>'
} else {
result = 'No data found'
}
document.getElementById( 'result' ).innerHTML = result
}
input {
margin: 5px
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%
}
td, th {
border: 1px solid #ccc;
text-align: left;
padding: 8px
}
tr:nth-child(even) {
background-color: #ddd
}
<input class="campi" id="nome" type="text" name="name" placeholder="nome">
<input class="campi" id="indirizzo" type="text" name="address" placeholder="indirizzo">
<input class="campi" id="città" type="text" name="city" value="Bagheria" placeholder="città">
<input class="campi" id="cap" type="text" name="zip" placeholder="cap"><br>
<button id="search" type="submit" onclick="search()">Cerca</button><br><br>
<div id="result"></div>