Reputation: 2126
I'm using awesomplete autocomplete plugin with thumbnail and I have index.html and I've <input id="myinput">
element but on my laoyut.html if I didn't put <input id="myinput">
then js give me a this erros
jquery.min.js:2 Uncaught TypeError: Cannot read property 'offsetWidth' of undefined
and my question is what should I do to fix it ?
var input = document.getElementById("myinput");
// Show label but insert value into the input:
new Awesomplete(input, {
list: [{
label: "<img src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRUxdD-Q4nIx3uIg9jBCe1oT5a9MHuWY5_pW4FoZSU-nQd1Y_WJPQ'/> Faceboock",
value: "https://www.facebook.com/"
},
{
label: "<img src='https://hydra-media.cursecdn.com/dota2.gamepedia.com/thumb/2/25/Pounce_icon.png/16px-Pounce_icon.png?version=77c984fc4a9c8ca491ead081322fa738'/> Youtube",
value: "https://www.youtube.com/"
},
{
label: "China",
value: "CN"
},
{
label: "United States",
value: "US"
}
]
});
// You can search for a better version
$(document).find('.awesomplete').on('click', function(e) {
if ($('#myinput').val())
window.location = $('#myinput').val();
//console.log($('#myinput').val());
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.css" rel="stylesheet"/>
<input id="myinput" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>
Upvotes: 0
Views: 1482
Reputation: 283
You can first check if #myinput is available in the html dom, then you can use the value of it.
var input = $("#myinput");
if (input.size() > 0) {
window.location = input.val();
}
I asume that there will be one div with this specific id. In that case, you can use
if (input.size() === 1) {
So in short, you can replace
$(document).find('.awesomplete').on('click', function(e) {
if ($('#myinput').val())
window.location = $('#myinput').val();
//console.log($('#myinput').val());
});
with
$(document).find('.awesomplete').on('click', function(e) {
var input = $('#myinput');
if (input.size() === 1) {
window.location = input.val();
}
});
Upvotes: 1