Get Value From Multiple Input And Search Array Match (with And E Or)
In the function onclilck, I have to get the value from each input and search with that value, a match in my array and then report in DIV 'result'. The problem is that I have to do
Solution 1:
you can do this:
- Copy the
pharmacies
array to atemp array
. - Get all
<input>
element. - Search among
<input>
elements for given value. - Delete array element, if given value not found.
- Remove undefined values from Temp array.
- Print the temp array.
Result:
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>
Post a Comment for "Get Value From Multiple Input And Search Array Match (with And E Or)"