Reputation: 97
I have a form and I am using an onkeyup
event to search for matches within a database based on what the user types. That part is working just fine. Results trigger a hidden DIV to be shown with matches.
What I would then like to do is allow the user to click a matching result and using onclick
have that result inserted into the text field the user was typing in.
Here is what I have:
HTML
Distributor
<font color="red"><b>*</b></font>
<input type="text"
name="dist"
id="dist"
value="<? if (isset($dist)) {echo $dist;} ?>" required
onkeyup="sugdist(this.value);"/>
<br><br>
SCRIPT
function fillDist() {
var insertText = $(this).text();
$('#dist').insert(insertText);
}
Here is what I have on the AJAX script side.
while ($result = $query ->fetch_object()) {
echo "<div id='fillDist' OnClick='fillDist'>"
.addslashes($result->name).
"</div>";
}
It's not working, but its also not tripping any errors.
Any ideas? Thanks
Upvotes: 0
Views: 126
Reputation: 1397
The flow is not so clear.
So, the AJAX script returns an HTML that has an onClick
function.
I am assuming that the output is correctly added to your output div, because I see a simple error here:
OnClick='fillDist'
you should change it to
onClick='fillDist()'
to really call the function.
However, you have the jQuery tag and you are using it in some other operations, so you can avoid the inline onClick
in the HTML code, and do it all javascript/jQuery side:
$(document).on('click', '#fillDist', function() {
const text = $(this).text();
$('#dist').text(text);
});
We are doing this:
$(document).on('click', '#dist', function() {});
and not this:
$('#dist').click(function() {});
Because the element is dynamically injected.
$(document).on('click', '#fillDist', function() {
const text = $(this).text();
$('#dist').text(text);
});
#dist {
margin: 20px;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dist">
</div>
<div id="fillDist">click me to add the same text to dist</div>
Please find the demo even here on codepen.
Upvotes: 2