I want to create wordpress search by title without refleshing page. New results have to be shown when more than 3 symbols are typed in search. I’ve got input with form:
JavaScript
x
4
1
<form id="searchForm">
2
<input id="newsSearch" name="newsSearch" type="text" name="newsSearch" placeholder="Для отображения ленты по определенной компании введите ее название или тикер в это поле">
3
</form>
4
But when I’m typing – value of input is not changing. How can I search posts after typing 3 symbols if I cannot get input.value.length
? Also how can I search without refreshing a page? I know that it can be done with ajax but I got this code and it does nothig, page is still reloading after submit:
JavaScript
1
21
21
1
<script>
2
$('#searchForm').submit(function(e) {
3
4
e.preventDefault(); // prevent from submitting form directly
5
6
$.ajax({
7
url: '<?php echo admin_url('admin-ajax.php'); ?>',
8
method: 'post',
9
data: $("#searchForm").serializeArray() // convert all form data to array (key:value)
10
})
11
.done(function(response){
12
alert('ok'); // show the response
13
$("#searchForm").reset(); // reset the form
14
})
15
.fail(function(error){
16
alert(error); // show the error.
17
});
18
})
19
20
</script>
21
Advertisement
Answer
Your input value isn’t changing because you are listening for ‘submit’ event on form. You should create a listener on input element on ‘input’ event.
JavaScript
1
2
1
$('#newsSearch').on('input', function(e) {
2
Inside you should create yourself a check in which the function will return and do nothing if value is shorter than 3 symbols.