Issue with editing JQuery document - javascript

The code does not run as written. If the button click part (the 3 lines after the first alert) is removed it works fine. It seems like any edits made to the JS/JQ area lead to issues. What could be going wrong here?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Problem #2</title>
<link rel="stylesheet" href="css/style.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Problem #2:</h1>
<form>
<input type="number" placeholder="Enter your cents" min="0" />
<input type="button" name="Solve" value="Solve" />
</form>
<div id="answer">
<div id="quarters"></div>
<div id="dimes"></div>
<div id="nickels"></div>
<div id="pennies"></div>
</div>
<script src="js/jquery-2.0.3.min.js"></script>
<script>
$( document ).ready(function() {
alert("Handler for .ready() called.");
$('button').click(function{
alert("Hello World");
});
});
</script>
</body>
</html>

This has a syntax error:
$('button').click(function{
alert("Hello World");
});
and needs to be this (missing parens):
$('button').click(function () {
alert("Hello World");
});
In the future, you should look at the debug console and it will tell you what line your syntax errors are on and often give you an idea what the error is. You can also run your code through jsHint (just paste in the relevant code) and it will often give you details on where syntax is wrong or suspect.
In addition, since you don't have any <button> tags in your HTML, your selector is also probably wrong. If you're targeting the solve button, then you should probably change your HTML like this:
<input id="solve" type="button" name="Solve" value="Solve" />
and your HTML like this:
$('#solve').click(function () {
alert("Hello World");
});

You are missing the parenthesis after function in the third line of your script.
Also, as #ArtOfCode in the comments said, your selector should be input[type=button].
It should look like this:
$('input[type=button]').click(function () {

Related

change() fires on page loading

Quick background:
I got a project that some developer worked on a couple of years ago and his code is a nightmare, let alone that almost all the software is outdated. The JQuery in the project is still 1.5.2 but I was able to work around that using the non-conflict option of JQuery.
However, I still can't seem to make the change() function work properly - it fires when the page is being loaded. Furthermore, for some strange reason, the On() function doesn't work either.
Here's the code (below the body):
jQuery_3_2_1(document).ready(function(){
jQuery_3_2_1("input[id^=DepartureDay]").on('change',alert('dd'));
And here's the non-conflict function (if it's relevant):
<script type="text/javascript">
var jQuery_3_2_1 = $.noConflict(true);
</script>
I don't know if it's relevant, but wired thing about the code is that the previous programmer decided load all the HTML using JS strings. Another thing that I should note is that I'm trying to detect a change in the value of a uikit datepicker.
Thank you for your help!
I add a fiddle:
https://jsfiddle.net/vzeuhohm/1/#&togetherjs=Sietj3k5oM
Another edit:
https://jsfiddle.net/vzeuhohm/2/
Another edit:
I attach the full code in the hope that someone would be able to understand what is wrong with it -
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="uikit.docs.min.css" type="text/css">
<script language="javascript" src="https://getuikit.com/v2/vendor/jquery.js"></script>
<script language="javascript" src="https://getuikit.com/v2/docs/js/uikit.min.js"></script>
<script language="javascript" src="https://getuikit.com/v2/src/js/components/datepicker.js"></script>
<link href="example160/css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="example160/js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="example160/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.slim.js"></script>
<script type="text/javascript">
var jQuery_3_2_1 = $.noConflict(true);
</script>
<script type="text/javascript">
jQuery_3_2_1(document).ready(function(){
jQuery_3_2_1("[id^=DepartureDay]").ready(function(){
jQuery_3_2_1("[id^=DepartureDay]").on('input',function(e){
alert('ff');
});
});
});
</script>
</head>
<body>
<form method="post">
<input type="text" name="DepartureDay1" id="DepartureDay1" data-uk-datepicker="{format:'DD.MM.YYYY'}" placeholder="mm/dd/yyyy" />
</form>
<div>TODO write content</div>
</body>
</html>
You're trying to use the result of calling alert('dd') as the change handler.
You probably want to wrap the alert in a function, and pass that function as the handler instead:
jQuery_3_2_1("input[id^=DepartureDay]").on("change", function() {
alert("dd");
});
Instead of using $(document).ready(), try using
$(window).on('load', function() {
$("input[id^=DepartureDay]").on('change',alert('dd');
});
EDIT
var jQuery_3_2_1 = $.noConflict(true);
jQuery_3_2_1(document).ready(function(){
jQuery_3_2_1('[id^=DepartureDay]').on('input', function(){alert('dd');});
});
Instead of .on('change'..., use .on('input'...).
You also have to say function(){alert('dd');} instead of just alert('dd').
try following code
textbox change event doesn't fire until textbox loses focus.
that's why i am posting both example
jQuery_3_2_1(document).ready(function(){
jQuery_3_2_1("input[id^='DepartureDay']").on("change", function() {
alert("your change event is working !!!");
});
});
jQuery_3_2_1("input[id^='DepartureDay2']").on('change keyup paste', function() {
console.log('your change/keyup event is working !!!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
</script>
<script type="text/javascript">
var jQuery_3_2_1 = $.noConflict(true);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<input type="text" name="DepartureDay" id="DepartureDay" />
<input type="text" name="DepartureDay2" id="DepartureDay2" />
</form>

JQuery Failed to Handle Button's On Click Event

I know this question may be stupid, but I'm new to JQuery and failed to guess (even after hard search at Google) Why My Function failed to Show me Alert on Click Event of Button, (I'm trying to do more tasks but for debugging purpose I'm showing alert).
<!DOCTYPE html>
<html>
<head>
<title>WebSite Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
$(document).ready(function(){
$('#foo').click(function(){
alert('ggg');
});
});
</script>
</head>
<body>
<input type="button" name="" value="Get Data" id="foo">
</body>
</html>
As #Pranav mentioned, you should separate the scripts, so each can work.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquer‌​y.min.js"></script>
<script>
$(document).ready(function() {
$('#foo').click(function() {
alert('ggg');
});
});
</script>
I'm Totally Agreed with Answers of above two users, You have to Put Your Code away from the tags referencing the Libraries, What you need to do is place your logical code may be of Javascript or JQuery in Another Script Tags

JQuery click event on all buttons with id starting with custom text

Using JQuery, I need to write a function, called on click for any of the two buttons (edit0, edit1).
I have the following code:
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$('[id^=edit]').click(function() {
alert("1111");
});
</script>
</head>
<body>
<button id="edit0" class="edit"> edit </button>
<button id="edit1" class="edit"> edit </button>
</body>
</html>
When I run it, nothing happens on button click.
I tried to replace the script with:
$('button[class="edit"]').click(function() {
alert('1111');
});
But the result is the same.
You can simply use CSS3 [attribute^=value] Selector to implement 'click event on all buttons with id starting with custom text' as you wish, like below.
$('button[id^="edit"]').click(function() {
alert('111');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<button id="edit0" class="edit"> edit </button>
<button id="edit1" class="edit"> edit </button>
<script type="text/javascript">
$('[id^=edit]').click(function() {
alert("1111");
});
</script>
</body>
</html>
And also, put your code just before the closure </body> tag to ensure your dom is ready when the code runs.
I normally see that syntax for addressing custom attributes, try this.
$('button.edit').click(function() {
alert('1111');
});
Also put your script below your HTML. Or use a jQuery on document ready. Remember JavaScript/JQuery are executed sequentially.

How to activate alert function in html

This is a basic question of javascript.
I'm doing my personal webpage. When people click the button ("botón") this message should appear: "clicked!"
My html5:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
<link href="website.css" rel="stylesheet"/>
<script src="script.js"></script>
</head>
This is the specific part of the button:
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button>botón</button>
My javascript code: (stored in the file: "script.js")
$("button").on("click", function() {
alert("clicked!")
});
But i click and no message appear (Chrome or Firefox).
UPDATE 1:
Apparently, i was following a Jquery tutorial.
I need to do that in basic javascript. What should i do. Code examples are welcome.
UPDATE 2: Based on suggestions, my code still does not work.
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
My new script:
document.getElementById('myButton').addEventListener('click', function(){
alert('clicked');
}), false);
document.getElementById('myButton').addEventListener('click',function(){
alert('Clicked!');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
</head>
<body>
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
</body>
</html>
Make sure to place your script right in front of the closing </body> tag, the elements can't be found if the DOM isn't loaded at the time your script gets loaded:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
<link href="website.css" rel="stylesheet"/>
</head>
<body>
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
<script src="script.js"></script>
</body>
</html>
script.js
document.getElementById('myButton').addEventListener('click',function(){
alert('Clicked!');
});
You should add an id to your button, then:
document.querySelector("#mybutton").addEventListener("click",function(){
alert("BUTTON CLICKED");
});
Where mybutton is your button ID. Try to work with IDs so your DOM query isn't getting more than one element.
Example:
http://jsfiddle.net/fthupjpd/
EDIT: Don't use jQuery for that :)
You dont have the jquery lib in your html, but you are using $, which is part of jquery (it's the facade for the api/lib)
add:
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
before you cann you click code. You need to also make sure the dom has loaded when you call you event handler, try:
$(function () {
$("button").on("click", function() {
alert("clicked!")
});
});
IF you dont want to use jQuery, give your button an id
<button id="myButton">botón</button>
then in your code
document.getElementById('myButton').addEventListener('click', function(){
alert('clicked');
}), false);
Here are the docs on native event handlers
document.getElementById('myButton').onclick=function(){
alert('clicked');
};
For a good start with JavaScript, I find W3schools very good:
http://www.w3schools.com/js/default.asp
EDIT
see Michael's answer for where to place your scripts when you need them to access the document elements. The body needs to be loaded before you can reference them on your JS code.
You have two problems.
You haven't defined $. It looks like you are trying to use the jQuery library. You need to include that in your page before the script.
You are trying to bind an event handler to all the button elements in the document while the head section is being parsed. At that point, there is no button elements. You need to move the script element to after the button elements (or use a ready or load event hander).

I get an undefined error in my error console

My myclickHandler function works perfectly but when I go on to my error console I get this error:
document.getElementsByName("prequestion")[0] is undefined;
Below is my code
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
if(validation()){
openSessionPopup();
}
</script>
</head>
<body>
<form action="create_session.php" method="post" name="sessionform">
<p><strong>10: </strong><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="myClickHandler()"/></p>
</form>
</body>
My question is what do I need to remove this error? because my function works does it matter if it shows an error in the error console?
Chances are you're loading the javascript before the DOM (or even possibly the HTML) has loaded properly.
For example, the following reproduces the same error as described in your question :
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
}
</script>
<input type="" name="prequestion" />
Whereas the following does not. The error is not present and the code works fine.
<input type="" name="prequestion" />
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
}
</script>
Trying to attach the event listener to an element which doesn't technically exist yet causes problems. You can check for the browser reporting the page has been loaded before attaching the event if needs be but be aware that browsers report this in different ways. Librarys such as jQuery provide useful means to test this such as $(document).ready(function(){});
Edit: I've just seen that you've added the relevant HTML too. It appears that this is in fact the case and the reason you're still seeing the expected behavior is because you're also using the onclick="" attribute on the input element. This is where the function is being called on click, and the event handler isn't being attached as you expect.
Edit #2: You also appear to be missing a closing } for your function. And I've now tested with your exact HTML and moving the script to just above the body tag resolves the error and correctly attaches the function to the click event.
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
</head>
<body>
<form action="create_session.php" method="post" name="sessionform">
<p><strong>10: </strong><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" /></p>
</form>
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
} // This was missing
</script>
</body>
I suspect that the problem is that there are no elements with the name attribute set to "prequestion".
If you're getting that error, then your script doesn't actually work, so you should fix it.

Categories