How to fix offsetWidth of undefined error? - javascript

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>

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();
}
});

Related

Dropdown value change style of pages dynamically

I am building a muti-page website with Kendo UI for Jquery. I have a dropdown to select the style the user want. For now I can change the style, but it doesn't stick; as soon as I refresh the page it goes back to the default style. I want the style to also change for all the other pages.
Here is my code:
HTML
<html>
<head>
<link rel="stylesheet" href="css/kendo.common.min.css">
<link rel="stylesheet" href="css/kendo.default.min.css"/>
<script src="script/jquery.min.js"></script>
<script src="script/kendo.all.min.js"></script>
</head>
<body class="k-content">
<label for="theme">Theme:</label>
<input id="theme" name="theme">
<button class="k-button">Export Immagine</button>
<button class="k-button">Export Excel</button>
</body>
</html>
Jquery
$('#theme').kendoDropDownList({
dataSource: [
{ text: "Original", value: "default" },
{ text: "Black", value: "black" },
{ text: "Blue Opal", value: "blueopal" },
{ text: "Metro", value: "metro" },
{ text: "Silver", value: "silver" }
],
dataTextField: "text",
dataValueField: "value",
change: function (e) {
var theme = (this.value() || "default").toLowerCase();
changeTheme(theme);
}
});
// loads new stylesheet
function changeTheme(skinName, animate) {
var doc = document,
kendoLinks = $("link[href*='kendo.']", doc.getElementsByTagName("head")[0]),
commonLink = kendoLinks.filter("[href*='kendo.common']"),
skinLink = kendoLinks.filter(":not([href*='kendo.common'])"),
href = location.href,
skinRegex = /kendo\.\w+(\.min)?\.css/i,
extension = skinLink.attr("rel") === "stylesheet" ? ".css" : ".less",
url = commonLink.attr("href").replace(skinRegex, "kendo." + skinName + "$1" + extension);
var theme = $('#theme').getKendoDropDownList().value();
$('.k-chart').each(function () {
var chart = $(this).data('kendoChart');
chart.options.theme = skinName;
chart.setOptions({ theme: theme });;
});
function preloadStylesheet(file, callback) {
var element = $("<link rel='stylesheet' media='print' href='" + file + "'").appendTo("head");
setTimeout(function () {
callback();
element.remove();
}, 100);
}
function replaceTheme() {
var oldSkinName = $(doc).data("kendoSkin"),
newLink;
if (kendo.support.browser.msie) {
newLink = doc.createStyleSheet(url);
} else {
newLink = skinLink.eq(0).clone().attr("href", url);
newLink.insertBefore(skinLink[0]);
}
skinLink.remove();
$(doc.documentElement).removeClass("k-" + oldSkinName).addClass("k-" + skinName);
}
if (animate) {
preloadStylesheet(url, replaceTheme);
} else {
replaceTheme();
}
};
I know I have to use sessionStorage, but I don't really know how to implement that with Kendo. Can someone help me?
Set the session storage value inside the changeTheme function with the chosen theme name:
sessionStorage.setItem('user.theme', skinName);
Then check for it on page load, and set it if any value is set:
let userTheme = sessionStorage.getItem('user.theme');
if (userTheme) {
changeTheme(userTheme);
$('#theme').getKendoDropDownList().value(userTheme);
}
Dojo

Highlight selected jsGrid row

I found this example which highlights a row after it has been selected but the problem with it is that it keeps the previous row(s) highlighted after another one has been selected.
Here's part of the code
//js
rowClick: function(args) {
var $row = this.rowByItem(args.item);
$row.toggleClass("highlight");
},
//css
tr.highlight td.jsgrid-cell {
background-color: green;
}
I can't find a solution to unhighlight the previously selected row
A little late to the party on this one, however the accepted answer by #Narenda didn't completely solve my problem. This may help someone else that stumbles across this later.
If you need a single select only, here's a way of doing it:
Extend the jsGrid plugin with a method to find a row by index:
jsGrid.Grid.prototype.rowByIndex = function(arg){
//this._content.find("tr")[arg] returns a DOM element instead of a jQuery object
//Pass the DOM element to the find method to get a jQuery object representing it
return this._content.find(this._content.find("tr")[arg]);
};
Modify the rowClick function in #Narenda's answer:
rowClick: function ( args ) {
//Deselect all rows
for(var i = 0; i<this.data.length; i++){
this.rowByIndex(i).removeClass("jsgrid-highlight-row");
}
//Everything else as per the previous answer
var $row = this.rowByItem(args.item),
selectedRow = $("#jsGrid").find('table tr.jsgrid-highlight-row');
if (selectedRow.length) {
selectedRow.toggleClass('jsgrid-highlight-row');
};
$row.toggleClass("jsgrid-highlight-row");
//Any other code to run on item click
}
And add some CSS. This mimics the row hover in the default theme:
tr.jsgrid-highlight-row td.jsgrid-cell {
background:#c4e2ff;
border-color:#c4e2ff;
}
You can achieve by this following steps
First on row click you need to get selected row like this
var selectedRow = $("#jsGrid").find('table tr.highlight').
Then you can use
selectedRow.toggleClass('highlight') or selectedRow.removeClass('highlight')
DEMO
$("#jsGrid").jsGrid({
width: "100%",
height: "auto",
paging: false,
//for loadData method Need to set auto load true
autoload: true,
noDataContent: "Directory is empty",
controller: {
loadData: function(filter) {
var data = [{
nickname: "Test",
email: "t#gmail.com"
}, {
nickname: "Test 1",
email: "t1#gmail.com"
}, {
nickname: "Test 2",
email: "t2#gmail.com"
}, {
nickname: "Test 3",
email: "t3#gmail.com"
}];
return data;
}
},
rowClick: function(args) {
var $row = this.rowByItem(args.item),
selectedRow = $("#jsGrid").find('table tr.highlight');
if (selectedRow.length) {
selectedRow.toggleClass('highlight');
};
$row.toggleClass("highlight");
},
fields: [{
name: "nickname",
type: "text",
width: 80,
title: "Name"
}, {
name: "email",
type: "text",
width: 100,
title: "Email Address",
readOnly: false
}]
});
tr.highlight td.jsgrid-cell {
background-color: green;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<div id="jsGrid"></div>
If you came looking for a solution in which only 1 line is selected and which also deselects the same line, here is the solution:
selectedVal = null;
$(document).ready(function(){
jsGrid.Grid.prototype.rowByIndex = function(arg) {
//this._content.find("tr")[arg] returns a DOM element instead of a jQuery object
//Pass the DOM element to the find method to get a jQuery object representing it
return this._content.find(this._content.find("tr")[arg]);
};
});
rowClick: function (args) {
selectedVal = args.item;
let $row = this.rowByItem(args.item);
if ($row.hasClass("highlight") === false) {
//Deseleciona todas as linhas
for (let i = 0; i < this.data.length; i++) {
this.rowByIndex(i).removeClass("highlight");
}
$row.toggleClass("highlight");
} else {
selectedVal = null;
$row.toggleClass("highlight");
}
console.log(selectedVal);
}

Parse not working in jQuery

I'm trying to make a website that uses parse. My java script will be shown below. The js is linked and I've made sure to include
<script src="//www.parsecdn.com/js/parse-1.6.12.min.js"></script>
in the html. My js :
$(document).ready(function() {
Parse.initialize("assumeisright", "assumeisright");
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({
foo: "bar"
}).then(function(object) {
alert("yay! it worked cash muni");
});
$("div").hover(
function() {
$(this).addClass("active");
},
function() {
$(this).removeClass("active");
}
);
Parse.Push.send({
channels: ["Everyone"],
data: {
alert: "First Push"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
});
This doesn't work because in my html my div doesn't change when I hover so I'm assuming the Parse crashed. Any ideas of how to fix this, am I doing something wrong?
Thanks
As you are using jquery so you need to import that library as well, so final code will be something like this
<!doctype html>
<html>
<head>
<style>
</style>
<script src="http://www.parsecdn.com/js/parse-1.6.12.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
Parse.initialize("assumeisright", "assumeisright");
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({
foo: "bar"
}).then(function(object) {
alert("yay! it worked cash muni");
});
$("div").hover(
function() {
console.log('add');
$(this).addClass("active");
},
function() {
$(this).removeClass("active");
}
);
Parse.Push.send({
channels: ["Everyone"],
data: {
alert: "First Push"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
});
</script>
</head>
<body>
<div>
<p>Hello</p>
</div>
</body>
</html>
On hover i have added console.log('add') just to test if hover is working fine, it outputs add when you hover over div
$("div").hover(
function() {
console.log('add');
$(this).addClass("active");
},
Always check your browser console for errors

fadeIn and fadeOut divs based on radio button with if conditions

I really appreciate your help in advance. Can someone help me figure out why my last else if statement is not working?
I am getting an error "Uncaught TypeError: Cannot read property 'checked' of null" in the console, but only for the last else if.
//html for radio buttons
<p><input type="radio" name="radio" value="generalPurpose" id="gp-toggle"><label for="gp-toggle" >General Purpose</label></p>
<p><input type="radio" name="radio" value="client" id="cc-toggle-one"><label for="cc-toggle-one">Client</label></p>
<p><input type="radio" name="radio" value="contractor" id="cc-toggle-contractor"><label for="cc-toggle-contractor">Contractor</label></p>
<p><input type="radio" name="radio" value="urgent" id="urgent-toggle"><label for="urgent-toggle">Urgent Request</label></p>
.
///js
$(function() {
$("#contact-form .button").click(function() {
var data = {
radio: $("input:radio[name=radio]:checked").val(),
firstName: $("#f-name").val(),
lastName: $("#l-name").val(),
email: $("#email").val(),
phone: $("#phone").val(),
comments: $("#comments").val(),
coverage: $("#coverage").val(),
services: $("#services-two").val(),
covered: $("#covered").val(),
provided: $("#provided").val(),
reason: $("#reason").val()
};
$.ajax({
type: "POST",
url: "formmail.php",
data: data,
success: function() {
$('.form-inner').fadeOut(1000);
setTimeout(function() {
if (document.getElementById('gp-toggle').checked) {
$('.gp-reply').fadeIn(1000);
} else if (document.getElementById('cc-toggle-one').checked) {
$('.client-reply').fadeIn(1000);
} else if (document.getElementById('cc-toggle-two').checked) {
$('.contractor-reply').fadeIn(1000);
} else if (document.getElementById('urgent-toggle').checked) {
console.log('perform fadein');
$('.urgent-reply').fadeIn(1000);
}
}, 1200);
}
});
return false;
});
});
thanks again. I was really hoping for a stupid typo; but I guess I will need to look more into this.
so based on this question here >> Uncaught TypeError: Cannot read property 'checked' of null index.html:24 suggested by https://stackoverflow.com/users/1421098/ameya-rote
I made some variables and it seems to be working fine now.
var gp = document.getElementById('gp-toggle').checked;
var client = document.getElementById('cc-toggle-one').checked;
var contractor = document.getElementById('cc-toggle-contractor').checked;
var urgent = document.getElementById('urgent-toggle').checked;
.
$(document).ready(function() {
$(function() {
$("#contact-form .button").click(function() {
var data = {
radio: $("input:radio[name=radio]:checked").val(),
firstName: $("#f-name").val(),
lastName: $("#l-name").val(),
email: $("#email").val(),
phone: $("#phone").val(),
comments: $("#comments").val(),
coverage: $("#coverage").val(),
services: $("#services-two").val(),
covered: $("#covered").val(),
provided: $("#provided").val(),
reason: $("#reason").val()
};
$.ajax({
type: "POST",
url: "formmail.php",
data: data,
success: function() {
$('.form-inner').fadeOut(1000);
setTimeout(function() {
if ('gp') {
$('.gp-reply').fadeIn(1000);
} else if ('client') {
$('.client-reply').fadeIn(1000);
} else if ('contractor') {
$('.contractor-reply').fadeIn(1000);
} else if ('urgent') {
console.log('perform fadein');
$('.urgent-reply').fadeIn(1000);
}
}, 1200);
}
});
return false;
});
});
});
Try the code given below, Hope it will work.
function get_checked_val() {
var inputs = document.getElementsByName("selected");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return inputs[i].value;
}
}
}
function onSubmit() {
var id = get_checked_val();
alert("selected input is: " + id);
}
Or you may try this to make the value checked
$(document.getElementById('cc-toggle-one')).attr('checked', true);

Append results from MULTIPLE arrays to the INITIALLY GENERATED ul after click, how can this be done?

So, I have a bunch of sources for Autocomplete, like this:
var search1 = [{
search: "authors1"
}, {
search: "autocomplete1"
}, {
search: "automatic1"
}];
var search2 = [{
search: "authors2"
}, {
search: "autocomplete2"
}, {
search: "automatic2"
}];
var search3 = [{
search: "authors3"
}, {
search: "autocomplete3"
}, {
search: "automatic3"
}];
I MUST store data in different arrays, so please don't suggest me to join them.
HTML:
<input data-source="search1,search2,search3" type="text" value="" />
<div id="loadingmsg" style="display:none">Searching...</div>
I'd like to have a recursive function that will come through all the sources specified in "data-source" attribute and append results to one menu. For example, when I type "auth", I want to see this:
#loadingmsg reveals itself.
The resulting menu (containing "authors1", "authors2" and "authors3") shows up.
#loadingmsg disappears.
Is it possible?
With <input data-source="1,2,3" />
//bind a response to typing for each of these inputs
$("img[data-source]").on('keyup', function () {
//get typed value
var value = $(this).val();
//clear the current menu
$("#menu").empty();
//show loading image (probably ineffective)
$("#loadingimg").show();
//iterate over source keys acquired from <input> data
$.each($(this).data('source').split(','), function () {
//iterate over corresponding object in `search`
$.each(search[this], function () {
//typed value matches string
if (this.indexOf(value) > -1) {
$("#menu").append('<span>' + this + '</span>');
}
});
});
$("#loadingimg").hide();
});

Categories

Resources