Javascript/HTML assigning a value - javascript

I am having a problem with some Javascript/HTML/CSS code. I am fairly new to creating websites, so please bear with me.
what I am ultimately trying to do is pull a dynamic value from javascript and use that to sort some divs (in a container). What I am thinking is I will assign the value to the Id and then pull those into an array to be sorted by tinysort. If there's a faster way to do this, let me know.
However, my first problem is putting the data into the id so it can be sorted. Would I do something like
document.getElementById(namesort).value = iterator;
or would I use something like myData?
Note: I don't want to display the value, I just want to use it to sort.
Please ask for clarification if needed! Thanks in advance. :)
Here is the applicable code to this problem. http://jsfiddle.net/dw77hLyp/1/
It just basically shows a very basic outline of some of my code.

Without JQuery. You can create your attribute :
document.getElementById(namesort).createAttribute('myData');
document.getElementById(namesort).setAttribute("myData","hello Im in");

Pure JS Solution:
for( i = 0 ; i < iterator.length ; i++ ) {
document.getElementsByName('namesort')[i].setAttribute('data-sort',iterator[i]);
}
That way you add each of those elements an attribute called data-sort where the iterator as a value, then could create an array insert all the namesort elements to it, use the sorting algorithm and you're done.

document.getElementById("divID").innerHTML="someContent";

Related

How to get value of Qualtrics Drag & Drop Choice using Javascript

I have what should be a simple answer. I have a drag and drop style multiple choice question on Qualtrics. I have recoded the answers as I wish. I think it assigns to each answer a variable like QID15_1 QID15_2 QID15_3, etc. The outputted data then gives the rank order of that selected option.
So if I ranked them, for example
QID15_3
QID15_1
QID15_2
The value of QID15_3 =1, the value of QID15_1=2, and the value of QID15_2=3.
What is the correct syntax to access these values? I want to set an Embedded Data item with the value of QID15_1, for example (so it should equal 2), but I can't seem to get it correct.
I've tried Qualtrics.SurveyEngine.getSelectedAnswerValue and things like this.
Any help would be appreciated. Thanks!
EDIT: With the help of a friend who knows Java, we figured it out. You can write something like
Qualtrics.SurveyEngine.addOnUnload(function()
{var order=document.getElementById( 'QR~QID15~1' ).getElementsByClassName( 'rank' )[0].innerText;
}
You don't need to set an embedded variable in JavaScript. You can just pipe the value wherever you need it (in a subsequent question, in the survey flow, etc.). It would be:
${q://QIDx/ChoiceNumericEntryValue/y}
where x is the question id and y is the choice id.
EDIT:
You can assign it to an embedded data variable in the survey flow like this:
edvar = ${q://QIDx/ChoiceNumericEntryValue/y}

How to get unique id from localStorage for delete button

I have been trying for getting an id from localStorage but unable to achieve it.
My localStorage inside events contains such as below.
[{"id":"ef5","title":"wan","start":"2016-05-12","end":"2016-05-13"},{"id":"ef6","title":"wana","start":"2016-05-21","end":"2016-05-22"},{"id":"ef7","title":"haha","start":"2016-05-25","end":"2016-05-26"},{"id":"ef8","title":"asdas","start":"2016-05-20","end":"2016-05-21"},{"id":"ef9","title":"sdas","start":"2016-05-19","end":"2016-05-20"}]
Now i will provide 2 coding with different method that i have tried so far. For information, i look through into this topic: localstorage: Get specific localstorage value of which contains many items
but none works for me.
I did tried coding as below:
1st method:
$("#deleteEventYes").click(function(){
var indexDel = localStorage.getItem("events");
var deleteId = calEvent.id;
var result = localStorage.getItem("events");
function getItemHrefById(json, itemId){
return $(json).filter(function(){return this.id == itemId;})[0].href;
}
var href = getItemHrefById(result, deleteId);
alert(href); });
Above code show some kind of array method (i think) where i'm using indexDel to get item from localStorage (events) while deleteId i took from calEvent.id which is the id for the event that has been clicked for to be deleted. Other than that, i think you guys know what it is. However for this method, i use result variable instead of indexDel. Thus don't mind if i getItem from localStorage 2 times
2nd method:
for (var i = 0 ; i < indexDel.length ; i += 1) {
if(deleteId == indexDel[i].id) {
return indexDel[i];
console.log(deleteId);
console.log(indexDel[i]);
}
}
return null;
Above code is using custom loop i think. The declaration of variable for indexDel is still the same with first method. I try to use the refactoring method but it seems its hard for me to understand how is it to be done. Is it because my variable placement is wrong? or is it because it is not suitable for my case?
NOTE: I want to delete an event inside eventClick function, and so far i did retrieve the id and remove the event from the calendar based on id. However my only problem now is to match the deleted event id with the id inside my localStorage and remove the item. So far getting an id from the is quite complicated for me.
UPDATED
I already done something like this but still don't work. Anyone can tell me what went wrong here? It is not giving me any error but it just do nothing. Not even delete.
https://jsfiddle.net/v35a2o07/3/
Never mind. I think i figure it out :)
It is because i forgot to setItem & stringify it after using splice.
Here i can assume splice is the same as add/remove such wrote at w3school
http://www.w3schools.com/jsref/jsref_splice.asp
"The splice() method adds/removes items to/from an array, and returns the removed item(s)."
My final code is on this fiddle given: https://jsfiddle.net/v35a2o07/4/
So the concept is:
1) First step is declare one variable that parse your localStorage key such asvar items = JSON.parse(localStorage["events"]); so that you can use it for the loop
2) Use for loop to determine the length of localStorage based on localStorage key that we parse on No. 1
3) Use if statement to check the comparison between localStorage data with our desire data such as if(items[i].id == deleteId){
4) This is OPTIONAL but important. To enable you to check the comparison is right, create one alert or console.log() and stringify it because if you don't, you will only see [object,object]. The coding such as alert(JSON.stringify(items[i])+"<<<>>>"+deleteId); Make some else statement too if you want to be sure.
5) When all the conditions are correct, then you are ready to do some action to it. For my case, i just use splice() to delete it. It is also can be used to add item. I am not sure how is it done but try to search for it to get more info.
6) After splicing it, it is safely to break and get out from the loop.
7) This is important otherwise, it will not work. Don't forget to set it back to localStorage and stringify it such as localStorage.setItem('events', JSON.stringify(items));
That's it.
I wish this would help anyone that needs it. If i have make wrong statement or wrong concept, please make correction and clarify it for anyone.
Cheers.

jQuery single line code optmization for getting and setting for the same input element

I'm using PHPStorm and have the following js code
$('#id'.val($('#id'.attr('default'));
The idea is to reset the value of a input field to it's default which is set in default attribute of the input element.
Now the IDE is suggesting me to avoid duplicate selectors.
Though it is working I'm interested in finding out what is the best way to optimize this code line?
Not exactly what you asked for but more future proof using data and not an attribute. You could even store complex data or other information in there as well like "originalvalue" or "lastchangedvalue" etc.
Storing in an attribute is fine however I prefer to store things like this in the data of the element like:
<myelementtag id="myid" data-defaultvalue="defaultvalue" />
You then access it like:
$('#myid').data("defaultvalue");
For example:
var myElement = $('#myid');
myElement.value = myElement.data('defaultvalue');
Want to reset the default?
var mynewdefault = "mynewvalue";
myElement.data('defaultvalue', mynewdefault);
Since you asked only one selector and one line code, please use like this as stated in jQuery documentation (middle section):
$("#id").val(function(index,value) {
return $(this).attr('default');
});
or if you want to avoid $(this):
$("#id").val(function (index, value) {
return this.getAttribute('default');
});
JSFiddle
And yes, as other members have pointed out, it would be better if you use data attribute (data-defaultValue) instead.
This is a more compact solution:
var id = $('#id');
id.val(id.attr('default'));
You really don't need to use $(...) every time.
Store your jQuery element in a variable:
var $id = $('#id');
$id.val($id.attr('default'));

How to Split many Strings with Jquery

Let's say I have a bunch of strings which I get from user input. Each strings starts with a new line like the following example:
gordon:davis
harley:vona
empir:domen
furno:shyko
I would like to write a function in jQuery which loads the user data from the form and splits each row's sting. However I would ONLY need the first part of the strings, like:
gordon
harley
empir
furno
Is there any simple solution for this?
I have found something called: $.each(split) but I didn't get it work.
I'm sorry I'm a really newbie in Jquery, I hope you guys can help me out! Thanks in advance!
Use String.prototype.split method.
"gordon:davis".split(":") will return ["gordon","davis"]
Based on this, using Array.prototype.map or a JQuery version :
var strings = ["gordon:davis", "harley:vona"];
var splitStrings = strings.map(function (string) {
return string.split(":")[0];
});

Trouble converting Javascript array into JQuery for IE7 compatibility

I am trying to convert a line in Javascript so that the functionality works in IE7. Below is the code I am trying to convert. Obviously IE doesn't like the class attribute being set which is where the issue occurs. So my solution was to translate it using JQuery for browser compatibility. But I am having trouble converting the array into something JQuery understands.
This is the code:
ulAccNm.children[iVal].setAttribute("class", "show");
I have tried the following, but it doesn't work correctly.
$(ulAccNm).children(jQuery.inArray("iVal")).addClass('show').removeClass('hide');
The variable of iVal translates into the total number of children to the parent and loops through each to determine to add a class or not. Any help would be greatly appreciated.
I'm guessing a lot here, but I think this will translate:
$($(ulAccNm).children()[iVal]).addClass('show').removeClass('hide');
However, if you want to do this to ALL the children, you don't need an explicit loop with iVal. Just use
$(ulAccNm).children().addClass('show').removeClass('hide');
You may just want to try changing your loop structure from a for loop to the jQuery.each method:
$(ulAccNm).children().each(function () {
// Decide if the class needs to be changed
if (needsToBeChanged)
$(this).addClass('show').removeClass('hide');
})
Ended up fixing by using Kevin B's suggestion of .children().eq(ival) and this makes it work

Categories

Resources