How to readout Data from a formular? - javascript

I am doing an exercise for school. Task is to readout Data from a formular. Though I do not know much and I am stuck with the first Task. The result of the first task should be: "Your name has .... Characters." So basically if I enter a name in the text field and press the submit button it should give me the .length of the Name.
HTML:
<form>
<input id="Name" type="text" name="Name">
<input id="Ausgabe" type="submit" value="Ausgabe" onclick="ausgabe"()>
<p id="yournamehas" class="ptags">Your Name has:</p>
<p id="lname" class="ptags"></p>
<p id="Characters" class="ptags"> Characters</p>
</form>
Javascript:
function namelength() {
var Namee = document.getElementById('#Name').value.length
document.getElementById('lname').innerHTML = Namee
};
function ausgabe() {
$("#Ausgabe").on("click",function(){
{
document.getElementById("#Ausgabe").innerHTML =
namelength();
}
})
};
I seriously dont know whats wrong. Can you guys help me out?

var a = document.getElementById('Name');
function ausGabe(){
var b = a.value;
var name = document.getElementById('yournamehas').innerHTML = "Your Name has:" + " " +b;
var len = document.getElementById('Characters').innerHTML = "Characters" + " " + b.length;
}
<form>
<input id="Name" type="text" name="Name">
<input id="Ausgabe" type="button" value="Ausgabe" onclick="ausGabe()">
<p id="yournamehas" class="ptags">Your Name has:</p>
<p id="lname" class="ptags"></p>
<p id="Characters" class="ptags"> Characters</p>
</form>

As this is a school exercise, some pointers may be useful, to go along with the other answer which is a working solution...
jQuery vs Vanilla JS
You are using jQuery, which is a JavaScript library (a reusable bit of code) to make some jobs easier, especially regarding manipulation of elements in the browser (DOM elements). Way back, jQuery also did a more important job of 'normalising' the different browsers (Internet Explorer, Firefox, Opera, Netscape, etc.) before they adhered to the standards.
Nowadays jQuery is less vital as a normaliser, but still very handy for selecting elements and changing the styling, content, and handling events.
In your example you are doing some things the basic "Vanilla JS" way and some with jQuery. In a few places you have got things a bit mixed up and tried doing it a mix of ways, which won't work...
Referencing an element
by id
If you have an element such as <div id="myDiv"></div> then you can access it using Vanilla JS:
document.getElementById("myDiv");
or jQuery:
$("#myDiv");
Notice that you only provide the real id with getElementById, no hash.
by CSS selector
Another thing that jQuery did, which was amazing at the time, was that it allowed you to access DOM elements using the same selectors as CSS. That is why the jQuery version has a hash (#) because that is the CSS selector for "id=". Nowadays there is a Vanilla JS version of that which is widely supported:
document.querySelector("#myDiv"); // returns a single element
document.querySelectorAll("div"); // returns multiple div elements
Event handling
with jQuery
In your example you have used jQuery to attach some code to the click event of your button.
$("#Ausgabe").on("click",function(){
// blah
});
That's great and attaches your function to be run later when the button is clicked.
with element attributes (the bad way)
However, you have put that in another function which is explicitly called when you click the button, using the old-fashioned onclick attribute.
<input id="Ausgabe" ... onclick="ausgabe()">
Your jQuery event is not initially attached. It only becomes so when the onclick attribute handles the first click. So you have to click the button to attach an event handler to deal with clicking the button. Have you seen the film Inception? You need to make your mind up about which approach to take. You should definitely be attaching to the event rather than using onclick.
Vanilla JS
However, you can also do that with Vanilla JS:
document.getElementById("Ausgabe").addEventListener("click", function() { /* your code goes here */ });
Setting content
Vanilla JS
You have used the Vanilla JS approach for setting content of your element, which is great:
document.getElementById('lname').innerHTML = Namee;
jQuery
But that's another thing that jQuery provides a method for:
$("#lname").html(Namee);
Be consistent
Vanilla JS vs jQuery
To make it easier to both write and read your code, it is better to be consistent. Decide if you are going to use Vanilla JS or jQuery and then stick to it. Although you might use jQuery for some of the more difficult things even when using Vanilla JS (like adding or removing a CSS class name).
Semi-colons
JavaScript instructions are supposed to end with a semi-colon;
You don't always have to do it, and there are people who claim that you shouldn't unless absolutely necessary. But it does make code clearer to read because JavaScript is allowed to split across multiple lines. So the semi-colon tells your reader that you've finished the instruction. My advice is to always use them.
Quotes
JavaScript is flexible on the use of 'single' and "double" quotes. There are different opinions on this, and plenty of arguments for/against each, but it really doesn't matter which. However it is nicer if you stick to one approach:
var string1 = "Stick to one set of quotes";
var string2 = 'else your code will look weird';
var string3 = `even this is allowed in modern JS`;
var string4 = "But this one is BROKEN';
form submit buttons
One more thing, which also harkens back to 'the old days'...
When the world wide web was new there was no JavaScript and web pages were just a little better than plain text. The only interaction was by filling in a form and 'submitting' it back to the server.
If you have a <form> element which contains an <input type="submit"> button then that's what the browser expects to do. If you press that button it will submit the form. Nowadays that's actually quite rare!
If you use that arrangement then you might find that your page doesn't act the way you expect. Therefore it is safer to use non-submit buttons which don't have any special behaviour:
<input type="button" value="My non-submit button">
Good luck and enjoy
That's a lot of advice. Hopefully you can now see where you were going wrong before and have a better understanding of things.
I hope you enjoy coding. It's not scary and if you get properly good at it then you can have a good job in the future. But only go down that route if it really appeals to you. It's actually a horrible job if you spend most of your time on StackOverflow asking for help! ;)
TL;DR
If that was too long and you didn't want to read it then I advise you to not become a developer. Going into the details of how things work is a very important lesson that you never stop learning.

Related

How to make a live HTML preview textarea safe against HTML/Script Injection

I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.
However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:
</textarea>
<script>alert("Hello World!");</script>
<textarea style="display: none;">
And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).
I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.
These few lines is what I use to live render HTML markup:
$(".main").on("keyup", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?
In order to sanitise your text area preview simply replace all the < and > with their html character code equivalents:
function showPreview()
{
var value = $('#writer').val().trim();
value = value.replace("<", "<");
value = value.replace(">", ">");
$('#preview').html(value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="writer" onInput="showPreview();">
</textarea>
<br/>
<hr/>
<div id="preview">
</div>
Edit: Actually, I think this solution is a little cleaner, and makes the below code unnecessary. In the velocity page all that is needed is to take advantage of the Spring framework. So I replace the textarea with this like so:
#springBindEscaped("myJavaObj.textAreaText" true)
<textarea id="actualTextArea" name="${status.expression}" class="myClass" rows="10" cols="120">$!status.value</textarea>
This paired with some backend Java validation and it ends up being a much cleaner solution.
But if you want a non-spring/ velocity solution, then this below works just fine
I cobbled together a quick fix as my main purpose is to eliminate the ability for others to execute scripts easily. It's not ideal, and I"m not claiming it to be the best answer, so if someone finds a better solution, please do share. I created a "sanitize" function like so:
function sanitize(text){
var sanitized = text.replace("<script>", "");
sanitized = sanitized.replace("</script>", "");
return sanitized;
}
Then the previous two event handlers now look like:
$(".main").on("keyup", "#actualTextArea", function () {
var textAreaMarkup = $('#actualTextArea').val();
var sanitizedMarkup = sanitize(textAreaMarkup );
$('#actualTextArea').val(sanitizedMarkup);
$('#previewTextArea').html(sanitizedMarkup);
});
// This one can remain unchanged and infact needs to be
// If it's the same as above it will wipe the text area
// on a highlight-backspace
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Along with Java side sanitation to prevent anything harmful being stored in the DB, this serves my purpose, but I'm very open to a better solution if it exists.

html, js - how to limit elements "scope" - namespaces

During last perioud I've seen more and more often the following situation.
Developer A creates a feature. Let's say is an autocomplete input. Let's assume for simplicity that no framework is used, html and js are on the same file. The file would look like this (let's also asume jquery used - is less to type):
<!-- autocomplete something.html file -->
.........................................
<input id="autocomplete" type="text" />
<script type="text/javascript">
$('#autocomplete').change(function() {
// Do lots of things here -> ajax request, parsing, etc.
});
</script>
.........................................
Now developer B sees the feature and says "Oh, nice feature, I can use that in my section, I'll put one at the top, and one at the bottom - because page is long".
And he does an ajax call to get that html file (this is important, I'm talking about features loaded like this, not features rewritten for the other section) and includes it where he needs it.
Now... problem. The first autocomple works, the second doesn't (because is select by id).
A workaround would be to modify, and use a class. And everything is ok, unless someone else (or himself, or whatever) uses same class for a tottaly different thing.
This could all be avoided if you could the the script to use as a "scope" (I know it is not the correct phrasing, couldn't find any better) the file where it was declared on.
Note: This is a theoretical question. For each particular case a solution could be found, but defining some kind of namespaces for this scenarios would solve the whole class of problems.
How could that be achieved?
As long as you're accessing the DOM the only way I see would be to use the "old" inline event:
<!-- autocomplete something.html file -->
.........................................
<input onchange="autocomplete_change();" type="text" />
<script type="text/javascript">
function autocomplete_change() {
// Do lots of things here -> ajax request, parsing, etc.
};
</script>
...........
Now the function name cannot be used by Developer B.
But when accessing DOM some kind of restriction will always be there.
However when creating the input by Script you can bind the handler directly to the Element:
<script>
var input = $('<input type="text"/>');
input.change(function() {
// Do lots of things here -> ajax request, parsing, etc.
});
document.body.appendChild(input[0]);
</script>

Using the `content` attribute as an HTML Template

I've been trying to use the CSS content property to make somewhat of a "template" for an element of a specific class.
I've tried multiple things. . .
Many places I have seen told me to convert everything to hexadecimal, so I did, until I saw that using hex wrote the litteral characters into the element, instead of evaluating the characters as HTML.
I then tried just litterally entering the characters into the content, and I got the exact same result (this makes it appear as if there is no purpose for the hex, yet thats hard to belive with how many people say there is. . . ).
Is there any way that I can place HTML content into an element using the CSS content attribute?
I've made a JS-Fiddle for this:
And, of course, Stack wants my source:
HTML:
<button id="normal" >Show with normal output</button>
<button id="hex" >Show with Hexadecimal output</button>
<div id="class_changer" ></div>
JS:
function changeClass(evt)
{
class_changer.className = evt.srcElement.id;
}
var class_changer = document.getElementById('class_changer');
var normal = document.getElementById('normal').addEventListener('click', changeClass, true);
var hex = document.getElementById('hex').addEventListener('click', changeClass, true);
And the un-godly long CSS:
.normal::before {
content: '<img alt="Facebook" src="http://cache.addthis.com/icons/v1/thumbs/32x32/facebook.png" />';
}
.hex::before {
content: '\0027\003c\0061\0020\0068\0072\0065\0066\003D\0022\0068\0074\0074\0070\003A\002F\002F\0061\0070\0069\002E\0061\0064\0064\0074\0068\0069\0073\002E\0063\006F\006D\002F\006F\0065\0078\0063\0068\0061\006E\0067\0065\002F\0030\002E\0038\002F\0066\006F\0072\0077\0061\0072\0064\002F\0066\0061\0063\0065\0062\006F\006F\006B\002F\006F\0066\0066\0065\0072\003F\0070\0063\006F\003D\0074\0062\0078\0033\0032\006E\006A\002D\0031\002E\0030\0026\0061\006D\0070\003B\0075\0072\006C\003D\0068\0074\0074\0070\0025\0033\0041\0025\0032\0046\0025\0032\0046\0077\0077\0077\002E\0063\0069\006D\0074\0072\0061\006B\002E\0063\006F\006D\0026\0061\006D\0070\003B\0075\0073\0065\0072\006E\0061\006D\0065\003D\0063\0069\006D\0063\006F\0072\0022\0020\0074\0061\0072\0067\0065\0074\003D\0022\005F\0062\006C\0061\006E\006B\0022\003e\003c\0069\006D\0067\0020\0061\006C\0074\003D\0022\0046\0061\0063\0065\0062\006F\006F\006B\0022\0020\0073\0072\0063\003D\0022\0068\0074\0074\0070\003A\002F\002F\0063\0061\0063\0068\0065\002E\0061\0064\0064\0074\0068\0069\0073\002E\0063\006F\006D\002F\0069\0063\006F\006E\0073\002F\0076\0031\002F\0074\0068\0075\006D\0062\0073\002F\0033\0032\0078\0033\0032\002F\0066\0061\0063\0065\0062\006F\006F\006B\002E\0070\006E\0067\0022\0020\002F\003e\003c\002F\0061\003e';
}
Check it out at JS-Fiddle and see what you can do! Let me know! Thanks everybody!
UPDATE: SOLVED (ish...)
Yes, wierd question sometimes accept wierd answers (like iterating over the DOM...) but if you have a better solution, I'm all ears.
As it turns out, the accepted answers means of evaluating a "CSS template" may be the best means of performing "templating" without the use of third-party libraries or the new <template> tag (that I'm still not sure of) even though it makes my skin crawl (if anyone has a better solution, please post it). Either way, I've updated my JSFiddle, so check it out!
Although, I guess the best answer would be purely making a template as a string in JavaScript, that is, if we are going to be evaluating it later on and pre-pending it to an element. Yea, that would make more sense...
No, this is not possible with plain CSS. However, if you really want to save these templates in CSS, you could iterate over all elements and use
window.getComputedStyle(element, ':before').content
to fetch the content and then prepend/append it to the element. To parse the HTML, you could either use jQuery.parseHTML, new DOMParser().parseFromString or a dummy DOM element. Alternatively, you could also use .innerHTML directly, but I wouldn't recommend that..

Can you mix ASP.Net and Unobtrusive JavaScript

Is it possible to mix the concept of Unobtrusive JavaScript with the event model of ASP.Net?
ASP.NET makes it very difficult, as every server side control requires a postback via the __doPostback javascript function.
You can make sure you are not using any server side controls, but this means you loose most of the benefits of ASP.NET.
Another option is to override the OnRender event and output different controls/javascript, but this is also quite a lot of work and defeats the purpose of ASP.NET.
You have much greater control when using ASP.NET-MVC.
yes, to a point. discounting standard controls and how they are built, there's not much stopping your from offloading all your own javascript to a separate file. the big hangup that comes to mind is referencing myControl.ClientID to render an element id in the middle of a script block. with a little planning, you can still minimize the amount of script you have to render in the page to work around this.
I realize that this question has already been answered but for anybody surfing in, I somewhat disagree with the accepted answer.
It depends on what controls you are using.
Not all the controls require JavaScript. The biggest culprit for me was always LinkButton. A regular button control does not use JavaScript at all however. On my pages, I actually use regular buttons and use CSS and JavaScript to make them into LinkButtons. The first step is to use CSS to make them look like links. If you really want to get fancy, you can detach the button, add an HTML anchor, and associate all the event handlers for the button with the anchor. This means that a user without JavaScript sees a regular button (HTML input) that is styled with CSS. Anybody using JavaScript will see an HTML link (
Also, if you use JQuery, it is very easy to select ASP.NET elements without worrying about all the extra mumbo-jumbo that ASP.NET adds to the IDs.
Example:
<asp:Button id='theButton' text='Click here' cssclass='linkbutton' runat='server' />
You can select this individual button using JQuery:
var theButton = $("input[name$='theButton']");
You can also replace everything of class 'linkbutton' with HTML anchors:
$(function() {
var buttons = $(".linkbutton");
buttons.each(function() {
var button = $(this);
var id = button.attr('id');
/*
* If a link button is not working
* it is likely because it does not
* have an ID attribute - check that
*/
if (id)
{
var text = button.attr('value');
var cssclass = button.attr('class');
button
.before("<a id='"+id+"' class='"+cssclass+"' href=''>"+text+"</a>")
.hide()
.detach();
$("a[id='"+id+"']").live('click', function(event) {
$(this).after(button);
button.click();
event.preventDefault();
});
}
});
});
Things like GridViews are a bit more work but also doable. I found that, after the initial honeymoon, I avoided those kinds of controls and just used repeaters anyway. Repeaters do not impose any nasty JavaScript either.
Anyway, it is certainly possible to do unobtrusive JavaScript with ASP.NET WebForms.

How to store arbitrary data for some HTML tags

I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handling it in case was to put that information in the href link this:
<a class="article" href="#5">
I then use jQuery to find the a.article elements and attach the appropriate event handler. (don't get too hung up on the usability or semantics here, it's just an example)
Anyway, this method works, but it smells a bit, and isn't extensible at all (what happens if the click function has more than one parameter? what if some of those parameters are optional?)
The immediately obvious answer was to use attributes on the element. I mean, that's what they're for, right? (Kind of).
<a articleid="5" href="link/for/non-js-users.html">
In my recent question I asked if this method was valid, and it turns out that short of defining my own DTD (I don't), then no, it's not valid or reliable. A common response was to put the data into the class attribute (though that might have been because of my poorly-chosen example), but to me, this smells even more. Yes it's technically valid, but it's not a great solution.
Another method I'd used in the past was to actually generate some JS and insert it into the page in a <script> tag, creating a struct which would associate with the object.
var myData = {
link0 : {
articleId : 5,
target : '#showMessage'
// etc...
},
link1 : {
articleId : 13
}
};
<a href="..." id="link0">
But this can be a real pain in butt to maintain and is generally just very messy.
So, to get to the question, how do you store arbitrary pieces of information for HTML tags?
Which version of HTML are you using?
In HTML 5, it is totally valid to have custom attributes prefixed with data-, e.g.
<div data-internalid="1337"></div>
In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.
If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain.
If you are using jQuery already then you should leverage the "data" method which is the recommended method for storing arbitrary data on a dom element with jQuery.
To store something:
$('#myElId').data('nameYourData', { foo: 'bar' });
To retrieve data:
var myData = $('#myElId').data('nameYourData');
That is all that there is to it but take a look at the jQuery documentation for more info/examples.
Just another way, I personally wouldn't use this but it works (assure your JSON is valid because eval() is dangerous).
<a class="article" href="link/for/non-js-users.html">
<span style="display: none;">{"id": 1, "title":"Something"}</span>
Text of Link
</a>
// javascript
var article = document.getElementsByClassName("article")[0];
var data = eval(article.childNodes[0].innerHTML);
Arbitrary attributes are not valid, but are perfectly reliable in modern browsers. If you are setting the properties via javascript, than you don't have to worry about validation as well.
An alternative is to set attributes in javascript. jQuery has a nice utility method just for that purpose, or you can roll your own.
A hack that's going to work with pretty much every possible browser is to use open classes like this: <a class='data\_articleid\_5' href="link/for/non-js-users.html>;
This is not all that elegant to the purists, but it's universally supported, standard-compliant, and very easy to manipulate. It really seems like the best possible method. If you serialize, modify, copy your tags, or do pretty much anything else, data will stay attached, copied etc.
The only problem is that you cannot store non-serializable objects that way, and there might be limits if you put something really huge there.
A second way is to use fake attributes like: <a articleid='5' href="link/for/non-js-users.html">
This is more elegant, but breaks standard, and I'm not 100% sure about support. Many browsers support it fully, I think IE6 supports JS access for it but not CSS selectors (which doesn't really matter here), maybe some browsers will be completely confused, you need to check it.
Doing funny things like serializing and deserializing would be even more dangerous.
Using ids to pure JS hash mostly works, except when you try to copy your tags. If you have tag <a href="..." id="link0">, copy it via standard JS methods, and then try to modify data attached to just one copy, the other copy will be modified.
It's not a problem if you don't copy tags, or use read only data. If you copy tags and they're modified you'll need to handle that manually.
Using jquery,
to store: $('#element_id').data('extra_tag', 'extra_info');
to retrieve: $('#element_id').data('extra_tag');
I know that you're currently using jQuery, but what if you defined the onclick handler inline. Then you could do:
<a href='/link/for/non-js-users.htm' onclick='loadContent(5);return false;'>
Article 5</a>
You could use hidden input tags. I get no validation errors at w3.org with this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />
<title>Hello</title>
</head>
<body>
<div>
<a class="article" href="link/for/non-js-users.html">
<input style="display: none" name="articleid" type="hidden" value="5" />
</a>
</div>
</body>
</html>
With jQuery you'd get the article ID with something like (not tested):
$('.article input[name=articleid]').val();
But I'd recommend HTML5 if that is an option.
Why not make use of the meaningful data already there, instead of adding arbitrary data?
i.e. use <a href="/articles/5/page-title" class="article-link">, and then you can programmatically get all article links on the page (via the classname) and the article ID (matching the regex /articles\/(\d+)/ against this.href).
As a jQuery user I would use the Metadata plugin. The HTML looks clean, it validates, and you can embed anything that can be described using JSON notation.
This is good advice. Thanks to #Prestaul
If you are using jQuery already then you should leverage the "data"
method which is the recommended method for storing arbitrary data on a
dom element with jQuery.
Very true, but what if you want to store arbitrary data in plain-old HTML? Here's yet another alternative...
<input type="hidden" name="whatever" value="foobar"/>
Put your data in the name and value attributes of a hidden input element. This might be useful if the server is generating HTML (i.e. a PHP script or whatever), and your JavaScript code is going to use this information later.
Admittedly, not the cleanest, but it's an alternative. It's compatible with all
browsers and is valid XHTML. You should NOT use custom attributes, nor should you really use attributes with the 'data-' prefix, as it might not work on all browsers. And, in addition, your document will not pass W3C validation.
As long as you're actual work is done serverside, why would you need custom information in the html tags in the output anyway? all you need to know back on the server is an index into whatever kind of list of structures with your custom info. I think you're looking to store the information in the wrong place.
I will recognize, however unfortunate, that in lots of cases the right solution isn't the right solution. In which case I would strongly suggest generating some javascript to hold the extra information.
Many years later:
This question was posted roughly three years before data-... attributes became a valid option with the advent of html 5 so the truth has shifted and the original answer I gave is no longer relevant. Now I'd suggest to use data attributes instead.
<a data-articleId="5" href="link/for/non-js-users.html">
<script>
let anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
let articleId = anchor.dataset.articleId;
}
</script>
I advocate use of the "rel" attribute. The XHTML validates, the attribute itself is rarely used, and the data is efficiently retrieved.
So there should be four choices to do so:
Put the data in the id attribute.
Put the data in the arbitrary attribute
Put the data in class attribute
Put your data in another tag
http://www.shanison.com/?p=321
You could use the data- prefix of your own made attribute of a random element (<span data-randomname="Data goes here..."></span>), but this is only valid in HTML5. Thus browsers may complain about validity.
You could also use a <span style="display: none;">Data goes here...</span> tag. But this way you can not use the attribute functions, and if css and js is turned off, this is not really a neat solution either.
But what I personally prefer is the following:
<input type="hidden" title="Your key..." value="Your value..." />
The input will in all cases be hidden, the attributes are completely valid, and it will not get sent if it is within a <form> tag, since it has not got any name, right?
Above all, the attributes are really easy to remember and the code looks nice and easy to understand. You could even put an ID-attribute in it, so you can easily access it with JavaScript as well, and access the key-value pair with input.title; input.value.
One possibility might be:
Create a new div to hold all the extended/arbitrary data
Do something to ensure that this div is invisible (e.g. CSS plus a class attribute of the div)
Put the extended/arbitrary data within [X]HTML tags (e.g. as text within cells of a table, or anything else you might like) within this invisible div
Another approach can be to store a key:value pair as a simple class using the following syntax :
<div id="my_div" class="foo:'bar'">...</div>
This is valid and can easily be retrieved with jQuery selectors or a custom made function.
In html, we can store custom attributes with the prefix 'data-' before the attribute name like
<p data-animal='dog'>This animal is a dog.</p>.
Check documentation
We can use this property to dynamically set and get attributes using jQuery like:
If we have a p tag like
<p id='animal'>This animal is a dog.</p>
Then to create an attribute called 'breed' for the above tag, we can write:
$('#animal').attr('data-breed', 'pug');
To retrieve the data anytime, we can write:
var breedtype = $('#animal').data('breed');
At my previous employer, we used custom HTML tags all the time to hold info about the form elements. The catch: We knew that the user was forced to use IE.
It didn't work well for FireFox at the time. I don't know if FireFox has changed this or not, but be aware that adding your own attributes to HTML elements may or may-not be supported by your reader's browser.
If you can control which browser your reader is using (i.e. an internal web applet for a corporation), then by all means, try it. What can it hurt, right?
This is how I do you ajax pages... its a pretty easy method...
function ajax_urls() {
var objApps= ['ads','user'];
$("a.ajx").each(function(){
var url = $(this).attr('href');
for ( var i=0;i< objApps.length;i++ ) {
if (url.indexOf("/"+objApps[i]+"/")>-1) {
$(this).attr("href",url.replace("/"+objApps[i]+"/","/"+objApps[i]+"/#p="));
}
}
});
}
How this works is it basically looks at all URLs that have the class 'ajx' and it replaces a keyword and adds the # sign... so if js is turned off then the urls would act as they normally do... all "apps" (each section of the site) has its own keyword... so all i need to do is add to the js array above to add more pages...
So for example my current settings are set to:
var objApps= ['ads','user'];
So if i have a url such as:
www.domain.com/ads/3923/bla/dada/bla
the js script would replace the /ads/ part so my URL would end up being
www.domain.com/ads/#p=3923/bla/dada/bla
Then I use jquery bbq plugin to load the page accordingly...
http://benalman.com/projects/jquery-bbq-plugin/
I have found the metadata plugin to be an excellent solution to the problem of storing arbitrary data with the html tag in a way that makes it easy to retrieve and use with jQuery.
Important: The actual file you include is is only 5 kb and not 37 kb (which is the size of the complete download package)
Here is an example of it being used to store values I use when generating a google analytics tracking event (note: data.label and data.value happen to be optional params)
$(function () {
$.each($(".ga-event"), function (index, value) {
$(value).click(function () {
var data = $(value).metadata();
if (data.label && data.value) {
_gaq.push(['_trackEvent', data.category, data.action, data.label, data.value]);
} else if (data.label) {
_gaq.push(['_trackEvent', data.category, data.action, data.label]);
} else {
_gaq.push(['_trackEvent', data.category, data.action]);
}
});
});
});
<input class="ga-event {category:'button', action:'click', label:'test', value:99}" type="button" value="Test"/>
My answer might not apply to your case. I needed to store a 2D table in HTML, and i needed to do with fewest possible keystrokes. Here's my data in HTML:
<span hidden id="my-data">
IMG,,LINK,,CAPTION
mypic.jpg,,khangssite.com,,Khang Le
funnypic.jpg,,samssite.com,,Smith, Sam
sadpic.png,,joyssite.com,,Joy Jones
sue.jpg,,suessite.com,,Sue Sneed
dog.jpg,,dogssite.com,,Brown Dog
cat.jpg,,catssite.com,,Black Cat
</span>
Explanation
It's hidden using hidden attribute. No CSS needed.
This is processed by Javascript. I use two split statements, first on newline, then on double-comma delimiter. That puts the whole thing into a 2D array.
I wanted to minimize typing. I didn't want to redundantly retype the fieldnames on every row (json/jso style), so i just put the fieldnames on the first row. That a visual key for the programmer, and also used by Javascript to know the fieldnames. I eliminated all braces, brackets, equals, parens, etc. End-of-line is record delimiter.
I use double-commas as delimiters. I figured no one would normally use double-commas for anything, and they're easy to type. Beware, programmer must enter a space for any empty cells, to prevent unintended double-commas. The programmer can easily use a different delimiter if they prefer, as long as they update the Javascript. You can use single-commas if you're sure there will be no embedded commas within a cell.
It's a span to ensure it takes up no room on the page.
Here's the Javascript:
// pull 2D text-data into array
let sRawData = document.querySelector("#my-data").innerHTML.trim();
// get headers from first row of data and load to array. Trim and split.
const headersEnd = sRawData.indexOf("\n");
const headers = sRawData.slice(0, headersEnd).trim().split(",,");
// load remaining rows to array. Trim and split.
const aRows = sRawData.slice(headersEnd).trim().split("\n");
// trim and split columns
const data = aRows.map((element) => {
return element.trim().split(",,");
});
Explanation:
JS uses lots of trims to get rid of any extra whitespace.

Categories

Resources