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).
Related
I need build code such : http://fiddle.jshell.net/bwKZt/152/
but my code dosen't work ! I am a beginner. Please help me.
index.php:
<!DOCTYPE html><html>
<head>
<script>
$("#label").bind("keyup", changed).bind("change", changed);
function changed() {
$("#url").val(this.value);
}
</script>
</head>
<body>
<input type="text" id="label" />
<input type="text" id="url" readonly />
</body>
</html>
Some of the JavaScript here isn't native JavaScript , but is using a plugin called jQuery that makes searching and manipulating HTML elements easier.
When you see $(), that's the jQuery way of finding elements. But it won't work because you don't have jQuery referenced at all.
If you don't want to use jQuery, you can find elements with something like document.getElementById('label').
But lots of people use jQuery to make referencing page elements short and sweet, as with $('#label').
Try to reference jQuery first, like:
<!DOCTYPE html><html>
<head>
<!-- The below line references an externally hosted copy of jQuery 2.2.4 -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
// The below chunk is telling it to bind to the keyup event only AFTER the document has fully loaded.
// Sometimes when your binding code is executed, the elements you wish to bind to aren't loaded yet.
$(document).ready(function(){
$("#label").bind("keyup", changed).bind("change", changed);
});
function changed() {
$("#url").val(this.value);
}
</script>
</head>
<body>
<input type="text" id="label" />
<input type="text" id="url" readonly />
</body>
</html>
The first problem is because you haven't include jquery with a script tag to solve that add this code in the head of you html file if you have the Internet connection to load Jquery from CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
or you can download Jquery file from Jquery site and you will have it locally
after that you must execute this code after the executing the jquery ready function
$(document).ready(function(){
$("#label").bind("keyup", changed).bind("change", changed);
function changed() {
$("#url").val(this.value);
}
})
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 () {
So what i want to do is when i click on a button, it will pass this click event to another element in webpage, or you can say it will create a new click event in another element. Below is my code, it does not work, please let me know what is wrong with it, it looks make sense...
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" onClick=alert("error") /></p>
<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>
</body>
</html>
Since you are using jQuery you can use this onClick handler which calls click:
$("#datepicker").click()
This is the same as $("#datepicker").trigger("click").
For a jQuery-free version check out this answer on SO.
The smallest change to fix this would be to change
onClick="document.getElementById("datepicker").click()">
to
onClick="$('#datepicker').click()">
click() is a jQuery method. Also, you had a collision between the double-quotes used for the HTML element attribute and those use for the JavaScript function argument.
To simulate an event, you could to use trigger JQuery functionnality.
$('#foo').on('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
The reason your code isn't working the way you would expect is because this line:
<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>
should be changed to:
<button type="button" value="submit" onClick="document.getElementById('datepicker').focus()">submit </button>
There are two things to notice here:
1: The "s around datepicker have been changed to 's so that they do not interfere with the quotes surrounding the onclick event.
2: The click() has been changed to focus() to activate the datepicker calendar. When the button is pressed.
Now, this fixes your issue...but I do agree with the other posts that using jQuery to access the DOM element and trigger the event is the better way to go. Since you're already doing this for the jQuery datapicker plugin via <script src="http://code.jquery.com/jquery-1.8.3.js"></script>, this should not be a problem.
Inline events are not recommended.
Or you can use what JQuery alreay made for you:
http://jqueryui.com/datepicker/#icon-trigger
It's what you are trying to achieve isn't it?
try this
document.getElementById("datapicker").addEventListener("submit", function())
Use this
jQuery("input.second").trigger("click");
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.
I have tried to set a item to read only, as you see in the code i have tried several way and can't get that to work. Can anyone help me with this?
<html>
<script>
//test.Attributes.Add("readonly","readonly")
//document.getElementById('testtt').setAttribute('readonly', 'readOnly');
// document.getElementByID('test').value=readOnly;
//document.getElementByID('test').readOnly = true;
// $("#test").attr("readonly", "readonly");
//$("#test").removeAttr("readonly");
//$('#test').attr('readonly', 'readonly');
$("#test").attr("readonly")
</script>
<body>
<input id="test" type="text" value="text" />
</body>
</html>
$('#test').attr('readonly', true);
working example : http://jsfiddle.net/FBUDt/
this should work for you:
$("#test").attr("readonly", "readonly");
remember that the DOM needs to be loaded before you try to find the element
you could use jquerys DOM-ready
$(function() {
$("#test").attr("readonly", "readonly");
});
what version of jquery are you using?
You should try wrapping your code into $('document').ready();
According to the documentation,
The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
So it would be:
$('document').ready(function(){
$("#test").attr("readonly", "readonly");
});
You can't refer to an element that is created later in the document. Move the script down below the form, or place it in a document.ready block. Also, you should use $.prop() in jQuery 1.6+
$(function(){
$('#test').prop('readonly', true);
});
I would go with
document.getElementById('test').setAttribute('readonly', 'readOnly');
But that is not the issue. The position of your script is where it goes wrong. You are trying to change element which does not exist.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>testcase</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css" />
</head>
<body>
<div class="some container">
<input id="test" type="text" value="text" />
</div>
<script type="text/javascript" charset="utf-8">
document.getElementById('test').setAttribute('readonly', 'readOnly');
</script>
</body>
</html>
If you place your scripts right befor the closing </body> tag , then it is executes as soon as DOM has been built.
And please. Stop using JS libraries to do the most basic things.
you are missing
$(document).ready(function() {
$('#test').attr('readonly', 'readonly');
});
sample
http://fiddle.jshell.net/Pe4J5/