JavaScript variable name and HTML input name attribute: namespace collision? - javascript

In an HTML file I have the following:
<input type="..." name="myInput1" />
In a corresponding JS file I have the following variable which will hold the string value of that input after blur:
var myInput1;
Is there any problem in having these two identical names? I'm guessing that the namespaces are separate so it is ok.

Short answer, no problem whatsoever.

A short answer is, indeed, no. However, it also greatly depends on how you use the variable. Let's consider that you use javascript for validating that the variable is set as follows:
if(myInput1) {do something}
If you also decide to set the id to be the same as the name is as follows (cause you didn't specify that, it can be anything):
<input type="myInput1" name="myInput1" />
your variable myInput1 will be set to contain the DOM element and won't be empty anymore.
This link between JS and HTML is not only interesting but can be used to create an exploit as described in the section 3.1.2 of Postcards from the post-XSS world (that's where I have the idea from - and yes, it still works even though the article is from 2011).

Related

Proper way to retrive HTML textbox data using JavaScript

Assuming I have a simple HTML page like the following:
<html>
<head>...</head>
<body>
<input type="text" id="mytextarea" />
<input type="button" id="button1" onClick="..." />
<input type="button" id="button2" onClick="..." />
</body>
</html>
What is the best way to access the text in the text-field with id="mytextarea" in a JavaScript function, without creating code heavily coupled to the HTML page, given the knowledge that button1 and button2 cause different manipulations on the text?
Just as an example, assume I am expecting a binary number in the text field, and button1 will convert it to an integer decimal number, but button two will convert it to a fractional decimal number. How can I handle this without tightly coupling the JavaScript code to the HTML page? Is there some way to send the data in mytextarea down to the JavaScript code, without having to use a document.getElementById('mytextarea') in the JavaScript functions themselves?
Perhaps I should clarify,
I am not looking for an alternative to using getElementById, I am looking for a way to write JavaScript code that can use a text-field in an HTML page without being coupled to it. In other words, I would like to know how to write JavaScript functions and HTML pages in such a way that (1) the JavaScript functions can perform work on data in the HTML page and (2) the JavaScript function can be be moved to another HTML page and used there, without changing said function.
I think this is what you want:
First you create an object called Textarea that lets you pass a textarea element as an argument:
function Textarea(textarea) {
this.container = textarea;
this.value = textarea.value
};
Then you can add methods shared by every instance of the Textarea object:
Textarea.prototype.ChangeValue = function(){
console.log( 'Please add your ' + this.value );
};
In this way, you can pass mytextarea and modify it as you want. This allows to reuse properties and methods in your object in other textareas or other projects where you need it.
t = new Textarea(document.getElementById('mytextarea'));
t.ChangeValue();
Demo: http://jsfiddle.net/SQ2EC/
Since you need some way to inform the functions about the elements to be operated on, there are two simple options. You can pass a reference to an element as a parameter when calling a function, as in
onclick="manipulate(document.getElementById('mytextarea'))"
Or you could pass just the id attribute value:
onclick="manipulate('mytextarea')"
in which case the function would need to use document.getElementById(), but on its parameter, not a wired-in string.
The first approach is more flexible in the sense that it lets you construct a reference in some other way too, e.g. document.getElementsByTagName('textarea')[0].
You could combine the approaches, by writing the function so that it can handle both kinds of parameters. It could e.g. first check whether its argument is of string type and use document.getElementById() on it if it is, otherwise expect it to be a reference to an element. And you should probably have some sanity checks in the function, testing that what you get or construct is really a reference to a textarea element.
I dint get what exactly you want to do but here you can get value of textbox on it's change event
<script>
$(document).ready(function () {
$('input[id$=mytextarea]').change(function () {
alert($(this).val());
.............
now you have got the value so convert it to decimal and do other stuff
});
});
</script>

Why replace backslash code doesn't work in JS?

My code in JSP file looks like this :
<s:form namespace="/user" action="list" method="POST" id="filterListForm" theme="simple"
onsubmit="document.getElementById('filterSearchText').value=document.getElementById('filterSearchText').value.replace(/\\/g,'')">
It won't replace the backslash char. I've tried the following, none of them work :
replace('/\\/g','')
replace(/\\\\/g,'')
replace(\/\\\/g,'')
But if I change it to the following, it works :
<s:form namespace="/user" action="list" method="POST" id="filterListForm" theme="simple"
onsubmit="replaceBackslash()">
<script type="text/javascript">
function replaceBackslash() { document.getElementById('filterSearchText').value=document.getElementById('filterSearchText').value.replace(/\\/g,''); }
</script>
Why ? Is there a way to make it work in the first case ?
You want:
var replaced = original.replace(/\\/g, '');
In a regular expression literal, all you need to do is double the backslash to quote it.
As to why it doesn't work when you try passing the code in via a JSP tag, well that would probably be JSP mangling the string for you. It might work to do this:
<s:form ... onsubmit=' ... .replace(/\\\\/g, "") ... ' >
but I don't have a good way to try that at the moment.
edit — actually I'm finding this challenging. It probably depends on what your tag library does. My framework (Stripes) likes to HTML-escape attribute values, so it's hard to pass through something like \ (well, impossible).
(This isn't really a solution, just a recommendation of a general practice that happens to solve this problem, too.)
Bottom line: Go with separated Javascript. If you feel it's too much work to completely separate it out into a different file (even though that would help you cleanly avoid all issues such as this), at least put it all in a script tag at the bottom. It helps separate layout and logic, and it keeps all the Javascript in one known place, making it easier to understand and maintain. You don't even need onclick/onsubmit attributes, you can assign those in Javascript too (usually keyed on html #id attributes). If you use the on[event] attributes anyway, just call one sensibly named function, and put the function's implementation in your main script.

javascript not getting value of input box

I seem to be having trouble with passing the value of an input box to anything else in my javascript.
It's not producing any errors - and I remember reading somewhere that you can have issues if the document hasn't finished loading - but I'm pretty sure it has!
The code in question is as follows in the javascript:
var address = getElementById(addyInput).value;
document.getElementById('add').innerHTML = address;
And in the HTML
<form>
<input name="addyInput" placeholder="Don't forget postcode!">
</form>
<button id="start" onclick="initialize()">Start!</button>
<p>Address Test
<div id="add"></div>
</p>
I know that the button itself is working as it fires the rest of my code fine without the offending code - however the moment I uncomment that little block at the top, it just does nothing. (no errors etc)
Any help on that one would be hot! Thanks :)
Update:
I now have it working! Thanks muchly for all the help!!
Your form needs to look like this (add an id attribute):
<form>
<input id="addyInput" name="addyInput" placeholder="Don't forget postcode!">
</form>
And the first line of Javascript needs to look like this (since getElementById is expecting an ID rather than a name).
var address = getElementById('addyInput').value;
Additionally, getElementById expects the id argument to be a string (hence the quotes). If you pass it addyInput without quotes, it'll try to interpret addyInput as a variable which has a value of undefined and you won't get back the DOM element you want.
Or, if you were using jQuery, you could leave the form markup as-is and change the Javascript to this:
var address = $('input[name=addyInput]').val();
Make sure to specify and id on the input. You only have a name.
You need to add the id "addyInput" to your form input rather than just the name.
getElementById expects a string.
var address = getElementById('addyInput').value;
If you put this directly into a script section in the head, then you will have a problem because the page is not loaded completely but the code is executed already.
And of course you should define an id for the input element as the others already said.
what you are getting is an array, you need to fetch your array into some readable data. Try something like:
$value = array_shift( $yourarray );
or if it's a multi value array you can just loop it to fetch out the values.

How to insert text into a form with JavaScript

I'm trying to create a simple extension for personal use. It's partially from laziness, and partially from an urge to learn. I've never made extensions before, but I've been looking at the documentation. Now I just need to write the code. What I'm trying to do, is when the browser loads a certain page, to insert text into a specific form. The form is as follows
<div id="set_tags" class="advanced_option">
<label for="post_tags" class="inline_input_label" id="post_tags_label"
onclick="Element.remove($(this))"
style="left:8px; right:auto; text-align:left">tags</label>
<input id="post_tags" name="post[tags]" type="text"/>
</div>
I haven't worked much with javascript, so is there a way to add the text "Music" to this when the page is loaded?
You can use the onload function to start your function.
http://javascript.about.com/library/blonload.htm
Since you are new to javascript you may want to get familiar with unobtrusive javascript (http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html) which I find is a better way to write javascript, as you can then easily comment out javascript and see how it works when that is disabled. But, it would be easier to learn this in the beginning.
To get the input tag you can use document.getElementById() which would be something like:
var elem = document.getElementById('post_tags');
Then, to add text to this field there should be a value property in your input definition above, and you would just do:
elem.value = "Music";
document.getElementById("post_tags_label").appendChild(
document.createTextNode("Music"));
I'm assuming that you want to put it at the end of the element post_tags_label.
This is really easy to do if you use GreaseMonkey. It's perfect for personal changes you want to make to web pages, etc.

Html Helpers generates ID from model properties. How do I target 1 particular element with JavaScript and CSS if many elements have the same ID?

As it's recommended, Javascript must be kept in a physically separate file (to be unobtrusive). So how do I access a particular element in particular page? should I detect those elements by id? that would mean 2 elements can't have the same id even if they are not located in the same page.
Well, for instance, using the Html helpers methods generates element's name + id from the model's properties. If I use the same model in several pages, many elements will have the same id. How can I target them in different pages. By the way, CSS work the same way.
EDIT
Let's say I've this
<% = Html.TextBoxFor(x => x.FirstName)%>
It will generates
<input type = "Text" name = "FirstName" id = "FirstName"/>
Let's say I've this textbox in 2 differen pages. If want, for instance, to disable the textbox located in page A, how do I do it knowing they are two of them in 2 different pages. How do I discriminate them from my external javascript file?
Thanks for helping
I suggest that for each page the uses the same model, you create a wrapper div
<div class="pageA">
// the model stuff here
<% = Html.TextBoxFor(x => x.FirstName)%>
</div>
<div class="pageB">
// the model stuff here
<% = Html.TextBoxFor(x => x.FirstName)%>
</div>
and then use Jquery selectors to get the correct element $(".pageA input[name='FirstName']") (not sure if this syntax is correct).
You cannot have multiple elements on the page with the same id. That isn't valid HTML.
So when you use the same HTML helper multiple times, you need to pass different names:
<%: Html.TextBox("Foo", Model.Foo) %>
<%: Html.TextBox("Bar", Model.Bar) %>
Correct me if i'm wrong, but are you saying, you have some elements with the same id, on multiple pages, that you want to attach different behaviour to? If so then this could help you out. if not, then what Craig said.
You can use more specific selectors, or give your selectors context
have a look at the documentations here: http://api.jquery.com/jQuery/
under this header:
jQuery( selector, [ context ] )
it explains a bit about selects and context. you should be able to use this and some creative page building to target the right element with your jQuery.
So you have two files, each with a text field with the id "FirstName". When you're script runs on Page A you want to disable the field, but not when your script runs on Page B.
Is the structure of the two pages identical? I suspect not if you're handling these fields differently. Use the context to your advantage. Like if the one on Page A is in a div with id "thisDiv" and the other is in a div with id "thatDiv" you could document.getElementById('thisDiv'). If you get an element then disable the field, if not do nothing.
If you want a more specific answer you're going to have to give us more context.
Well JavaScript may be kept in a separate file or not, but it is definitely included as part of the HTML send to the browser for a particular page. I Hope I've understood your question, but, generally if you have you JavaScript code in a file, lets say utils.js then in your html generated should include (probably within the <head> tag):
<script type="text/javascript" src="/path/to/utils.js"></script>
The script get included in the page, and when the browser encounters this, it loads and then runs the script, for that page. Therefore, it is not important what the ids for elements on different pages are.
Does that make sense, or have I completely misunderstood your question?
Update:
Ok, so based on your comments, I think I understand. You have
//Page 1
//When loaded, this input should flash blue via javascript for example
<input id="firstName" .../>
And
//Page 2
//When loaded, this input has some other fancy effect/behaviour
<input id="firstName" .../>
Well in this case, as far as I see, there are only 2 types of answers. Have two seperate external js files, one per page and this way you can change to your hearts content ...OR... have some sort of hidden field in your page that tells your script what page it is looking at (this seems hacky)
<input type="hidden" value="page1"/> //etc..

Categories