When I click on button, nothing happens - javascript

I have following HTML,
$(document).ready(function() {
$('#searchMovieBtn').click(function(e) {
e.preventDefault();
console.log('search');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="searchMovieBtnBox">
<button class="btn btn-primary" type="button" id="searchMovieBtn">Search</button>
</div>
When I click on button, nothing happens, it seems like event is not triggering.

It is a caching issue. When you was developing and testing your JQuery code, your old code remained into the browser cache. Browser cached it to load page faster in next uses. In order to solve this problem you have 3 options.
Delete your browser history
Refresh your browser by pressing Ctrl + F5 (Preferred for developing purpose)
Tell browser that this JQuery code has changed by adding a version for it. It is used when you are publishing your code on the server because you can't ask your clients to delete their browser history or load your page by pressing Ctrl + F5
Here is how you could add version to your JQuery code:
<script type="text/javascript" src="js/script.js?v=1"></script>
Look at v=1. Next time when you updated your JQuery code change it to v=2 to tell browser that your code has been changed.

You can try the next thing,
First of all, your HTML markup I think it might be wrong as you are not pointing out correctly the folders.
I attached all the css and js bootstrap + jquery files through a CDN.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"</script>
<script type="text/javascript" src="js/script.js"></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<title> jQuery button click event working?</title>
</head>
<body>
<div id="searchMovieBtnBox">
<button class="btn btn-primary" type="button" id="searchMovieBtn">Search</button>
</div>
</body>
</html>
Therefore,your script.js stays as it is.
For me it has worked like this. I got the message printed onto my console.
Hope that helps you.

Make sure you don't have another element in the HTML with the same id.

Related

I get "function is not defined" when I move a Javascript function from in-line code, to a separate js file

I am trying to make a very simple thing work:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script src="js/test.js" type="text/js"></script>
<button onclick="test()" type="submit">Test</button>
</body>
</html>
With js/test.js being found by the browser and containing:
function test() {
alert("test");
}
When opening the page and clicking the button, nothing happens and I can see in the console:
Uncaught ReferenceError: test is not defined
at HTMLButtonElement.onclick (test:7)
I have tried to move the script import above or under the button, or in the header.
I have tried to use "window.setlocale = function" in my js file.
I have tried to put nothing in the test method.
I checked for errors with JSLint (there is no error).
When I check the source, I can see the js file and the browser opens it when I click on it.
The only way I can get the Javascript to work is to write it inline...
Maybe the issue is with my environment?
In order to run this, I use an Apache server, and it is configured to serve this on localhost:8077. I works fine so far.
I use Laravel 7.10, PHP 7.4... working fine. To run this I created a simple route, that shows the view (a simple index.blade.php) with the HTML content copy/pasted above. It displays fine on "http://localhost:8077/test", no problem.
I also tried to use the laravel notation
<script src="{{ asset('js/test.js') }}" type="text/js"></script>
but it gives the same result.
I also have the PHP debugbar (a Laravel plugin) active, and it does not show any error. The view is properly loaded and displayed.
Also, I use PHPStorm, and it does not detect any issue.
It's been 2 days and I cannot makes this seemingly extremely basic thing to work, please help me m(_ _)m
Your script type is wrong. Use application/javascript in your script element to make your javascript work - or better yet, remove the type attribute and let browsers auto-detect the type:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script src="js/test.js" type="application/javascript"></script>
<button onclick="test()" type="submit">Test</button>
</body>
</html>
Without type attribute:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script src="js/test.js"></script>
<button onclick="test()" type="submit">Test</button>
</body>
</html>
you can try to add script tag to header tag. like this
<head>
<script type="text/javascript" src="path/to/script.js"></script>
<!--other script and also external css included over here-->
</head>
Try removing the function name in js/test.js
function() {
alert("test");
}
Please add the js file as a reference in the header section of your core file. External referencing.

My jQuery code doesn't answer to button clicks

I have been trying to use jQuery in order to get some text written on the same page I have opened. I inserted a button, but it is not working on my Django server. After doing some research I noticed that the code works on some servers and doesn't work on others.
For example, I wrote the snippet below and it will be posible to notice that buttons work on it, but when I bring it to my server or to repl.it, the first button never works.
I intend to use exactly the first button example to produce my codes. Can anyone help me to clarify the reasons the above mentioned button doesn't work sometimes?
$("#sentiment_training").click(function(){
/* This is a work in progress yet */
alert("Using jQuery in a File");
});
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="script.js"></script>
<script>
function myFunction() {
alert("Alert with inline script");
};
$("#sentiment_training3").click(function(){
/* This is a work in progress yet */
alert("Using jQuery Inline");
});
</script>
</head>
<body>
<button id="sentiment_training" name="sentiment_training" class="btn btn-primary mb-2">jQuery in a file</button>
<button id="sentiment_training2" name="sentiment_training2" class="btn btn-primary mb-2" onclick="myFunction()">JavaScript Inline!</button>
<button id="sentiment_training3" name="sentiment_training3" class="btn btn-primary mb-2">jQuery Inline</button>
</body>
</html>
The reason this doesn't work is that the document is not yet loaded at the script's runtime. Moving your scripts to the end of body is a solution. You can also create an event, which will be triggered on document load and run your script afterward.
Put the code inside a $(document).ready(function() {}) block.
This ensures that the code will only run after document is "ready."
$(document).ready(function() {
$("#sentiment_training3").click(function(){
/* This is a work in progress yet */
alert("Using jQuery Inline");
});
})

Can't see localstorage event across tabs

I'm trying to create a simple proof-of-concept regarding the use of localStorage to trigger tabs in my application when changes occur. I know this is possible based on other articles I've seen. I understand the spec states the event will fire on ever page except the one I'm on - this is in fact what I want. However, I can't seem to get this simple demo to actually work.
I've taken the code below, and opened up multiple tabs of it. Using my Chrome Dev Tools, I can check >localStorage in the console and see the value before and after the "Add" and "Clear" buttons are pressed - they are in fact functioning as desired in storing and clearing the key value pair into local storage, yet the event isn't firing the alert.
I even placed breakpoints in the javascript in my Chrome Dev Tools of each tab, yet I can never seem to get the "onStorageEvent" function to hit in any tab opened.
What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Tab1</title>
</head>
<body>
<button id="add" onclick="localStorage.setItem('tab','changed')">Add</button>
<button id="clear" onclick="localStorage.clear()">Clear</button>
<script type="text/javascript">
function onStorageEvent() {
alert("storage event: " + localStorage.getItem("tab"));
}
window.addEventListener('storage', onStorageEvent, false);
</script>
</body>
</html>
In order for the window.addEventListener to work on storage:
you MUST access the page using web-server (http://a.b.c.d/ or http://domain)
Direct access (using file:/// or c:\file.html will not work.
(chrome and ie ignore it, firefox and safari can run it anyway).
I would consider also removing the 3rd, it is not relevant to elements in your DOM tree, and it might cause troubles (let the browser have it's defaults).
This code was tested in Chrome 52, Firefox 47+48, IE 11, Safari 5.7.1
<!DOCTYPE html>
<html>
<head>
<title>Tab1</title>
</head>
<body>
<button id="add" onclick="localStorage.setItem('tab','changed')">Add</button>
<button id="clear" onclick="localStorage.clear()">Clear</button>
<script type="text/javascript">
function onStorageEvent() {
alert("storage event: " + localStorage.getItem("tab"));
}
window.addEventListener('storage', onStorageEvent);
</script>
</body>
</html>

Jquery mobile pageshow event does not fire when second page is shown

I have working javascript mobile app which I have been trying to restructure (correctly or incorrectly). The index.html file contained one page (using data-role="page") with various <div> elements that I hide and show depending what the user wants to do. I thought I could improve the structure by putting each of these <div> elements each in their own page (still in the index.html file) using data-role again. However, the subsequent pages lose their javascript functionality. I have created a very simple index.html file to demonstrate:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" />
<script type="text/javascript" src="js/jquery-1.9.1.min.js"/></script>
<script type="text/javascript" src="js/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<div data-role="page" id="mainPage">
<INPUT type="button" id="showPageTwo" value="Show Next Page" />
</div>
<div data-role="page" id="secondPage">
<INPUT type="button" id="showMainPage" value="Show Main Page" />
</div>
<script>
$(document).on("pageshow", "#mainPage", function(e) {
alert("Main page");
$("#showPageTwo").click(function()
{
$("#secondPage").show();
$("#mainPage").hide();
});
});
$(document).on("pageshow", "#secondPage", function(e) {
alert("Second page");
$("#showMainPage").click(function()
{
$("#mainPage").show();
$("#secondPage").hide();
});
});
</script>
</body>
</html>
Main page displays correctly, the alert is displayed $("#showPageTwo").click(function() works. But none of the javascript runs when secondPage loads.
Additionally when secondPage is shown it does not have the styling from jquery.mobile-1.3.2.min.css that mainPage has.
What am I doing wrong or misunderstanding? (This is when running the app in the Eclipse AVD)
Additionally, I would like to know:
Is the way I am trying to restructure my code using data-role="page" good or bad practice? Is there a recommended way to structure "pages" in a mobile app?
I also want to put my custom script(s) in their own .js file(s). Can I only load the script shown in the above code before the </body> tag? Is there any way to load it in the header along with all the other scripts?

Trouble with jquery link in html5 file

So here's my html code (Important part is in the triple quotations):
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
<link rel="stylesheet" type="text/css" href="ToDoApp.css"/>
"""<script type="text/javascript" src="ToDoApp.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>"""
</head>
<body>
<h2>To Do</h2>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<div id="button">Add!</div>
<br/>
<div class="list">
<ol></ol>
</div>
<div class = "counter">
<h4>Things to do:</h4>
</div>
<div class = "comment"></div>
</body>
</html>
and my .css connection is working perfectly, but my .js/jquery connection is just not functioning. I've tried looking up correct html syntax for including a link, and I tried alternating among a few different links to the jquery library. Is there something I'm missing here, have I put the link in the wrong place, or is the syntax funky? Thanks in advance for any help.
If your ToDoApp.js relies on jQuery then you will need to change the order of your code.
<link rel="stylesheet" type="text/css" href="ToDoApp.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script src="ToDoApp.js"></script>
Otherewise, the code that you have supplied shows not reliance on jQuery.
The best way I have found to debug issues with JS or CSS files not being included, is to monitor the network traffic with your browsers Debugging tools.. In IE, press F12, and then click on the Network tab. Click 'Start Capturing' and re-navigate to the page.
If a 404 is returned, the path is probably wrong.. From here, you can look at the path the application actually tried to request its file from.
Other errors require different investigations. If you don't even see the file show up in the requests list, then check the Console tab to see if the browser has logged any messages that may pertain to the situation. As per Jeff's answer, if the problem is that something in your ToDoApp.js relies on jQuery, then you will see messages in the console that point to that issue, such as $ is undefined.

Categories

Resources