Uncaught ReferenceError: var is not defined - javascript

I have two textarea which starts on empty value.
Then when I fill the first textarea with id "postcrudo" I want that the next textarea (with id "posthecho") getthe same value as the first, and also show the same. Like a two way binding, like AngularJS, but only with JavaScript and jQuery.
This is the JS:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
$("#postcrudo").val(function(){
algo = this;
});
postHecho = postCrudo;
console.log("OK!");
});
});
</script>
and this the HTML:
<body>
<div style="width:700px;float:left;">
<p>Post crudo:</p>
<p><textarea cols="100" maxlength="99999" name="postCrudo" id="postcrudo" rows="60"></textarea></p>
</div>
<div style="width:700px;float:left;">
<p>Post pasado:</p>
<p><textarea cols="100" maxlength="99999" name="postHecho" id="posthecho" rows="60"></textarea></p>
</div>
<div style="clear:both;"></div>
<p><input type="submit" value="submit" id="submit" /></p>
</body>
The error in Chrome console is:
Uncaught ReferenceError: postCrudo is not defined

Is this what you want?
https://jsfiddle.net/a4nmto6t/1/
Just get the value of the first textarea and change the value of the second to that:
$(document).ready(function(){
$("#submit").click(function(){
var postCrudoVal = $("#postcrudo").val();
$("#posthecho").val(postCrudoVal);
console.log("OK!");
});
});
Neither postHecho nor postCrudo are declared (by you**), and even if they were, assigning one of them to the other does not do what you want. You have to assign the value of the first textarea to the value of the second textarea using (in this case) jQuery selectors, because they ARE the ones referencing the DOM elements (the textareas).
** Elements that have an id are set as global 'variables' by default, but you shouldn't use them; it is instead suggested that you either use the DOM API to find elements or use jQuery (which uses the DOM API behind the scenes).

There is no declaration of postCrudo so it is undefined. Also why would you want to try and do this yourself instead using something like AngularJS to handle data bindings. You are essentially doing more work for no reason. Plus you have to handle all aspects of 2 way data binding manually. To me there is smarter ways to do this.

Your element id postcrudo is all lowercase. postCrudo is indeed not defined
This linepostHecho = postCrudo; makes no sense, I think you're trying to do this:
$('#posthecho').val($('#postcrudo').val())

JavaScript syntax is case sensitive.
`postHecho = postCrudo;`
Should be:
`postHecho = postcrudo;`

Related

What it is the jQuery equivalent function of Javascript DafaultValue()

I want to get the default value of an input textbox when the page was loaded. As I searched around I saw that the DefaultValue() is a method to get a value from a textbox when is loaded . But what is the jQuery one?
<input id=text > </input>
<script>
$(#text).DefaultValue(); // This is wrong I need the Jquery function of this
</script>
Any Idea?
You can read the defaultValue DOM property like this:
$('#text').prop('defaultValue')
Heres a working example
$('#value').click(function(){
alert($('#text').val())
});
$('#def').click(function(){
alert($('#text').prop("defaultValue"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" value="This is the default value">
<button id="value">Click to see the current value</button>
<button id="def">Click to see the default value</button>
If you want to call a Javascript DOM function on a jQuery object, you can simple extract the corresponding DOM object with .get(0) or [0]:
$("#text").get(0).defaultValue;
$("#text")[0].defaultValue;
Note also that you were calling the basic JS wrong. First, it's defaultValue, not DefaultValue. Second, it's a property, not a method, so there's no parentheses after it.
Try this,
$(function(){
console.log($('#text')[0].defaultValue);
// or try
console.log($('#text').prop( 'defaultValue' ));
});
Read https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

Can not copy data of HTML tags to JavaScript

For some reasons I am trying to change functionality of submit button. I am facing problem in copying data from HTML tags to JS. The alert generated by following code prints "Undefined" not the data inside tag.
<html>
<body>
<input class="inputtext" id="email" name="email" type="text"></div>
<input value="Submit" name="v4l" id="login" class="inputsubmit" type="button" onclick="myFunction();return false">
<script>
function myFunction() {
var TestVar =document.getElementsByClassName('login').value;
alert(TestVar);
}
</script>
</body>
</html>
I know it can be done by form but I need it this way.
try
var TestVar = document.getElementById('email').value
alert(TestVar);
this will get value of text field
getElementsByClassName
^
See that s? Elements is plural. getElementsByClassName returns a NodeList (which is like an Array).
You have to either pick an index from it (foo[0]) or loop over it to get the values.
That said, you don't actually have any elements that are a member of the login class, so it is going to return a Node List of zero length.
You do have an element with id="login", so maybe you should use getElementById instead.
There doesn't seem much point in reading the value from an element that you've hard coded the value for. You might actually want to be using document.getElementById('email')

What is innerHTML on input elements?

I'm just trying to do this from the chrome console on Wikipedia. I'm placing my cursor in the search bar and then trying to do document.activeElement.innerHTML += "some text" but it doesn't work. I googled around and looked at the other properties and attributes and couldn't figure out what I was doing wrong.
The activeElement selector works fine, it is selecting the correct element.
Edit: I just found that it's the value property. So I'd like to change what I'm asking. Why doesn't changing innerHTML work on input elements? Why do they have that property if I can't do anything with it?
Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.
value applies only to objects that have the value attribute (normally, form controls).
innerHtml applies to every object that can contain HTML (divs, spans, but many other and also form controls).
They are not equivalent or replaceable. Depends on what you are trying to achieve
First understand where to use what.
<input type="text" value="23" id="age">
Here now
var ageElem=document.getElementById('age');
So on this ageElem you can have that many things what that element contains.So you can use its value,type etc attributes. But cannot use innerHTML because we don't write anything between input tag
<button id='ageButton'>Display Age</button>
So here Display Age is the innerHTML content as it is written inside HTML tag button.
Using innerHTML on an input tag would just result in:
<input name="button" value="Click" ... > InnerHTML Goes Here </input>
But because an input tag doesn't need a closing tag it'll get reset to:
<input name="button" value="Click" ... />
So it's likely your browsers is applying the changes and immediatly resetting it.
do you mean something like this:
$('.activeElement').val('Some text');
<input id="input" type="number">
document.getElementById("input").addEventListener("change", GetData);
function GetData () {
var data = document.getElementById("input").value;
console.log(data);
function ModifyData () {
document.getElementById("input").value = data + "69";
};
ModifyData();
};
My comments: Here input field works as an input and as a display by changing .value
Each HTML element has an innerHTML property that defines both the HTML
code and the text that occurs between that element's opening and
closing tag. By changing an element's innerHTML after some user
interaction, you can make much more interactive pages.
JScript
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
HTML
<p>Welcome to Stack OverFlow <b id='boldStuff'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
In the above example b tag is the innerhtml and dude is its value so to change those values we have written a function in JScript
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
For instance:
document.getElementById("example").innerHTML = "my string";
This example uses the method to "find" an HTML element (with id="example") and changes the element content (innerHTML) to "my string":
HTML
Change
Javascript
function change(){
document.getElementById(“example”).innerHTML = “Hello, World!”
}
After you clicked the button, Hello, World! will appear because the innerHTML insert the value (in this case, Hello, World!) into between the opening tag and closing tag with an id “example”.
So, if you inspect the element after clicking the button, you will see the following code :
<div id=”example”>Hello, World!</div>
That’s all
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
Example.
HTML
Change
Javascript
function FunctionName(){
document.getElementById(“example”).innerHTML = “Hello, Kennedy!”
}
On button Click, Hello, Kennedy! will appear because the innerHTML insert the value (in this case, Hello, Kennedy!) into between the opening tag and closing tag with an id “example”.
So, on inspecting the element after clicking the button, you will notice the following code :
<div id=”example”>Hello, Kennedy!</div>
Use
document.querySelector('input').defaultValue = "sometext"
Using innerHTML does not work on input elements and also textContent
var lat = document.getElementById("lat").value;
lat.value = position.coords.latitude;
<input type="text" id="long" class="form-control" placeholder="Longitude">
<button onclick="getLocation()" class="btn btn-default">Get Data</button>
Instaed of using InnerHTML use Value for input types

How to refer to a javascript variable in a value field?

I'd like to refer to a variable ("special") in field later in the same script. I've gotten the variable to display with alert boxes and document.write, but don't now how to make to apply its value to the value field in
var special=(10000-health);
var health=(100);
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
this just writes "special" to the box, when I would like the value instead.
You have to set the value explicitly:
document.getElementById('special').value = special;
Note: You can only access the element after it was parsed in the DOM. To be sure, you can insert this part of the script after the element in the HTML. Often JavaScript code is added just before the closing body tag or is only executed when the load event fires. For more information, see Where to place JavaScript in a HTML file.
Update: Here is an example:
<body>
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
<script type="text/javascript">
var health = 100;
var special = 10000 - health;
document.getElementById('special').value = special;
</script>
</body>
References: getElementById, DOM
MDC's JavaScript Guide is also worth reading.
document.getElementById('special').value = special;
you have to use some kind of DOM manipulation. One of the more popular libraries is JQuery.
using jQuery you'd write something like
$('#special').val(special);
var input = document.getElementById('special');
input.value = special;

How can I escape a DOM name in javascript?

I have a form element that I want to address via javascript, but it doesn't like the syntax.
<form name="mycache">
<input type="hidden" name="cache[m][2]">
<!-- ... -->
</form>
I want to be able to say:
document.mycache.cache[m][2]
but obviously I need to indicate that cache[m][2] is the whole name, and not an array reference to cache. Can it be done?
UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute.
Here's some code that proves it:
<html>
<body>
<form id="form1">
<input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/>
<input type='button' value='Test' onclick='showtest();'/>
<script type="text/javascript">
function showtest() {
var value = document.getElementById("field[m][2]").value;
alert(value);
}
</script>
</form>
</body>
</html>
Update: You can also use the following to get the value from the form element:
var value = document.forms.form1["field[m][2]"].value;
Use document.getElementsByName("input_name") instead. Cross platform too. Win.
Is it possible to add an id reference to the form element and use document.getElementById?
-- and in the old days (in HTML3.2/4.01 transitional/XHTML1.0 transitional DOM-binding) you could use:
form.elements["cache[m][2]"]
-- but the elements-stuff is, as Chris Pietschmann showed, not necessary as these binding-schemes also allow direct access (though I personally would prefer the extra readability !-)

Categories

Resources