how to target class with multiple text fields using jQuery
I am generating text fields via php.
So, depending on the user, it could output 1 text field, 3 text fields, 5 text fields, however many.
In each of those text fields I want to perform an ajax search.
Each text field will search exactly the same database table.
I have managed to give each ID of the text field a number starting at 1 and then it goes up to however many text fields there are.
The issue is the CSS.
I tried to use a class to style the search results but if I type into not text field, results start showing in ALL text fields instead of just the one I am typing into.
This is the code for the text fields outputted in the loop:
<?php
echo "<input id='search{$item}' name='search[]'type='text' autocomplete='off' onKeyUp='ajax_call(\"{$item}\")'>";
echo "<div style='display:none' id='loading{$item}'><img src='functions/loading.gif'/></div>";
echo "<ul class='test'></ul>";
Here is the jQuery and Ajax
<script type="text/javascript">
$("#loading").hide();
function ajax_call(textfield) {
var textfield_value = textfield;
$("#loading" + textfield_value).show();
var search = $('#search' + textfield_value).val();
if (search.length > 3) {
$.ajax({
type: 'POST',
url: 'functions/daily-prod/lost-time-search.php',
data: {
search: search
},
success: function(data) {
if (!data.error) {
$('.test').html(data);
$("#loading" + textfield_value).hide();
}
}
});
}
if (search.length < 1) {
$('.test').html('');
$("#loading" + textfield_value).hide();
}
}
</script>
CSS:
<style type="text/css">
.test {
font-size: 15px;
margin-left: 10px;
width: 50%;
margin-top: 0px;
background: #f9f9f9;
overflow-y: auto;
overflow-x: hidden;
z-index: 1000;
}
.test li {
padding: 10px;
border-bottom: 1px solid #ddd;
border-right: 1px solid #ddd;
border-left: 1px solid #ddd;
list-style-type: none;
margin-left: -39px;
color: #000000;
}
.test li:hover {
background: #dddddd;
color: red;
}
</style>
Generated HTML code is:
<input id='search1' name='search[]'type='text' autocomplete='off' onKeyUp='ajax_call("1")'>
<div style='display:none' id='loading1'><img src='functions/loading.gif'/> </div>
<ul class='test'></ul><input id='search2' name='search[]'type='text' autocomplete='off' onKeyUp='ajax_call("2")'><div style='display:none' id='loading2'>
<img src='functions/loading.gif'/></div><ul class='test'></ul><input id='search3' name='search[]'type='text' autocomplete='off' onKeyUp='ajax_call("3")'>
<div style='display:none' id='loading3'><img src='functions/loading.gif'/> </div><ul class='test'></ul>
Answers 1
Give the
<ul class="test></ul>
anid
attributetest{$item}
and adjust the function call to use$('#test' + textfield_value)
like you have done with the input fields.