Best way to store JQuery variables? - javascript

I just want to get some thoughts on storing variables for JQuery's use.
Example
Here JQuery would use the the value of the video_id hidden input, and then voteup the video by the video_id.
<form class='voteup' action='' method='post'>
<input type="hidden" name='video_id' value='<?php echo $video_id; ?>' />
<input type='submit' value='Vote Up' />
</form>
Note: This is just an example.
But what if I want a link to do the same thing. Where would I store the video_id?
Obviously, I could store the video_id in the class attribute, but I don't think that this is the best way, especially if I needed to send more than one variable.
Any ideas on this?
I must mention that I'm only looking for XHTML valid ways.

You can use the jQuery data method to attach arbitrary data to an element. In your case, if I've understood what you're trying to do correctly, you probably want to do something like this:
$(document).ready(function() {
$("#yourLink").data("video_id", "<?php echo $video_id; ?>");
});
As you are looking for valid XHTML solutions, you can't use the HTML5 data-* attributes. If that was the case, you could add the attribute value directly on the element (as you've done with the value attribute in your example).
The data method does not require a corresponding data-* attribute to be present on the element, so this will still allow you to write valid XHTML.

If you digg HTML5 you should go for the data attribute.
http://ejohn.org/blog/html-5-data-attributes/

In an HTML 5 page, you can use "data-" attributes for things like that:
<img src='http://placekitten.com/100/100' data-video-id='whatever'>
Then, from jQuery:
$('img').click(function() {
var video = $(this).data('video-id'); // 'videoId' also works here
});
If you're (tragically) stuck with strict XHTML, well, you're stuck. For an <a> tag you could possibly use the "rel" attribute I guess. In general "class" is probably in fact the thing to do. The convention I've used for name-value pairs in the "class" is to separate them with a colon and then extract them via regex:
<sometag class='whatever videoId:video22 something'>
and then:
$('sometag').click(function() {
var videoId = this.className.replace(/videoId:(\S*)/, '$1');
// ...
});

Perhaps use the rel attribute, and grab it in jQuery using the .attr() method.
var myVar = $('#link_id').attr('rel');
http://api.jquery.com/attr/

Related

Creating an ID for a Form Variable (or Changing it) Using Javascript or JQuery

I am receiving an XML data form result and using the Strophe library to convert it into html.
This gives me a chunk of HTML (form) as a variable, which I can then append to a page:
var iqHtml = iqForm.toHTML();
$("#form-result-div").append(iqHtml);
The issue is that the form which it attaches has no id, action, or anything to identify it:
<form data-type="result">
...
I have two possibilities here.
Option 1. (preferred method)
Is it possible to change the variable iqHtml, which is just raw HTML, and an ID to it? Ideally this would be done before it is appended to the page.
I've tried multiple ways to find the form tag and add the attribute using .find() and .attr() but with no success.
Option 2. (less preferable)
I can edit the library to add a random ID (say id="some-id") which I will then need to EDIT rather than creating new.
This editing will have the questions as Option 1 - how do I search the variable and then change the form's ID.
Thank you.
Kind Regards,
Gary Shergill
You could assign an id before appending it
$(iqHtml).attr('id', 'someid').appendTo("#form-result-div");
Edited: id needs to be in ''
This should work:
var iqHtml = "<form><input type='text' /></form>";
$("#form-result-div").append(iqHtml).find("form").attr("id", "myForm");
Demo: http://jsfiddle.net/AA8Cf/
You can also play with one of the child selectors to pick up a specific one, if there is more than one form.
http://api.jquery.com/category/selectors/child-filter-selectors/

Ways to pass information from PHP to JQUERY?

I'm having a hard time figuring out what is the best way to transfer information from PHP to Jquery. I know putting PHP in Javascript is a really bad alternative (my JS and PHP files are seperated anyway), so what I usually do is print the info with PHP in the HTML with a input type hidden and retrieve the info in JQuery using the element.text() or .val() or any other method, but I feel this is kind of noobish. Is there a better way?
I recommend never using a server-side language to build JavaScript. Instead, keep your data in HTML (model), your styles in CSS (view), and your interactions in JS (controller).
When you need to pass data to JavaScript, make good use of attributes and templates.
When it comes to passing data via attributes, you can go a long way with just using native attributes.
In this example, it is quite apparent that the link will open a modal, and the [href] attribute is used to point to where the modal lives:
Open modal
<div id="modal">lorem ipsum</div>
When you can't fit data within native attributes, you should make use of [data-*] attributes.
In this example, [data-tooltip] is being used to store a rich-text tooltip.
<div data-tooltip="<p>lorem ipsum</p>">...</div>
Even more importantly, jQuery automatically grabs and casts all [data-*] attributes on a DOM node when .data() is called on the node.
<div id="example"
data-foo="bar"
data-fizz="true"
data-max="100"
data-options="{"lorem":"ipsum"}">
...
</div>
<script>
$('#example').data();
/*
{
foo: 'bar',
fizz: true,
max: 100
options: {
lorem: 'ipsum'
}
*/
</script>
The thing to watch out for is JSON encoding within HTML encoding. jQuery makes it very straight-forward to get the data out of the DOM node without needing to worry about decoding, but in PHP you need to make sure that you json_encode data before calling htmlentities:
<div data-example="<?= htmlentities(json_encode($someArray)) ?>">...</div>
In some instances you may want to make use of jQuery's .attr() method.
For large amounts of data, such as an HTML template string, you can use <script> tags with a template mime type (such as type="text/x-jquery-tmpl"):
<script id="template-example" type="text/x-jquery-tmpl">
<h1>${title}</h1>
<p>${body}</p>
</script>
Or you can use the HTML5 <template> element:
<template id="template-example">
<h1>${title}</h1>
<p>${body}</p>
</template>
You can then access the HTML contents of the element run it through whatever your favorite flavor of string templating happens to be.
You can simply echo PHP variables into Javascript variables for your jQuery to use like this:
<?php
$stringVar = "hi";
$numVar = 1.5;
?>
<script>
var stringVar = "<?php echo $stringVar; ?>";
var numVar = <?php echo $numVar; ?>;
</script>
This can be used for practically any data type as long as you convert it correctly upon echoing it (oftentimes json_encode() is enough for complex structures such as arrays and objects).
Also note that this way will only work if your jQuery code is included after these variables have been defined.
The other way is to look into using AJAX, but if these are static variables that don't need to change within the lifetime of the page then I would go with the method above.

Can't pull input-field value located beyond form tag

Problem
I use popup calendar, which is launched via href. I need to pass 'document.tstest.timestamp' (date input field) parameter into javascript function. And all worked well, BUT:
I want to include this tag-file into another form, so I can't use form
<form name="tstest">
in my tag file. As a result, without form I can't find document.timestamp input-field (as I understand due window.object hierarchy)
My tag file:
<form name="tstest">
<input type="Text" id="time_stamp" name="timestamp">
<a href="javascript:show_calendar('document.tstest.timestamp',
document.tstest.timestamp.value);"> showCalendar</a>
</form>
<script>
function show_calendar(target, value) {
............
}
</script>
Help me, please, to find out solution.
Your element has an id attribute on it so you can just use document.getElementById() to get a reference to it. I'd suggest modifying your show_calendar function to either take the id or a reference to the element directly, though, since you'll likely need to reference it again inside of that function.
You should be able to do the following anywhere on the page and get the element:
var elem = document.getElementById("time_stamp");
var myVal = elem.value;
This would work too
<a href="javascript:show_calendar('document.tstest.timestamp',
document.getElementById('time_stamp').value);"> showCalendar</a>
Don't use document.tstest as syntax instead use document.getElementById("time_stamp")
Also remember an id is unique so don't put 2 elements with a same I'd on a same page

JSF ui:include and getElementById

I'm writing the ui:composition xhtml file to include in different pages using ui:include. It looks like there's no way I can refer to the tags from javascript in this file using getElementById, as the tag ids might be prepended with the form id from the parent page. Is there a workaround?
Found this answer after I posted the question. It helped!
Acquire full prefix for a component clientId inside naming containers with JSF 2.0
You could do this:
var elem = document.querySelector( '[id$="-test"]' );
where test is the ID without the prefix, and - is the prefix separator.
The above code will select the element which "id" attribute ends with "-test" (e.g. <div id="form1-test">...</div>).
Live demo: http://jsfiddle.net/8kyb2/
Note that querySelector() paired with an attribute-ends-with selector performs slower than getElementById().
If you happen to use Apache's Tomahawk Components, and specify forceId="true", tag ids will remain unchanged. E.g.:
<t:inputText id="name" forceId="true" value="#{myBean.property}" />
will result in an <input type="text" id="name" ... / >.

How to store HTML-Markup in the ID-Attribute?

I need to show for every link, dynamically some text with Java-Script (jQuery). The problem is that the text is also formatted as HTML, so this causes some problems in the later view.
Now I am storing it in the ID-attribute, this works, but only without embedded HTML in it.
<?php
...
$desc = '<p style="color: red">some <span>data</span></p>';
echo '' . $key . '';
?>
Ajax-requests are not allowed. Is there a simple way to reach this goal?
The id attribute is one of the least appropriate places for this (must be unique, cannot contain all characters). Use a data- attribute (introduced in HTML5 but also works in old browsers and without using a HTML5 doctype) instead:
<a href="#" data-desc="....">
If you are using jQuery you can access it via .data('desc'), in plain JavaScript the most portable way is using .getAttribute('data-desc'). If you do not need to support older browsers, you can access the value via the .dataset.desc property.
In any case, you need to ensure that nothing breaks when inserting dynamic data in the attribute. Use htmlspecialchars() for this purpose:
$desc = '<p style="color: red">some <span>data</span></p>';
echo '' . $key . '';
The other comments are absolutely right. Don't do this. It isn't appropriate to put anything but an identifier of some kind in the id attribute.
That being said, I figured I would let you know why your code is failing. You need to use htmlspecialchars() on your data before you try to use it as you intend. That way, HTML won't be interpreted as HTML... all of the HTML entities will get converted for, so your attribute value is interpreted as text. < becomes <, > becomes > and so on. If you later pull the value out (with jQuery or whatever), you will get the text as intended.

Categories