How can I escape a DOM name in javascript? - 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 !-)

Related

Uncaught ReferenceError: var is not defined

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;`

How to display page title in form field?

I'd like to display the page title in a form input field using plain javascript.
I've tried this but it doesn't work. What am I doing wrong?
<input type="text" value="javascript:document.title;"/>
Also, how can I check if the input field is actually there and do nothing if so. I'd like to do this check to avoid JS errors.
No, it would not. value is never executed. Try this instead:
<title>title text here</title>
<!-- ... -->
<input type="text" id="titleinput">
<script>
var theInput = document.getElementById('titleinput')
if (theInput) {
theInput.value = document.title;
}
</script>
EDIT: Shown how to test for existence of the input, and removed the arcane way of finding title since there is a better way. Although, in this case, you might know that you've created the input field, and take it as granted that it is there (your program should make an error if it's not, just like it should make an error if you delete a line from the code itself. I would only have such a check on HTML that I do not control. It might be a personal choice though, I know I don't do enough defensive programming.
EDIT2: jasonscript has a point, but I thought it would confuse the OP even more. If you want a best-practices answer though, you'd do some variety of this, to avoid global variables:
(function(theInput) {
if (theInput) {
theInput.value = document.title;
}
})(document.getElementById('titleinput'));
value attribute is a string, it wouldn't execute if you place some JS in it.
You would set its value with JS after the input is ready in DOM:
<input type="text" value="">
<script>
document.querySelector('input').value = document.title;
</script>
Whereas querySelector will give you the first input element in the DOM.
Specificly, you can pass any css selectors to the method, e.g. ID selector in following code. Please note different parameter querySelector is using:
<input type="text" value="" id="titleInput">
<script>
document.querySelector('#titleInput').value = document.title;
</script>
More on querySelector, visit selectors api spec.
This would work:
HTML:
<title>awesome site</title>
<input type="text" id="textinput" value=""/>
JAVASCRIPT:
<script>
var title = document.title;
var textinput = document.getElementById('textinput');
if (textinput) {
textinput.value = title;
}
</script>
or shorter:
<script>
document.getElementById('textinput').value = document.title;
</script>

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')

Setting HTML textbox value using javascript function?

I'm using this code to set the HTML textbox value using Javascript function. But it seems to be not working. Can anyone point out, what is wrong with this code?
Whats your Name?
<input id="name" value="" />
<script type="text/javascript">
function setValue(value){
var myValue=value;
document.getElementsById("name").value = myValue;
}
</script>
the "value" is came from my android java class using this codes
String value = "Isiah";
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/www/webpage");
web.loadUrl("javascript:setValue("+ value +")");
function setValue(value) {
var myValue=value; //unnecessary
document.getElementById("name").value= myValue;
}
But then as pointed out in the comments, you need to call setValue(value) somewhere in your code. Right now you just defined the function is never called.
You could either access the element’s value by its name:
document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"
So:
input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />
Or you assign an ID to the element that then identifies it and you can access it with getElementById:
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />
You are using document.getElementsById("name") it should be document.getElementById("name")
not Elements it is Element
You are not linking the function to anything. For example, a click:
<input id="name" value="" onclick="javascript:this.value=12;"/>
Replace the onclick attribute for your desired function, whatever it does (you need to be more specific)
Also, there is no language attribute (at least not anymore) use type="text/javascript" instead
Here is a fiddle: http://jsfiddle.net/4juEp/
Click the input to see it working.
Look at this second fiddle. http://jsfiddle.net/4juEp/1/
which loads whatever is defined in the hid input to the name input.
Firstly, you have a typo in your javascript function i.e. you have used getElementsById as compared to getElementById
To set the value of the textbox on page load, I suggest you use an alternative
<body onload="setValue('yourValueToSet');">
<!-- Your usual html code in the html file -->
</body>
I think you are missing the quotes,
try,
web.loadUrl("javascript:setValue('"+ value +"')");
also consider about the typo.
Check this out:
<body onload="setvalue($value);">
Whats your Name?<input id="name" name="name" value=""/>
<script type="text/javascript">
function setValue(value){
document.{formname}.name.value = value;}</script>
It's not Elements
It's Element
You should use document.getElementById('object-id');

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;

Categories

Resources