Jsfiddle Code
The code work in Jsfiddle
Dont work in firefox or any browser
Line error:tarea.addEventListener('input', update)
Error is Firefox "TypeError: tarea is null"
Error in Chrome is "Uncaught TypeError: Cannot read property 'addEventListener' of null"
Please help me. I am looking for an effective solution, with simple code that works correctly
<html>
<head>
<title>Counter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
<script type="text/javascript">
// Encapsulate function to document.ready now not error.
$(document).ready(function(){
var tarea = document.querySelector('#ta')
var input = document.querySelector('#rt')
function update() {
var res = (tarea.value.match(/\n/g)) ? tarea.value.match(/\n/g).length : 0;
input.value = res;
}
tarea.addEventListener('input', update) //Error Here
});
tarea.addEventListener('input', update) //Error Here
$(document).ready(function(){
if (jQuery) {
// jQuery is loaded
alert("Jquery load!");
} else {
// jQuery is not loaded
alert("Jquery Doesn't Work");
}
});
</script>
<body>
<textarea name="ta" id="ta" rows="4" cols="50">
ABC
DEF
GHI
</textarea>
<input type="text" id="rt" name="textnumber" value="">
</body>
</html>
Put your code through a validator. I think you have missing semi-colons and bad braces.
I see you're using jQuery. Something like this should suffice:
$(function() {
var tarea = $('#ta');
var input = $('#rt');
function update(e) {
var val = tarea.val(),
matches = val.match(/\n/g),
res = (matches) ? val.match(/\n/g).length : 0;
if(val.length){res++;}
input.val(res);
}
tarea.on("input", update)
.trigger("input");//set initial value
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="ta" id="ta" rows="4" cols="50">ABC
DEF
GHI</textarea>
<input type="text" id="rt" name="textnumber" value="">
The problem with your code is that you're trying to access the element before the document is fully loaded.
You should either move your JavaScript code at the end (right before the closing </body> tag) or move all your event handling code (including the tarea definition) to $(document).ready(...).
Related
The 'rightbox' section must show the key and value entered in the form after they were stored using sessionStorage.
I tried Chrome, Firefox, Edge, and Opera browsers. The code didn't work on any of them.
Here is the code:
function doFirst() {
var button = document.getElementById('button');
button.addEventListener('click', saveStuff, false);
}
function saveStuff() {
var one = getElementById('one').value;
var two = getElementById('two').value;
sessionStorage.setItem(one, two);
display(one);
}
function display(one) {
var rightbox = document.getElementById('rightbox');
var thedata = sessionStorage.getItem(one);
rightbox.innerHTML = 'Name of variable: ' + one + '<br />Value: ' + thedata;
}
window.addEventListener('load', doFirst, false);
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<section id="leftbox">
<form>
<p>(key) One: <input type="text" id="one"></p>
<p>(value) Two: <textarea id="two"></textarea></p>
<p><input type="button" id="button" value="Save"></p>
</form>
</section>
<section id="rightbox">
Nothing yet!
</section>
</body>
</html>
The following block from your code:
function saveStuff() {
var one = getElementById('one').value;
var two = getElementById('two').value;
console.log(one, two);
sessionStorage.setItem(one, two);
display(one);
}
You need to use document.getElementById() instead of just getElementById. That will solve your issue.
Furthemore, you have used document.getElementById() properly in your first function, so make sure to check for errors in the browser console next time before posting a question. That will help you in long run.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
For a few hours I've been trying to understand what's wrong. My purpose is to enable a button after textfields are filled. Code seems fine according to my test at JSFiddle but it's still not working on my server. Am'I missing something or is this a server problem (which is hard to believe since javascript is client-side)?
PS: I'm not expert at HTML, so I don't know how to identate it's syntax; if it's not that readable I'm sorry and would appreciate an edit-help. thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
</script>
</head>
<body>
<section class="container">
<div class="OpenKore">
<div id="absolute">
<form method="GET" action="generate.php">
<fieldset>
<legend><h1>OpenKore Automatic Config:</h1></legend>
LOGIN:
<p><input type="text" id="id_login" name="login_value" value="" placeholder="Login"></p>
SENHA:
<p><input type="text" id= "id_senha" name="senha_value" value="" placeholder="Senha"></p>
PIN:
<p><input type="text" id="id_pin" name="pin_value" value="" placeholder="PIN"></p>
<input id="apply" type="submit" name="commit" disabled value="Gerar Configurações">
</fieldset>
</form>
</div>
</div>
</section>
</body>
</html>
When the browsers reads your HTML page, it reads top to bottom. When it gets to your <script> tags it runs them. Now it us doing this before it has got to the rest of the page, i.e. before it even knows about any body or form or input:text tags, so even though you code will run, it will simply not do anything because none of the elements on the page exist yet.
JavaScript 101, make the code run after the page has loaded, if you need to access elements on the page. How do you do that? either put the code at the bottom of the page (move your <script> tags to just before the </body> tag), or wrap your code in a function that is executed after the browser has finished loading the page. Now jQuery has a very helpful way of doing this for you, pass a function to jQuery and it will be executed after the page is loaded.
jsFiddle does this automatically for you, hence the drop down in the top left corner saying 'onLoad'
i.e. your code
$(); //this is the jQuery function
//This is your code wrapped in a function called 'yourCode'
function yourCode() {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
}
$(yourCode); //this is passing the jQuery function a function,
//this will now be execute once the page is loaded
//or what most people do, pass in as an anonymous function
//which eliminates a step
$(function () {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
});
as suggested by #j08691 I would suggest reading about the document ready in jQuery here
I have written the following code to display an input with Javascript's alert( ... ) function.
My aim is to take a URL as input and open it in a new window. I concatenate it with 'http://' and then execute window.open().
However, I just get 'http://' in the URL name, even after concatenation, and not the complete URL. How can I fix this?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<body onload="onload();">
<input type="text" name="enter" value="" id="url_id">
<input type="button" value="Submit" onclick="func();">
</body>
<script type="text/javascript">
var url;
function onload() {
url = document.getElementById("url_id").value;
}
function func(){
var var1 = "http://";
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
</script>
</head>
</html>
You shouldn't be calling it in onload(), only after the user has entered the url into the input field. Of course its an empty string, because you assign url to the value of #url_id before the user has a chance to enter anything when you place it in onload().
function func(){
var var1 = "http://";
url = document.getElementById("url_id").value;
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
Others have given solutions, and you already have accepted one. But none of them have told you what is wrong with your code.
Fristly, you have a body element inside your head element. This is invalid markup. Please correct it:
<html>
<head>
<!-- this is a script -->
<script type="text/javascript">
// javascript code
</script>
</head>
<body>
<!-- this is an inline script -->
<script type="text/javascript">
// javascript code
</script>
</body>
</html>
Secondly, you need to have an idea about the execution order of JavaScript inside browser windows. Consider this example:
<html>
<body onload="alert('onload')">
<p>Lorem Ipsum</p>
<script type="text/javascript" >
alert('inline');
</script>
</body>
</html>
Which alert do you thing will get executed first? See the JSFiddle.
So as you can see, inline JavaScript will be executed first, and then the browser will call whatever code is in <body onload=.
Also, onload function is called immediately after the page is loaded. And user has not entered anything when the function is executed. That is why you get null for url.
function func()
var url = document.getElementById("url_id").value;
var fullUrl = "http://".concat(url);
alert(fullUrl);
// or window.open(fullUrl);
}
You're not concatenating with a String but with an Object. Specifically an HTMLInputElement object.
If you want the url from the text input, you need to concatenate with url.value.
if its not concatenating, use:
var res = val1+val2.value;
I would like to change the contents of a div, using javascript and innerHTML.
I cannot get it to work. I just added the code for changing the div, before that the code was working fine. I double checked the syntax.
I'm using webshims, openlayers and jquery/javascript
In the in the console I see
Uncaught TypeError: Cannot set property 'innerHTML' of null
imagegaledit - myFile.php :768
so.onmessage - myFile.php :324
768 is that line
document.getElementById("imgedtitle").innerHTML=mnmi[0];
and 324 is this
imagegaledit(0);
Little help?
Thanks
edit
websockets work and responce fine
Here is the code (concise and simplified)
<!doctype html>
<header>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html">
<script src="jquery-1.8.2.min.js"></script>
<script src="js-webshim/minified/extras/modernizr-custom.js"></script>
<script src="js-webshim/minified/polyfiller.js"></script>
<script>
$.webshims.polyfill();
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--open layers api library-->
<script type='text/javascript' src='OpenLayers.js'></script>
<script type='text/javascript'>
//openlayers vars and stuff here...
function init(){
//when a point on map clicked...
function selected_feature(event){
//some openlayers magic...
var so = new WebSocket("ws://localhost:8000");
so.onerror=function (evt)
{response.textContent = evt;}
so.onopen = function(){
response.textContent = "opened";
so.send(JSON.stringify({command:'map',fmid:jas}));
}
so.onmessage = function (evt) {
var received_msg = evt.data;
var packet = JSON.parse(received_msg);
//pass data to var and arrays...
imagegaledit(0);
}
}//closes function selected_feature
}//closes init
function imagegaledit (w){
if (w==0){
document.getElementById("imgedtitle").innerHTML=mnmi[0];
}
}//closes imagegaledit
</script>
<body onload='init();'>
Title</br><div id="imgedtitle"> </div> </br>
</body>
You need a closing script tag:
</script>
<body>
This is the code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function nameNotAva()
{
alert("Name already exists.");
//some code
}
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
$.ajax({
url : curl,
type : 'GET',
success : function(urlOutput){
if(urlOutput.contains('NAMECHECK: NOTAVALIBLE')){
nameNotAva();
}
}
});
}
</script>
</head>
<body>
<input class="textBox" id="uname" type="text" maxlength="15" required/>
<input type="button" onclick="nameCheck()" value="Submit">
</body>
</html>
The problem is there in the $.ajax part. I know this because when i put alert(curl); just before the ajax part, it displays the correct URL. If you want the complete info that what i am trying to do then goto- How to check output of a created URL?
I am using jquery library of the latest version.
You haven't included the jQuery library so $ is undefined and the script will error on the Ajax part.
In general, if you have a problem with some JavaScript: Open the JS console in your browser and pay attention to any error messages.
Update after comments suggest that the code in the question was incomplete:
This is the library i am using- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript" />
Script elements are not defined as empty. The end tag is required.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
</script>
http://jsfiddle.net/ksJEj/
Change the input type:
<input type="submit" value="Submit"/>
include this in your <head></head> tags:
HTML
<script type="text/javascript" src="ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
and this too:
HTML/JavaScript
<script type="text/javascript">
$(document).ready(function{
function nameNotAva() {
alert("Name already exists.");
//some code
}
$('input[type="submit"]').click(function (event) {
event.preventDefault();
var username = $('#uname').val();
$.get("http://rscript.org/lookup.php", {
'type': 'namecheck',
'name': username
}, function (urlOutput) {
if ($(urlOutput).contains('NAMECHECK: NOTAVALIBLE') == true) nameNotAva();
else alert("woohoo");
});
});
});
</script>