I'm new to this forum and I would like to tell you my problem already.
I need a multiple search field, when I go to enter the first letters I get the results through an AJAX call made on a file in php, the problem is that in the second input field that I have cloned the AJAX scan does not work and I do not suggestions come out. So how can I go about making multiple search fields work?
I am attaching the code to make you understand better. Thank you all.
<div class="cont">
<input type="text" class="form-control search" id="search">
<button id="add" onClick="add()"> </button>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="output">
</tbody>
</table>
function add(){
$("#search").clone().val("").attr("id", "search").appendTo(".cont");
}
$("#search").keyup(function(){
$.ajax({
type:'POST',
url:'search.php',
data:{
name:$(this).val(),
},
success:function(data){
$(".#output").html(data);
return data;
}
});
});
I did as you said, but the ajax call in the second input doesn't work, should I call the ajax function to make it work on the new input? How could I do?
Thanks a lot everyone, I solved it
CodePudding user response:
You need to be identifying a class search .. You are calling an ID which is supposed to be unique
When cloning remove the ID attribute and use addClass('search')
$("#search").clone().val("").addClass("search").appendTo(".cont");
Then change your selector from: $("#search")
To $(".search")
in effect calling any element with the class search on keyup
UPDATE
as @ADyson mentioned in the comment .. You will need to bind
the keyup action .. The easiest way to do this is using on()
( from the deprecated .live()
). IE:
$(document).on('keyup', '.search', function(){
FULL SNIPPET:
function add(){
$("#search").clone().val("").addClass("search").appendTo(".cont");
}
$(document).on('keyup', '.search', function(){
alert('Call AJAX');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cont">
<input type="text" class="form-control search" id="search">
<button id="add" onClick="add()"> </button>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="output">
</tbody>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Check out the API Documentation for a full list of events handled through .on()