javascript onkeypress input text - javascript

I am learning Javascript.. Below code working only if my script tag below my input text element, but if i place code above input text tag, its not working. May I know why? Below is code:
<head>
</head>
<body>
<input type="text" id="name" >
<script type="text/javascript">
var txtId = document.getElementById('name');
txtId.addEventListener('keypress', function(e){
console.log('Pressed!')
})
</script>
</body>
Below code is same as above except that I am using function, inside which I am using same code as above. But in this case, my script tag is above input text tag, and its working. How it's working in this case? Below is the code:
<head>
<script type="text/javascript">
function keyPressListener(){
var txtId = document.getElementById('name');
txtId.addEventListener('keypress', function(e){
console.log('Pressed!')
})
}
</script>
</head>
<body>
<input type="text" id="name" onkeypress="keyPressListener()">
</body>
So, what exactly difference between above 2 codes?

When you are using the onkeypress attribute. It actually works the same way as the addEventListener. You just have to write a simple function and call it in onkeypress
<input type="text" id="name" onkeypress="keyPressed()">
<script>
function keyPressed(){
console.log('Key Pressed');
}
</script>

Why is not working to place above the input
-Because document was not ready .so you need body.onload event .see the body onload=start() it will apply the js function after body loaded
<body onload="start()">
<input type="text" id="name">
<script type="text/javascript">
function start() {
var txtId = document.getElementById('name');
txtId.addEventListener('keypress', function(e) {
console.log('Pressed!')
})
}
</script>
</body>
And the second one -you are using two function in a single event. So use with any one of the event
if use with inline keypress of keyPressListener() else use Dom event of the
keypress (addEventListener)
*Note:
Dont include the addEventListener() inside keyPressListener() .
If you use with addEventListener() remove the onkeypress event inline of the markup.
because both are same action .
<head>
<script type="text/javascript">
function keyPressListener() {
console.log('Pressed!')
}
</script>
</head>
<body>
<input type="text" id="name" onkeypress="keyPressListener()">
</body>

You can use addEventListener.
Or try this as your input:
Add a ; after keyPressListener():
<input type="text" id="name" onkeypress="keyPressListener();">
If that doesn't work try this:
<input type="text" id="name" onkeypress="keyPressListener(); return true;">
HTML5 knows that when you use an onkeypress attribute that it needs to call the JavaScript function when the key is pressed. You can basically put any functional JavaScript in the parameter for the onkeypress="(JavaScript goes here)" attribute.
You can also just grab the element from the DOM and then add the event listener to the element like so:
jQuery: $('#name').onkeypress( function() { //code goes here } );
Regular Js: document.getElementById('name').onkeypress( function() { //code goes here } );

Related

Javascript code not being executed on button click

I have some html and some javascript code that is supposed to take input in a text box, and open a new tab with the Wikipedia page of whatever was in the text box. However, I'm using this as an extension, and google chrome doesn't allow inline javascript.
page.js
document.getElementById("search").addEventListener("click", searchPage);
function searchPage() {
console.log("test")
var temp = document.getElementById(pageName);
var temp = temp.value;
var myPage = "http://en.wikipedia.org/wiki/" + temp;
window.location.replace(myPage);
}
popup.html
<!DOCTYPE html>
<html>
<body>
Random
Enter page to lookup: <input type="text" id="pageName" /><br />
<input type="submit" value="Submit" id="search" />
<script src="./page.js></script>
</body>
</html>
Anyone have any clue why this isn't working?
what you can do instead is include your JS in your HTML <head> tag, and add an onClick attribute to your button, like so:
<!DOCTYPE html>
<html>
<body>
<a href="http://en.wikipedia.org/wiki/Special:Random/" target="_blank">$
Enter page to lookup: <input type="text" id="pageName" /><br />
<input type="submit" value="Submit" id="search" />
<script src="./page.js"></script>
</body>
</html>
I think the problem was that in your original code, you had <script src="./page.js></script> instead of <script src="./page.js"></script>
then you can change your javascript to be the following:
document.getElementById('search').addEventListener('click', searchPage);
function searchPage() {
console.log("hjabdfs");
var temp = document.getElementById('pageName');
var temp = temp.value;
var myPage = "http://en.wikipedia.org/wiki/" + temp;
window.location.replace(myPage);
}
please note that I also changed var temp = document.getElementById(pageName) to var temp = document.getElementById('pageName'), as pageName is not a variable.
Input type submit is trying to submit a form. You need to add an action to that submit button or you can change it to a button and the event will fire.
Your click event listener doesn't work because it has not been loaded yet. Or in other words, you need to make sure this line <script src="./page.js></script> is correctly pointing to page.js.

innerHTML not displaying text

Please excuse my basic query to javascript and html
I am new to javascript and html. I am trying to work with javascript on click and few other things. In below code, am trying to display a text on "onclick" function. I am using an external javascript.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" >
<script type="text/javascript" src="/home/roger/Documents/html/myScript.js"></script>
</head>
<body>
<form>
First Name: <input type="text" name="first" id="names"/><br>
Phone Number: <input type="number" name="numb" id="numb"/><br>
<button type="button" onclick="verifyText()">Click Me!</button>
</form>
</body>
</html>
Below is my code in myScript.js
function verifyText(){
document.getElementById("names").innerHTML = "Why not displaying?.";
}
If I put alert in function, pop comes out, but I am unable to figure why innerHTML is not working. Any help will be highly appreciated. Thanks.
You need to set the value, because names is an input field.
document.getElementById("names").value = "Why not displaying?.";
See: http://jsfiddle.net/zrmrx/
names is an <input>. You need to set its value, instead of innerHTML. Try this:
function verifyText(){
document.getElementById("names").value = "Must display now!";
}
Use the javascript element.setAttribute('[attr]','string') to save the user input values or input checkbox checks as part of the document innerHTML. The reset() function changes the form input back to its current Attribute setting. Javascript can dynamically change the default input value with the setAttribute therefore, change the user input default value when reset() is clicked or your code reloads it as part of a saved innerHTML.
function update_attribute() {
var obj = document.getElementById('demo');
if (obj.type == 'checkbox') {
if (obj.checked == true) {
obj.setAttribute('checked', 'checked');
} else {
obj.removeAttribute('checked');
}
}
if (obj.type == 'text') {
obj.setAttribute('value', obj.value);
}
}
<form id='myform'>
<label>Text Input</label><br>
<input type='text' id='demo'>
<br>
<br>
<button type='button' onclick='update_attribute(this)'>Change Attribute</button>
<button type='reset'>RESET</button>
</form>

When we assign value jQuery event call?

I have two text fields:
<input type="text" id="ex_1" class="update">
<input type="text" id="ex_2" class="update">
I want when I assign value:
jQuery("#ex_1").val(12);
jQuery event called like below but not on the change but on assign value:
jQuery(".update").change();
jQuery(".update").live('keyup change', function()
{
alert(jQuery(this).val());
}
On the assignment of value jQuery event called?
you can use like this
$(".update").keyup(function () {
$(this).trigger("change");
});
$(".update").change(function () {
alert("change");
});
DEMO
Is this what you are looking for>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../JS/jQuery.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("input").change(function () {
alert('in'); // do you stuff here
});
$("#Button1").click(function () {
$("input").val(12);
$("input").trigger("change");
});
});
</script>
</head>
<body>
<input type="text" id="ex_1" class="update">
<input type="text" id="ex_2" class="update">
<input id="Button1" type="button" value="button" />
</div>
</body>
</html>
.trigger("change") will invoke the elements change function.
In the code above, on click of the button the val will be changed and also the change function will be triggered.
Syntax :
$("selector_of_element").trigger("event_function");
The change event fires only if the value is changed by the user interaction.
If you want to fire event then you have manually trigger event. So use .change(); or.trigger('change');
If you're programatically assigning value, you'll have to manually trigger the change event. Check this answer.
Try this:
jQuery('#ex_1').val(12).change();

Submit button alert box bug. How do I identify the bug and fix the code?

HELP! I need to know for this code to pop up an alert box, but the submit button does not bring it up! What is the bug and how can I fix the code without entirely changing the all of it? Thanks!
<!DOCTYPE html>
<html>
<head>
<title>Dougie's Script</title>
<script>
var textinput;
function submitHandler(e){
alert("You entered " + textinput.value + "\n");
e.preventDefault();
}
textinput=document.getElementById("textfield");
var form = document.getElementById("theform");
form.addEventListener("submit", submitHandler, false);
</script>
</head>
<body>
<form id="theform" action="#">
<label>Enter text here...</label>
<input id="textfield" type="text" >
<input type="submit" value="Submit" >
</form>
</body>
</html>
Move this to underneath the ending form tag:
<script type="text/javascript">
textinput=document.getElementById("textfield");
var form = document.getElementById("theform");
form.addEventListener("submit", submitHandler, false);
</script>
Move your <script> tag to the bottom of your <body>:
</form>
<script>...</script>
</body>
Right now, your script is trying to look for elements that haven't been created yet. The alternative would be to listen for the document's DOMContentLoaded event, but that isn't cross-browser.
Try moving your script tag to the very bottom of the body. This way the script will execute after the document has loaded (and then your elements should be "gettable" and "listener-attachable".)
The problem is that the elements of the page have yet to load when the javascript is ran. Therefore, document.getElementById("textfield") does not return an element, and no event is tied to it.
Try encapsulating the event handling of your javascript code as follows:
var textfield;
function submitHandler(e) { ... }
// When the window loads, run this function.
window.onload = function() {
textfield = document.getElementById("textfield");
var form = document.getElementById("theform");
form.addEventListener("submit", submitHandler, false);
}
That will make sure the event is tied to the element once it is loaded.
Remember to keep things in scope; where you are grabbing the text input dynamically every time you call the function in-order to keep the value updating within the response. Also, make sure the DOM is loaded before trying to access elements within the HTML tree, and since you are using addEventListener, here is a working version of your script:
<!DOCTYPE html>
<html>
<head>
<title>Dougie's Script</title>
<script>
(function(d){
var init = function(){
var form = d.getElementById("theform"), submitHandler = function(e){
var textinput = d.getElementById("textfield");
alert("You entered " + textinput.value + "\n");
e.preventDefault();
};
form.addEventListener("submit", submitHandler, false);
};
d.addEventListener("DOMContentLoaded", init, false);
})(document);
</script>
</head>
<body>
<form id="theform" action="#">
<label for="textfield">Enter text here...</label>
<input id="textfield" type="text" >
<input type="submit" value="Submit" >
</form>
</body>
</html>

Noob JavaScript Question - trying to assign a variable from a html text input and then have that variable used in a function

I'm trying to assign a variable from a html text input value and then have that variable used in a function that uses the jquery ":contains" selector to hide divs that don't match the variable...here is the code I have...
<head>
<script language="JavaScript" type="Text/JavaScript" src="jquery.js"></script>
<script language="JavaScript" type="Text/JavaScript">
var myform = document.forms[0];
var FilterText = myform.FilterText.value;
function FilterBlocks()
{
$("div.block").hide();
$("div.block:contains(FilterText)").show();
}
</script>
</head>
<body>
<form action="#">
<input class="navButtons" type="text" name="FilterText">
<input class="navButtons" type="button" name="FilterButton" value="Filter Videos" onMouseUp="FilterBlocks()">
<br /><br />
</form>
<div class="block"><a href="1.html"><img src="images/1.jpg">This is the title<a></div>
</body>
I tried doing an alert() with the variable that I an trying to use but it's coming back undefined.
Any help would be greatly appreciated...thanks!
Try $("div.block:contains(" + FilterText + ")").show(); instead. You'll need to 'escape' special characters too ((, ), etc), but this should work on simple strings.
And BTW, what you are coding in called Javascript, not Java.
you might want to do it this way,
function FilterBlocks(){
$("div.block").hide();
$("div.block:contains("+FilterText+")").show();
}
and also, calling var myform = document.forms[0];, in your code above, would result myform as undefined because DOM is not yet ready.
you might want it this way,
<script language="JavaScript" type="Text/JavaScript">
$(function(){
// call it when DOM is ready
var myform = document.forms[0];
var FilterText = myform.FilterText.value;
function FilterBlocks(){
$("div.block").hide();
$("div.block:contains("+FilterText+")").show();
}
});
</script>
for better jQuery style codes, I suggest this,
<input class="navButtons" type="button" name="FilterButton" value="Filter Videos" onMouseUp="FilterBlocks()">
to just,
<input class="navButtons" type="button" name="FilterButton" value="Filter Videos" >
your jQuery would be,
<script language="JavaScript" type="Text/JavaScript">
$(function(){
// call it when DOM is ready
var myform = document.forms[0];
$('.navButtons:button').click(function(){
var FilterText = myform.FilterText.value;
$("div.block").hide();
$("div.block:contains("+FilterText+")").show();
});
});
</script>

Categories

Resources