I was making a survey in Qualtrics, and needed to have my items show different values of the slider depending on a variable, in my case, the value from a loop and merge. That didn't seem like a thing that you could do with piped text, so I had to figure out how to do it in Javascript.
I'm just posting this as an opportunity to provide the answer I found on my own. As usual with Qualtrics, your mileage may vary, and this may need to be modified for your specific situation. In particular, the question IDs and postTags change depending on whether it is in a loop/merge, and perhaps on other factors.
Put the following code into the javascript section of the question:
// Set the slider range
// First define the function to do it
setSliderRange = function (theQuestionInfo, maxValue) {
var postTag = theQuestionInfo.postTag
var QID=theQuestionInfo.QuestionID
// QID should be like "QID421"
// but postTag might be something like "5_QID421" sometimes
// or, it might not exist, so play around a bit.
var sliderName='CS_' + postTag
window[sliderName].maxValue=maxValue
// now do the ticks. first get the number of ticks by counting the table that contains them
var numTicks = document.getElementsByClassName('LabelDescriptionsContainer')[0].colSpan
// do the ticks one at a time
for (var i=1; i<=numTicks; i++) {
var tickHeader='header~' + QID + '~G' + i
// the first item of the table contains the minimum value, and also the first tick.
// so we do some tricks to separate them out in that case.
var tickSpanArray = $(tickHeader).down("span.TickContainer").children
var tickSpanArrayLength=tickSpanArray.length
var lastTickIndex=tickSpanArrayLength - 1
var currentTickValue = tickSpanArray[lastTickIndex].innerHTML
currentTickValue=currentTickValue.replace(/^\s+|\s+$/g,'')
console.log('Tick value ' + i + ' is ' + currentTickValue)
// now get the new value for the tick
console.log('maxValue: ' + maxValue + ' numTicks: ' + numTicks + ' i: ' + i)
var newTickValue = maxValue * i / numTicks //the total number of ticks
tickSpanArray[lastTickIndex].innerHTML=newTickValue.toString()
console.log('Changed tick value to ' + newTickValue)
}
}
var currentQuestionInfo = this.getQuestionInfo()
var currentQuestionID = currentQuestionInfo.QuestionID
// Now call the function
setSliderRange(currentQuestionInfo, theMaxValueYouWant)
If you find my answers helpful, help raise my reputation enough to add "qualtrics" as a valid tag!! Or, if someone else with reputation over 1500 is willing to do it that would be very helpful!
For a client's requirement, I have set out several images as follows:
img/img1.jpg
img/img2.jpg
img/img3.jpg
...
img/img4.jpg.
Now, I need to make the function that loads images dynamic. At the moment, the current solution is as follows:
// Grab the last image path
var lastImagePath = $("lastImage").attr("src");
// Increment the value.
var nextImagePath = "img/img" + (+lastImagePath.replace("img/img").replace(".jpg") + 1) + ".jpg";
// So on.
I was wondering if there's a cleaner way to increment the number?
Slightly cleaner:
var nextImagePath = lastImagePath.replace(/\d+/, function (n) { return ++n; });
This uses the version of replace that accepts a regular expression and a function.
I want to display YouTube videos on my website, but I need to be able to add a unique id for each video that's going to be shared by users. So I put this together, and I have run into a little problem. I am trying to get the JavaScript to add a random string for the div id, but it's not working, showing the string:
<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var div = randomString(8);
</script>
<div id='div()'>This text will be replaced</div>
<script type='text/javascript'>
jwplayer('div()').setup({
'flashplayer': 'player.swf',
'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
I really like this function:
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
From Create GUID / UUID in JavaScript?
2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.
A simple way to create a unique ID in JavaScript is to use the Date object:
var uniqid = Date.now();
That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.
The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.
var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();
This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.
Here is the reusable function to generate the random IDs :
function revisedRandId() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}
// It will not start with the any number digit so it will be supported by CSS3
I think some folks here haven't really focused on your particular question. It looks like the problem you have is in putting the random number in the page and hooking the player up to it. There are a number of ways to do that. The simplest is with a small change to your existing code like this to document.write() the result into the page. I wouldn't normally recommend document.write(), but since your code is already inline and what you were trying do already was to put the div inline, this is the simplest way to do that. At the point where you have the random number, you just use this to put it and the div into the page:
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
and then, you refer to that in the jwplayer set up code like this:
jwplayer(randomId).setup({
And the whole block of code would look like this:
<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
'flashplayer': 'player.swf',
'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
Another way to do it
I might add here at the end that generating a truly random number just to create a unique div ID is way overkill. You don't need a random number. You just need an ID that won't otherwise exist in the page. Frameworks like YUI have such a function and all they do is have a global variable that gets incremented each time the function is called and then combine that with a unique base string. It can look something like this:
var generateID = (function() {
var globalIdCounter = 0;
return function(baseStr) {
return(baseStr + globalIdCounter++);
}
})();
And, then in practical use, you would do something like this:
var randomId = generateID("myMovieContainer"); // "myMovieContainer1"
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
i like this simple one:
function randstr(prefix)
{
return Math.random().toString(36).replace('0.',prefix || '');
}
since id should (though not must) start with a letter, i'd use it like this:
let div_id = randstr('youtube_div_');
some example values:
youtube_div_4vvbgs01076
youtube_div_1rofi36hslx
youtube_div_i62wtpptnpo
youtube_div_rl4fc05xahs
youtube_div_jb9bu85go7
youtube_div_etmk8u7a3r9
youtube_div_7jrzty7x4ft
youtube_div_f41t3hxrxy
youtube_div_8822fmp5sc8
youtube_div_bv3a3flv425
I also needed a random id, I went with using base64 encoding:
btoa(Math.random()).substring(0,12)
Pick however many characters you want, the result is usually at least 24 characters.
Based on HTML 4, the id should start from letter:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
So, one of the solutions could be (alphanumeric):
var length = 9;
var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
var id = prefix + Math.random().toString(36).substr(2, length);
Another solution - generate string with letters only:
var length = 9;
var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);
Or you could use Cripto since it's already built in(except in IE11, I swear these guys havent updated in years!)
https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples
var id = new Uint32Array(10);
window.crypto.getRandomValues(id);
I also found this:
https://gist.github.com/6174/6062387#gistcomment-3255605
let length = 32;
let id = crypto.randomBytes(length).toString("base64");
There's a lot of ways to do this, but for most people, there's no reason to reinvent the wheel :)
A edited version of #jfriend000 version:
/**
* Generates a random string
*
* #param int length_
* #return string
*/
function randomString(length_) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (typeof length_ !== "number") {
length_ = Math.floor(Math.random() * chars.length_);
}
var str = '';
for (var i = 0; i < length_; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
For generating random ids, you can also use the standard crypto API with its randomUUID() function which is available in node.js (>=v16.7.0) and all relevant browsers except Safari:
const uuid = crypto.randomUUID()
console.log(uuid)
// prints e.g. "7f3f4512-fcf9-45fe-b726-512bba403426"
I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.
<div id="placeholder"></div>
Now, the idea is to dynamically create a new div, with your random id:
var rndId = randomString(8);
var div = document.createElement('div');
div.id = rndId
div.innerHTML = "Whatever you want the content of your div to be";
this can be apended to your placeholder as follows:
document.getElementById('placeholder').appendChild(div);
You can then use that in your jwplayer code:
jwplayer(rndId).setup(...);
Live example: http://jsfiddle.net/pNYZp/
Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)
May I an share an intuitive way to generate a randomID ?
const getRandomID = (length: number) => {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
Here is an easy one liner:
const generateUniqueID = (idLength) => [...Array(idLength).keys()].map((elem)=>Math.random().toString(36).substr(2, 1)).join("")
Where all you do is enter the idLength and it will return a unique id of that length.
generateUniqueID(23)
>>>'s3y9uebzuo73ih79g0s9p2q' // Id of length 23
First. Assign an id to your div. Like this:
<div id="uniqueid">This text will be replaced</div>
After that, add inside your <script> tag following code:
Document.getElementById("uniqueid").id = randomString(8);
window.btoa(String.fromCharCode(...window.crypto.getRandomValues(new Uint8Array(5))))
Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML5, an ID should start with a letter for compatibility.
function id(prefix = '', length = 7) {
let result = prefix;
for(let i = 0; i < length; i++) {
const random = Math.random();
result += String.fromCharCode(Math.floor(random * 26) + (random < .5 ? 65 : 97));
}
return result;
}
a random number between 0 and 25 is generated then added to either 65 or 97. When added to 65 it will give you an ascii code for a capital letter and when added to 97, an ascii code for a small letter.
Just use built-int crypto.randomUUID() which is supportted by all major browsers:
let uuid = crypto.randomUUID();
console.log(uuid);
I have the following function that produces numbered input fields with ids and names of the current timestamp they're were created. I'm trying to attach a datepicker to each one created, hence the unique/timestamp id's.
Can anybody suggest a way for me to go about doing this?
I believe the datepicker function needs to be produced under each input field created but I don't know how to produce a JavaScript function with JavaScript. I'm thinking maybe I can use jQuery's load() function and call a PHP script that produces a unique function and loads it into a div. Is that the best way to tackle this? Thanks!
<script>
var number = 0;
var num;
$('#add_date').click(function(event) {
number++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10){var month = "0"+month;}
if (day<10){var day = "0"+day;}
var fullyear = month+"/"+day+"/"+year;
num = event.timeStamp
$('#box').append( number+". <input type='text' id='" + num + "' name='" + num + "' value='"+ fullyear + "' size='10'/><br><br>");
var idtag = "#"+num;
});
</script>
Why not just set up the datepicker when you create the input?
var picker = $("<input/>", {
type: 'text',
id: num,
name: num,
value: fullyear
}).datepicker();
$('#box').append(number).append(picker);
Also you should make "id" values that look like valid identifiers instead of plain numbers.
Look at #Pointy's answer for an actual solution, he was quicker than me, my answer will not actually solve your problem, I just would like to mention a few points to note.
Try to indent your code properly, so it's easy to read for you after looking at it in a month's time. You might know now what it does exactly, but it will be a pain to figure it out in the long term.
As unlikely as it is, it can't be guaranteed that the same event won't fire twice in the same millisecond, I would avoid using event.timeStamp for generating unique IDs. It's just a personal preference though, it will probably never happen, I just don't like to rely on timers for uniqueness. You have your incrementing number variable already, you should use that, that will definitely be unique.
When writing HTML into a string, I would rather use the proper standard markup. Use ' as your string boundaries and " for your HTML attributes.
Lastly, inside your if(month<10){...} condition, don't redefine the variable you have already defined within your function. It would probably not throw an error or have any negative effect, but we can only thank the current forgiving javascript implementation for that, redefinition should not be allowed in the same scope.
Finally make sure you put all your jQuery initialisation code into the jQuery ready function to make sure the DOM and jQuery itself has fully loaded.
And sorry for the rant... ;)
$(function(){
var number = 0;
$('#add_date').click(function(event) {
number++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10) month = "0"+month;
if (day<10) day = "0"+day;
var fullyear = month+"/"+day+"/"+year;
// Insert #Pointy's solution in here...
});
});
You can add a fict
<input type='text' id='" + num + "' name='" + num + "' value='"+ fullyear + "' size='10' class='fake-class'/>
And then, you can load the datepicker object like this:
$('.fake-class').each(function(){
$(this).datepicker();
});
Hope it helps
Just a little correction about the variable num and number, #Pointy was using num and #DarthJDG was using number. Here is the complete code that worked for me
In Script:
var num = 0;
$('#btn').click(function(event) {
<!-- Set the default date to be todays date, can be removed for blank-->
num++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10) month = "0"+month;
if (day<10) day = "0"+day;
var fullyear = month+"/"+day+"/"+year;
<!-- End -->
var picker = $("<input/>", {
type: 'text',
id: num,
name: num,
value: fullyear
}).datepicker();
$('#holder').append(num).append(picker);
}
And in the HTML:
<input type="button" id="btn" value="button">
<div id="holder">
</div>
If I have a date like 8/9/2010 in a textbox, how can I easiest set a variable to the value 201098?
Thanks in advance.
var date = "8/9/2010";
var result = date.split('/').reverse().join('');
EXAMPLE: http://jsfiddle.net/hX357/
To add leading zeros to the month and day (when needed) you could do this:
var date = "8/9/2010";
var result = date.split('/');
for( var i = 2; i--; )
result[i] = ("0" + result[i]).slice(-2);
result = result.reverse().join('');
EXAMPLE: http://jsfiddle.net/hX357/2/
I would recommend using Datejs to process your dates.
You can do something like
date.toString("yyyyMMdd");
to get the date in the format you want
Using regex:
"8/9/2010".replace(/([0-9]+)\/([0-9]+)\/([0-9]+)/,"$3$2$1")
Do a split on '/', take the last element and make it the first of a new string, the middle element becomes the middle element of the new string, and the first element becomes the last element of a new string.
It would be like this:
myString = document.getElementById('date_textbox').value;
var mySplitResult = myString.split("\");
var newString = mySplitResult[2] + mySplitResult[1] + mySplitResult[0];
This is basically the idea I think you are going for.
-Brian J. Stinar-
Dang, it looks like I was beaten to the punch...
Or you can use the built-in JavaScript Date class:
function processDate(dStr) {
var d = new Date(dStr);
return d.getFullYear() + (d.getMonth() + 1) + d.getDate();
}
processDate("8/9/2010");
Easiest to manage and debug, certainly.