$(...).autocomplete is not a function error - javascript

I have the following files
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/boostrap-min.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Then I have javascript function
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("MerrBarkodet","Produktet")'
});
});
});
</script>
But is not working, is showing error
Uncaught TypeError: $(...).autocomplete is not a function
#using (Html.BeginForm("Index", "Produktet", FormMethod.Get, new { #class = "navbar-form navbar-left" }))
{
<div class="form-group">
<b>Search:</b>#Html.TextBox("search", null, new { id = "txtSearch" })
<input class="btn btn-default" type="submit" value="Search" />
</div>
}

Comment out (or remove) the code I commented below. $(function() { }) is not going to initialize inside a $(document).ready() call.
//$(document).ready(function () {
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("MerrBarkodet","Produktet")'
});
});
// });

Possible causes for the issue.
The order that jquery.js get loaded. jquery.js must be present before jqueryui.js
Possible duplicate of jquery.js reference. Ensure that there is no jquery reference in your file. If you are implementing a layout file,or an external library ensure there is no jquery called there.
try using the jQuery.noConflict() method for a test. It basically just makes you use a different alias for jQuery.
Ex:
var j = jQuery.noConflict();
j("div p").hide();
Check that you're function call isn't getting hit before the document is loaded:
$(function(){
var $searchBox = $('#txtSearch');
$searchBox.autocomplete(...);
});

Related

How can I execute scripts in a React.js component?

I received an HTML file with 2 scripts in the head and I'm figuring out the best way to execute them in my react app. The first script load socket.io.js and the second contains the JS code for the upload system:
Original code
//...
<head>
<link rel="stylesheet" type="text/css" href="/css/upload.css" />
<script src="/js/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect("/", { path: "/app/socket.io" });
var SelectedFiles = [];
var SelectedFile = 0;
var paused = 0;
var FReader;
var dat;
window.addEventListener("load", Ready);
function Ready() {
//...
}
function handleUploads() {
//...
}
function StartUpload(Name, size) {
FReader.onload = function(evnt) {
socket.emit("Upload", {
//...
});
};
socket.emit("Start", {
//...
});
}
function getBlocks(data) {
//...
}
socket.on("MoreData", function(data) {
//...
});
function UpdateBar(percent) {
//...
}
socket.on("Done", function(data) {
//...
});
function Refresh() {
location.reload(true);
}
</script>
</head>
<body>
//...
First of all I moved the JS code content in a new JS file named "upload-script.js" and then used "React Helmet" module (https://www.npmjs.com/package/react-helmet) in order to load them in document head during component rendering:
My code
return (
<Row className="mb-4">
<Helmet>
<link rel="stylesheet" type="text/css" href="/css/upload.css" />
<script src="/js/socket.io.js" />
<script src="/upload-script.js" />
</Helmet>
<Colxx xxs="12">
Checking on browser the module correctly adds the scripts in the document head, but come out the following error:
./src/containers/form-validations/upload-script.js
Line 2:14: 'io' is not defined no-undef
Line 124:3: Unexpected use of 'location' no-restricted-globals
The browser cannot compile the app because in the JS file "upload-script.js" contains variables that are only defined in the first script.. how can I solve it? Is this a good way to add the scripts in a React app?
Any suggestions or guidance would be greatly appreciated. Thank you in advance.

Cant submit html form after use js script

I have this html site
<html>
<head>
<link rel="stylesheet" href="~/Content/index.css" />
<link rel="stylesheet" href="~/Scripts/fancyBox/source/jquery.fancybox.css" type="text/css" media="screen" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript" src="~/Scripts/prototype.js"></script>
<script type="text/javascript" src="~/Scripts/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="~/Scripts/Scale.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="~/Scripts/fancyBox/source/jquery.fancybox.pack.js"></script>
<title>Countries</title>
</head>
<body>
<div>
#foreach (var country in Model)
{
<a class="fancybox">
<div class="tooltip">
#using (Html.BeginForm("ChangeCulture", "Home", new { lang = country.Culture }))
{
<!-- onclick="zoomIn('#country.Culture')"-->
<input id="#country.Culture" class="#country.Sprite" type="image" name="submit" src="//" />
<span class="tooltiptext">#country.Country</span>
}
</div>
</a>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
this.find("form").submit();
}
});
})
</script>
</body>
</html>
The bottom line is that the flags of countries with tooltips are displayed on the screen and by pressing it is necessary to change the language of the tooltips to the language used in the country. I did this, and now I need to increase the whole screen after receiving the picture with the flag, and then the language would change. I found the fancybox scripts, but after it is inserted, the form is not sent, the selected flag appears in the center, but nothing happens after that, what could be the problem? I have not written to asp and js before
After click on the image I got an error
Uncaught TypeError: this.find is not a function
at Object.afterShow (Index:119)
at Function.trigger (jquery.fancybox.pack.js:17)
at HTMLDivElement._afterZoomIn (jquery.fancybox.pack.js:33)
at HTMLDivElement.d.complete (jquery-latest.min.js:4)
at j (jquery-latest.min.js:2)
at Object.fireWith [as resolveWith] (jquery-latest.min.js:2)
at i (jquery-latest.min.js:4)
at m.fx.tick (jquery-latest.min.js:4)
My method
public ActionResult ChangeCulture(string lang)
{
var returnUrl = this.Request.UrlReferrer?.AbsolutePath;
var cookie = this.Request.Cookies["lang"];
if (cookie != null)
{
cookie.Value = lang;
}
else
{
cookie = new HttpCookie("lang")
{
HttpOnly = false,
Value = lang,
Expires = DateTime.Now.AddYears(1)
};
}
this.Response.Cookies.Add(cookie);
return this.Redirect(returnUrl ?? "Index");
}
You should user jquery selector
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
$(".fancybox").submit();
}
});
})
The error is located in this statement:
this.find("form").submit();
You're trying to call find() method on plain JS object inside this wrapper, where the function belongs to a jQuery object. The correct way is using jQuery object like this:
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
// alternative: use $(this).closest("form").submit();
$(this).find("form").submit();
}
});
});
</script>
Additionally your redirection method in controller action should be like below, since Controller.Redirect requires full path or URL for redirect to another page:
public ActionResult ChangeCulture(string lang)
{
var returnUrl = this.Request.UrlReferrer?.AbsolutePath;
// cookie settings here
if (string.IsNullOrEmpty(returnUrl))
{
return this.RedirectToAction("Index");
}
return this.Redirect(returnUrl);
}
The this in this.find("form") is not $(".fancybox") here.
Try using $('.fancybox form') instead.

Uncaught ReferenceError: jQuery is not defined

I don't see why I would get this, code below:
<head>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" type="text/javascript"></script>
<script>
var json1 = {
text: "After first paragraph"
};
var first_content_added = false;
$(function() {
$(".learn-more").on("click", function() {
$.getJSON("json_info.json", function(data) {
appendContentToFirstP(data.reviews[0].about.moreinfo);
});
});
});
function appendContentToFirstP(content) {
if (first_content_added) {
return;
}
var after_first_p = $('<p class="more-info" />');
after_first_p.text(content);
$(".first").append(after_first_p);
first_content_added = true;
}
</script>
</head>
What would be causing the error?
My initial thought is the error is because I have not imported JQuery, but I have. It's inside the script tag at the top.
You haven't included jQuery, you've only included the plugin jQuery.color.
Reference it before jQuery.color:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
write before that color js like this
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" type="text/javascript"></script>

How do I pass this JSON data to an autocomplete

Special thanks to Raúl Monge for posting a fully working code for me.
My problem was getting JSON data from a file.json and using this data to autocomplete search on it with JavaScript. The code that finaly got it working for me is the following:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('json/telefoonnummers.json', function(json) {
$.each(json.personen.persoon,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.naam+" - "+value.telefoonnummer;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
This is the html:
<body>
<div id="content">
<input type="text" id="search" />
</div>
And this has to be included in the head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
Thanks stackoverflow!
NEW EDIT CODE WORKING:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('data.json', function(json) {
$.each(json.persons.person,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.name;
arrayAutocomplete[index]['value'] = value.phoneno;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
</script>
Add this in head
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
This is the html
<body>
<div id="content">
<input type="text" id="search" />
</div>
</body>
why not use
var data = [
"Aragorn",
"Arwen",
....
];
since all of those data are labels?
There you go
A working example with the data structure you have.
Just initialize the autocomplete once the JSON is loaded & the data is formatted.
$( "#search" ).autocomplete({source: availableTags});
Your document ready is within your function.
Try to write your function outside of your document ready.
Then write your document ready to call your function.
Some something like this:
function loadJson() {
//alert("Whoohoo, you called the loadJson function!"); //uncomment for testing
var mycontainer = [];
$.getJSON( "data.json" , function(data) {
//alert(data) //uncomment for testing
$.each( data, function( key, val ) {
//alert("key: "+key+" | val: "+val); //uncomment for testing
array.push([key , val]);
});
});
return mycontainer;
}
$(document).ready(function(){
//alert("Boojah! jQuery library loaded!"); //uncomment for testing
var content = loadJson();
dosomethingwitharray(content);
});
Hope this helps!
Also make sure you have jQuery included in your head ( <head> </head> ):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
And add your javascript at the end of your body ( <body> </body> ).
To test if jquery does it's job try this:
<html>
<head>
<title>getting started with jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<h1>my page</h1>
<p>this paragraph contains some text.</p>
<!-- javascript at end -->
<script>
$(document).ready(function(){
//show a dialog, confirming when the document is loaded and jquery is used.
alert("boojah, jquery called the document ready function");
//do something with jquery, for example, modify the dom
$("p").append('<br /> i am able to modify the dom with the help of jquery and added this line, i am awesome.');
});
</script>
</body>
</html>
PS. Uncomment alerts for testing stuff, so you can test what happens. If you have space in your document i suggest using $.append to an div that log's all action's so you can see exactly what's going on because alert's in a loop like the .each are quite annoying! more about append: http://api.jquery.com/append/

Reuse a Jquery Script

I'm trying to reuse a function i made, but with any help yet.
Here is my index.html.
<html>
<head>
<script src="jquery-1.5.1.js")" type="text/javascript"></script>
<script src="JqueryScript.js")" type="text/javascript"></script>
<script type="text/javascript">
//MYLIBRARY.init(['#button1']);
execute(['#button1']);
execute(['#button2']);
</script>
</head>
<body>
<button type="button" id="button1">Click Me!</button>
<button type="button" id="button2">Click Me!</button>
</body>
</html>
And here is my script.
function execute (Args){
_args = Args;
$(function() {
$(_args[0]).click(function() {
alert("hello " + _args[0]);
return false;
});
});
}
The problem is always triggers the second alert windows (#button2). How can i make it work with both alert windows?
My guess is that you are wondering why both buttons alert the same output.
Because _args is global. Thus the second invokation will overwrite _args.
Use var to make it local:
var _args = Args;
Your code could still be improved (see #Town's answer), but this should get you started.
You also have errors in your HTML
<script src="jquery-1.5.1.js")" type="text/javascript"></script>
<!-- ^^ -->
<script src="JqueryScript.js")" type="text/javascript"></script>
<!-- ^^ -->
What exactly are you trying to do?
From what I can see, you could achieve the same functionality as what you have with simply:
$(function() {
$('button').click(function() {
alert("hello #" + this.id);
});
});
Example
Looks like C to me :)
You'd be better off with
<script type="text/javascript">
$(function () {
execute('#button1');
execute('#button2');
}
function execute(buttonId)
{
$(buttonId).click(function () { alert('Hello ' + this.id); });
}
</script>

Categories