Jquery not working at all but other Javascript code runs - javascript

I'm facing a problem with my jquery. I have a table with multiple records and with each record there is delete link. On clicking that link that particular record is deleted. That is fine but what I am trying for is when a record is deleted it simply disappears without any page refresh. For that I have a jquery code which works fine on a stand alone page but when I'm trying to integrate it with my actual code nothing happens at all. I replaced $ with jQuery but still nothing happening. I also checked for other causes but nothing worked. Can someone point out what could possibly be missing or I'm doing wrong. Codes are below:
This is my row code which is inside a foreach so multiple ones are created
<tr class="showdel">
<td class="align"><input type="checkbox" name="instanceids[]" id="checkid" value="<?php echo $instanceid; ?>" /></td>
<td class="align"><?php echo $i++.'.'; ?></td>
<td><?php echo $title; ?></td>
<td>Delete</td>
</tr>
Below is my jquery code which deletes the record and it simply disappears. It is in head section of the page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function()
{
jQuery(".delete").click(function()
{
var element = jQuery(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
jQuery.ajax({
type: "POST",
url: "content_list.php",
data: info,
success: function() {}
});
jQuery(this).parents(".showdel").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
Please point out what am I doing wrong. Thanks in advance.
PS: Here is my whole head section. See if this helps. May be ordering of scripts is wrong.
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title><?php echo $client; ?> Admin</title>
<!-- bootstrap core css -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- custom css -->
<link href="css/sb-admin.css" rel="stylesheet">
<!-- style.css -->
<link href="css/style.css" rel="stylesheet">
<!-- paginng css -->
<link href="css/pagination.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(".delete").click(function()
{
var element = jQuery(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
jQuery.ajax({
type: "POST",
url: "content_list.php",
data: info,
success: function() {}
});
jQuery(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
</script>
<!-- form validation scripts -->
<script type="text/javascript" src="js/validate_category.js"></script>
<script type="text/javascript" src="js/validate_subcategory.js"></script>
<script type="text/javascript" src="js/validate_subsubcategory.js"></script>
<script type="text/javascript" src="js/selectall.js"></script>
<script type="text/javascript" src="js/validate_content.js"></script>
<script type="text/javascript" src="js/validate_resource.js"></script>
<script type="text/javascript" src="js/validate_data.js"></script>
<script type="text/javascript" src="js/ajax_scripts.js"></script>
</head>
Also my table is loaded by ajax call as Alpesh Panchal below pointed out.

Since your data table is loading by an ajax call, your selection of jQuery(".delete") is actually empty when it is trying to set the event handlers before the data is loaded. So, the solution is to set the event handler to the document itself and set a filter for your .delete element. Like this :
jQuery(document).on('click',".delete",(function()
{
//Your code
});

Make sure to check any javascript error using firebug console during page loading. Sometimes javascript errors prevents rest of javascript to execute.
Make sure that your table is not being loading by ajax call. If it is then jQuery's click event won't be binded to it. To bind it, you need to use ajaxStop() event handler to bind delete function.
If ajaxStop() doesn't work then you can create your delete click function separately and call it on "onclick" event of link
e.g.
<td>
Delete
</td>

With the jQuery .animate() method only numeric values can be animated (like "margin:30px"). String values cannot be animated (like "background-color:red").
Read more in jQuery docs.
Instead of animate use the .css() method of jQuery to change color and/or hide elements.

Related

Running JavaScript libraries (Looper) in Blazor Server-side - some javascript code is not running

I am trying to implement Looper theme to my blazor server-side app, and I have the javascript libraries referenced at the end of the in _Host.cshtml.However some scripts in theme.min.js is not running. Why?
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script src="_framework/blazor.server.js"></script>
My problem is that while
<div data-toggle="drowndown"></div> works, but hamburger menu toggle
<button class="hamburger hamburger-squeeze mr-2" type="button" data-toggle="aside-menu" aria-label="toggle aside menu"><span class="hamburger-box"><span class="hamburger-inner"></span></span></button>
does not work. What am I missing here? What am I doing wrong? My theme change script also isn't running. If I step through theme.js and I can see that this script runs when blazor is not active (commenting out blazor.js) but with blazor active, this script does not run.
(line 610) in /library/javascript/theme.js
}, {
key: "toggleAside",
value: function toggleAside() {
var _this4 = this;
var $trigger = $('[data-toggle="aside"]');
$trigger.on('click', function () {
var isShown = $('.app-aside').hasClass('show');
$trigger.toggleClass('active', !isShown);
if (isShown) _this4.hideAside();else _this4.showAside();
});
}
My educated guess is that theme.js is using something that blazor does not allow? Is anybody experienced enough with Looper theme (or with javascript in general) to know why it wouldn't work? Particularly the hamburger toggle and the theme switching code
(line 1992 in /library/javascript/theme.js)
var Looper = function () {
var Looper = new Theme(); // toggle skin thought button
$('[data-toggle="skin"]').on('click', function (e) {
e.preventDefault();
var skin = Looper.skin === 'dark' ? 'default' : 'dark';
Looper.setSkin(skin); // we need to refresh our page after change the skin
location.reload();
}).each(function () {
var isDarkSkin = Looper.skin === 'dark';
var $icon = $(this).find('.fa-moon');
if (isDarkSkin) {
$icon.addClass('far');
$icon.removeClass('fas');
}
}); // make it global
return Looper;
}();
This is the website https://worshipground.azurewebsites.net/ You can use the inspector tool to see that blazor has been correctly loaded and all the javascript files are loaded in /library/javascript and /library/vendor/...
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- End Required meta tags -->
<title> Starter Template | Looper - Bootstrap 4 Admin Theme </title>
<base href="~/" />
<meta name="theme-color" content="#3063A0">
<link rel="apple-touch-icon" sizes="144x144" href="Library/apple-touch-icon.png">
<link rel="shortcut icon" href="Library/favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans:400,500,600" rel="stylesheet">
<link rel="stylesheet" href="/Library/vendor/open-iconic/font/css/open-iconic-bootstrap.min.css">
<link rel="stylesheet" href="/Library/vendor/fontawesome/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="/Library/stylesheets/theme.min.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/theme-dark.min.css" data-skin="dark">
<link rel="stylesheet" href="/Library/stylesheets/custom-app.css">
<link rel="stylesheet" href="/Library/stylesheets/custom.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/custom-dark.css" data-skin="dark">
<script>
var skin = localStorage.getItem('skin') || 'default';
var isCompact = JSON.parse(localStorage.getItem('hasCompactMenu'));
var disabledSkinStylesheet = document.querySelector('link[data-skin]:not([data-skin="' + skin + '"])');
// Disable unused skin immediately
disabledSkinStylesheet.setAttribute('rel', '');
disabledSkinStylesheet.setAttribute('disabled', true);
// add flag class to html immediately
if (isCompact == true) document.querySelector('html').classList.add('preparing-compact-menu');
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
You may find you have your work cut out in terms of making a JavaScript heavy template work nicely in Blazor.
You will probably need to utilise IJSRuntime
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0
I think I know where this problem comes from! If you comment out the following code on the "Host.cshtml" file, this problem will most likely go away!
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
But!!!! You will get some javascript errors related to "WebSocket" instead! something like this:
"WebSocket is not in the OPEN state"
Or
"Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State."
The cause of these errors is a conflict between "pace.min.js" file and "blazor.server.js" file! You can check this link for more information and get more help

innerhtml result to a better format

I am very novice with coding, I just started learning about it a week ago.
To cut the story short, i have a code here.
function lookup (){
var mac_address = document.getElementById('mac_address');
var resultDiv = document.getElementById("result");
if(mac_address.value.length<6){
alert('Enter at least 6 characters!')
}else{
var lookUpAdress = '<object type="text/html" id="lookupresult" data="http://macvendors.co/api/jsonp/'+mac_address.value+'"></object>';
resultDiv.innerHTML=lookUpAdress;
}
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin">
<div style="padding:0px;">
<label>Enter mac address:</label>
<input type="text" id="mac_address" />
<input type="button" value="Lookup!" onclick="lookup();" />
<div id="result" style="margin-top:10px;" class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin">
</div><!-- Result. -->
</div><!-- Input Box. -->
</div><!-- Container. -->
</body>
</html>
I want to get the result of the Look Up and show it in a better format like :
Company :
Prefix :
Address :
Takenote I'd be happy just to get the "Company."
TIA.
Load jquery together with your html, make sure jquery is loaded otherwise you wont be able to use $.ajax and will have to go the javascript way. Also it is alot easier to use jquery than javascript to manupilate the dom. So if you are a beginner, first learn jquery then move on to javascript.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Use the above one or any other. You can google jquery cdn.
Then add a script to the bottom of your html:
<script>
$(document).ready(function(){
GetMacAddress();
});
function GetMacAddress(){
$.ajax({
url:'http://macvendors.co/api/jsonp/34:13:e8:1b:82:e4',
type:'get',
success:function(data){
// do something with data
alert(data.result.company);
},
error:function(){
console.log('oops');
},
});
}
</script>
This code will get you the result, change the code to suite your needs, i.e. display something in textbox
I guess this would solve your problem but:
You had to look up how to do it in non jQuery (or use jQuery)
I couldn't get it to work with https connections
$.getJSON('https://anyorigin.com/go?url=http%3A//macvendors.co/api/jsonp/34%3A13%3Ae8%3A1b%3A82%3Ae4&callback=?', function(data){
console.log(data.contents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You may read more about it here:
https://medium.freecodecamp.org/client-side-web-scraping-with-javascript-using-jquery-and-regex-5b57a271cb86

JQuery parent selector and fadeout

I'm trying to make a simple ToDo list in JQuery and I run into a problem.
I made function 'deleteListItem' and I use it to delete my lists items with:
$(this).parent().remove();
, and then I wanted to add fadeOut effect to my list and so I tried:
$(this).fadeOut(1000, function(){
$(this).parent().remove();
})
, but this fadesOut just my delete button so then I tried
$(this).parent().fadeOut(1000, function(){
$(this).parent().remove();
})
and this fades all of my 'ul' instead of just 'li' element.
Here is mine JSBIN so you better understand what I'm doing: http://jsbin.com/ciyufi/edit?html,js,output
Inside the callback handler, this refers to the <li>.
$(this).parent().fadeOut(1000, function(){
$(this).remove();
})
// This is where I put my functions
// This function adds items on our list
function addListItem() {
var text=$('#newText').val(); // val returns any text thats inside input
$('#todoList').append('<li><input type="checkbox" class="done">'+ text +'<button class="delete">Delete</button></li>');
$('#newText').val(''); // this is added so that our input deletes previous text when add is clicked
};
// This function deletes items on our list
function deleteListItem() {
// In order to delete entire list item we have to use parent method > without parent method we would only delete our delete button
$(this).parent().fadeOut(1000, function(){
$(this).closest("li").remove();
})
};
// This function adds checked remark on our item list
function itemDone() {
// First we check if our element has textDecoration="line-through"
// If it has it second line deletes it
// And our else statement allows as to add it again
if ($(this).parent().css('textDecoration') == 'line-through') {
$(this).parent().css('textDecoration', 'none');
} else {
$(this).parent().css('textDecoration', 'line-through');
}
}
$ (document).ready(function(){
$('#add').on('click', addListItem); // This is for button to add text
// This part enables us to add text on pressing enter key
$( "#newText" ).keypress(function( event ) {
if ( event.which == 13) {
addListItem();
}
});
// $('.delete').on('click', deleteListItem);
// $('.done').on('click', itemDone);
// Lines above don't work because we are adding elements after page loads
// In above lines browser didn't bind functions to our new elements because it didn't see them at the time
// In order to make it work we add document selector > its not the best solution but i'm not good enough for better
// We don't need to do it for #add because its already on page
$(document).on('click', '.delete', deleteListItem);
$(document).on('click', '.done', itemDone);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>ToDo Lista</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<section class="container">
<h1>ToDo List</h1>
<ul id="todoList">
<li><input type="checkbox" class="done"> Clean House <button class="delete">Delete</button></li>
<li><input type="checkbox" class="done">Buy Milk <button class="delete">Delete</button></li>
<input id="newText" type="text" placeholder="Write Your Task"><button id="add">Add</button>
</ul>
</section>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
I prefer to use closest. closest Just change 'deleteListItem' function to remove closest li item on delete.
function deleteListItem() {
// In order to delete entire list item we have to use parent method > without parent method we would only delete our delete button
$(this).parent().fadeOut(1000, function(){
$(this).closest("li").remove();
})
};

Handlebarsjs : H1 tag won't display when submit button is clicked

I'm messing around with Handlebars.js and I'm doing a very simple example consisting of a tutorial from a website(the shoes section) and my own simple little template(the heading, where the problem is)
handlebardemo.html
<head>
<meta charset="ISO-8859-1" name="viewport" content="width=device-width, initial-scale=1">
<title>Handlebar demo</title>
<script src="lib/jquery-2.1.4.js" type="text/javascript"></script>
<script src="lib/jquery-ui.js" type="text/javascript"></script>
<script src="lib/handlebars-v4.0.4.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/w3.css">
<link rel="stylesheet" href="css/jquery-ui.css">
</head>
<body>
<div class="username-container">
<script id="heading-template" type="x-handlebars-template">
<h1 class="h1">Hello {{username}}</h1>
</script>
<input type="text" id="username">
<button type="submit" id="username-submit">Enter</button>
</div>
<h4 class="w3-row-padding">Shoe List:</h4>
<ul class="shoesNav w3-ul w3-text-indigo"></ul>
<script id="shoe-template" type="x-handlebars-template">
{{#each this}}
<li class="shoes">{{name}}--Price:{{price}} </li>
{{/each}}
</script>
</body>
main.js
$("#username-submit").click(function(){
var uNameVal = $("#username").val();
var uName = {"username":uNameVal};
var theTemplateScript = $("#heading-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(".username-container").append(theTemplate(uName));
});
$(function (){
var shoesData=[{name:"Nike", price:199.00}, {name:"Loafers", price:59.00}, {name:"Wing Tip", price:259.00}];
//Get html from tempalte in script tag
var theTemplateScript = $("#shoe-template").html();
//Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
$(".shoesNav").append(theTemplate(shoesData));
//shoesData is passed to compiled handlebars function
//function inserts values from the objects in their respective places in the HTML
//and returned HTML: as a string. Then jQuery is used to append the resulting HTML string to the page
})
Im not sure if I'm using the handlbars syntax etc. correctly, but i based it mostly off of the second function in main.js, which came from a brief handlebars tutorial
When I click the Enter button, nothing happens. There are no console errors, it just does nothing. Am I going about this the wrong way, at least compared to the unordered list example?
EDIT: As per Elli Parks answer, I added an id to the submit button and changed the click handler assignment to the submit button rather than the textbox(a silly mistake on my part). The element still won't appear when the submit button is clicked
In main.js, you're attaching the click handler to #username, which is an input field. You need to give the Enter button an id (ex: #username-submit) and attach the click handler to the button.
So something like this:
handlebardemo.html
<button type="submit" value="Enter" id="username-submit" >Enter</button>
main.js
$("#username-submit").click(function(){
var uNameVal = $("#username").val();
var uName = {"username":uNameVal};
var theTemplateScript = $("#heading-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(".username-container").append(theTemplate(uName));
});
You need to change two things:
fix the selector to target the button, like #ElliPark has already said
put the whole thing into the document-ready handler (ie, into the $(function () {...} ); construct. You are trying to attach the event listener before the DOM is ready.
See the demo on JSBin.

Ajax in Tinybox 2

I have a Tinybox 2 popup opening when clicking 'register'. The user has then to choose if he/she wants to register as a user or a performer. I'd like to show a different registration page for each, but first asking it, so handling with ajax would be the best. It can be done, as shown here, in the 5th example. Here is my current code:
<!doctype html>
<html>
<head>
<title>Regisztrációs típus kiválasztása</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="../css/soon.css"/>
<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
</head>
<body>
<div id="teljes">
<h1>Miként szeretnél regisztrálni?</h1>
<div id="felhasznalo">
Felhasználóként
</div>
<div id="eloado">
Előadóként
</div>
</div>
<script type="text/javascript">
$('#felireg').click(function() {
$.get("../php/register.php");
});
</script>
</body>
</html>
Thanks!
If i understand correctly, you want to make an ajax call to your registration file named "register.php" and show this in a Tinybox
$('#felireg').click(function() {
TINY.box.show({
url:'../php/register.php',width:300,height:150
})
});
This should work.
//EDIT :
Assuming your file returns only html:
$('#felireg').click(function() {
$.get("../php/register.php", function(data)
{
TINY.box.fill(data);
});
});
This should update the current Tinybox

Categories

Resources