Reputation: 107
I'm having a textbox which is "observed" by a jquery for several actions, all code being a part of a "search-as-you-type" form. Well, everything works flawlessly on Mozilla but in Chrome, the textbox is losing focus after 1'st hit, so I have to click again in textbox to continue search. Any clue ? My experience is leading me to a bug
<div class="search-container">
<input type="text" placeholder="Search.." name="searchb" >
</div>
<script>
$('input[name="searchb"]').on('input propertychange
paste',function(){
if ($(this).val().length > 2){
document.cookie = "psearch="+this.value+";"+"path=/";
window.open("main.php?psearch="+this.value, "iframe_a");
}
});
</script>
Upvotes: 1
Views: 1184
Reputation: 3623
Your search input is losing focus because the new opened window will gain focus.
Moreover, with your current code, a new window is opened each time an input with a length more than two characters is detected.
There are many solutions, here are two of them. I didn't put them into code snippets because they will not work correctly.
You can get the generated HTML of main.php
thanks to an AJAX request:
HTML
<div class="search-container">
<input type="text" placeholder="Search.." name="searchb" >
</div>
<div id="searchb-result"></div>
Javascript
$('input[name="searchb"]').on('input propertychange paste', function() {
// Empties the result container.
$('#searchb-result').empty();
if ($(this).val().length > 2) {
document.cookie = `psearch=${this.value};path=/`;
// Gets the HTML by AJAX and adds it to the result container.
$.get('main.php', `psearch=${this.value}`, (html) => {
$('#searchb-result').html(html);
});
}
});
<iframe>
You can load your URL in a <iframe>
tag.
HTML
<div class="search-container">
<input type="text" placeholder="Search.." name="searchb" >
</div>
<iframe style="display:none;"></iframe>
Javascript
$('input[name="searchb"]').on('input propertychange paste', function() {
// Hides the <iframe> by default.
$('iframe').hide();
if ($(this).val().length > 2) {
document.cookie = `psearch=${this.value};path=/`;
// Updates the <iframe> source when an input is detected.
$('iframe')
.attr('src', `main.php?psearch=${this.value}`)
.show();
}
});
Upvotes: 2
Reputation: 107
I rewrote the entire section without jquery , clean and a with bit of 4'th grade approach, but it works. The lost focus was the problem.
<div class="search-container">
<input type="text" placeholder="Search.." name="searchb" id="search" autofocus="autofocus">
</div>
<script>
window.name = 'parent';
search.onchange = search.oninput = search.onpaste = function() {
var sv = search.value;
if (sv.length > 3){
var search_window = window.open("main.php?psearch="+sv, "iframe_a");
parent.focus();
}
else {
document.cookie = "psearch=";"path=/";
var search_window = window.open("main.php?psearch=", "iframe_a");
parent.focus();
}
}
</script>
Upvotes: 0