I have a javascript where I can create list items in HTML. At the moment I can drag and remove the items with another script. Now I would like to store some information within every list item created, for an example a JSON-object. Then afterwards I save the data in the right order in the database.
Is it possible, or should I go another way?
As Nikhita says you can add values as data-values attributes to the list items. For example if you want to store the id and name atributes you can do as follow, and recover the values with jquery:
<li data-id="1" data-name="name" class="listItemClick"> List item </li>;
$(".listItemClick").click(function(){
var id= $(this).attr("data-id");
var name = $(this).attr("data-name");
//TODO
});
#Javier's answer works if you are using jQuery.
Those attributes can be accessed through regular Javascript as well.
// Make sure you have a valid reference
var el = getElementBySomeMeans();
// Set the value
el.setAttribute("data-test-this", "10");
// Get the value
var v = el.getAttribute("data-test-this");
console.log(v);
// Clear the attribute
el.removeAttribute("data-test-this");
I should mention, for completeness, that there is an HTML5 dataset method that also works on the data attributes, but I personally don't use it since we have to support older browsers at work.
IF you have the luxury, might be worth looking into.
1 - save data in html in any hidden div
2- add data in any unique attribute
<li data-name="' + data-value + '"> List item </li>;
This should do the trick. Append whatever data value and data name you see fit.
Related
I want to access the inner text or inner html of specific cities that I am adding to my page. Since I entered 'moscow' first (then san diego, then oakland) getElementById is only picking up 'moscow'. Based on how my page is set up, I want to access the city name that is next to the 'navigate' button. Clicking on 'oakland' is rendering as 'moscow'. here are some photos: looks like the page is mapping out an array of objects. i want to access oakland if i click on oakland... and
my coode shown here, with the .map happening in the return section
#Lokendra Soni pointed me in the right direction. I got it to work by swapping .getAttribute("value") with .textContent. But the real trick was to utilize the item's unique ID in their tag's id names (for ex. <p id={displayedCity-${item.id}}>)
document.getElementById() always returns the first encountered element matching the provided id, that's why you're receiving Moscow as you've entered it first.
If you want to fetch the data from id attribute, make id of all the items unique.
Try modifying your goToCity method like this:
const goToCity = (id) => {
const x = document.getElementById(`displayedCity-${id}`).getAttribute("value");
navigate(`/${x}`);
}
Then modify your HTML:
...
<p id=`displayedCity-${item.id}` value={`YOUR VALUE`}>{item.item}</p>
<button className="button" onClick={()=>goToCity(item.id)}>navigate</button>
...
So here is the situation, im creating a clickable dynamic table by adding row with a button. Each row have informations and can be clicked (the entire row). I look for a way to send the information of the row I clicked to another js function who will copie the row in another dynamic table. But here is the trick : to create a clickable row, I use the function .append and I create the row in a < a> tag which will use href="function_to_add_the_copied_row" to call the other function.
The problem is I cant find out the good syntax. Any suggestion for syntax or other way to do the trick would be appreciated. Here is my code :
//javascript function to make clickable rows
{
var infos = modules_found[i].split("\\t");
rowNum++;
//word ="'Row number : "+infos[0]+"'";
$(".targets").append('<li> <div class="ui-grid-a"><div class="ui-block-a ui-grid-b"><div class="ui-block-a">'+infos[0]+'</div><div class="ui-block-b">'+infos[1]+'</div><div class="ui-block-c">'+infos[2]+'</div></div><div class="ui-block-b ui-grid-b"><div class="ui-block-a">'+infos[3]+'</div><div class="ui-block-b">'+infos[4]+'</div><div class="ui-block-c">'+infos[5]+'</div></div></div></li>');
}
//javascript function who receive the array and add the copied row
function transferArray(infos)
{
alert("in transferArray function");
$(".copied").append('<li> <div class="ui-grid-a"><div class="ui-block-a ui-grid-b"><div class="ui-block-a">'+infos[0]+'</div><div class="ui-block-b">'+infos[1]+'</div><div class="ui-block-c">'+infos[2]+'</div></div><div class="ui-block-b ui-grid-b"><div class="ui-block-a">'+infos[3]+'</div><div class="ui-block-b">'+infos[4]+'</div><div class="ui-block-c">'+infos[5]+'</div></div></div></li>');
}
Here is a high level approach (assuming you know jQuery): instead of wrapping your row inside A tag, better way is to have register a click event listener on your table (via jQuery APIs and not in HTML). In that click handler you can get the index of row clicked easily (make use of jQuery APIs) and once you have the rowindex, you can easily clone the row and move it to somewhere else.
typically how this is handled - if you are not using some type of javascript library like Angular or Knockout is to just store data in the actual HTML with data attributes. you can make as many data attributes as you want as long as they start with data-
ex.
$(".targets").append('<li data-id="xx" data-name="xx" data-custom=""> <a href="...
then I would recommend using jQuery click handler on every row by giving them all a class , ex.
$(".targets").append('<li class="rowClick" data-id="xx" data-name="xx" data-custom=""> <a href="...
then handle the click like this
$(document).on('click' , 'rowClick' , function(e){
var $this = $(this);
//get data of row clicked
var idClicked = $this.attr('data-id');
var nameClicked = $this.attr('data-name');
// you also have the full HTML of the clicked row if you need to copy somewhere
var rowHtml = $(".copied").append($this);
});
You're already using jQuery , so use it to handle the click and then you have the element clicked as a jQuery object right there . You can use native javascript function to handle the click and pass data like you were , but you already are using jQuery and that will automatically bring in a lot more data for you.
Finally, I used native javascript function since the suggested solution didn't work, even if it looks all legit. So here is what I have done:
(...)
//append the js function
$(".FindTable").append('<li id="addedFindRow"><div class="ui-grid-a"><div class="ui-block-a ui-grid-b"><div class="ui-block-a">'+infos[0]+'</div><div class="ui-block-b">'+infos[1]+'</div><div class="ui-block-c">'+infos[2]+'</div></div><div class="ui-block-b ui-grid-b"><div class="ui-block-a">'+infos[3]+'</div><div class="ui-block-b">'+infos[4]+'</div><div class="ui-block-c">'+infos[5]+'</div></div></div></li>');
}
function copyrow(info0,info1,info2,info3,info4,info5)
{
//use data
}
This is quite heavy, but that will do. Would be more chaotic if there was more parameters thought.
I have a class 'container' with an id.
<div class="container" id="1500"></div>
Now in my javascript I fetch the id with the following code:
$('.container:' + place).click(function(){
var id = $(this).attr('id');
});
Is there a possible way to link also a title in the class 'container'?
If I debug my code and set a watch point on the attribute $(this), there is a field 'innerText' and field 'OuterText' with the value I want, but I can't fetch it.
Is there a possible way to get these attributes or can I pass a variable by initializing the container?
i dont know if you can vincule that, maybe you can work with id only, and you can call via jquery for example if you have <div id="container1500"></div> yu can call var val=$("#container1500").html(); check here
now if you have a dinamic var, you can use var val=$("#container" + i).html(); where "i" is a dinamic var, for example in for(var i =0 ;....
Yes, using jQuery you can access them using $(this)[0].innerText and $(this)[0].outerText
Are you sure its a good idea to have an ID that starts with an integer and not a letter?
I am writing a Greasemonkey script and I need to be able to take the value from a hidden form element and set it to a variable.
The hidden form value looks like this:
<input type="hidden" name="ASIN" value="B009MO89Y4" />
I have no ID, class, or any way I can see to set the "value" to a variable. This needs to work dynamically and I currently have no way to establish a class or ID to this value.
Is there a Javascript (or jQuery) method to set this?
In other words:
Find "input" with name "ASIN" and set .val() to a variable?
This selector and assignment:
$("input[name='ASIN']").val(); <---- returns value of that input
var inputVal = $("input[name='ASIN']").val(); <-- Assigns it
var temp = "Stuff";
$("input[name='ASIN']").val(temp); <----Assigns the value of the temp var.
You can use the jQuery attribute equals selector
$('input[name="ASIN"]').val(foo);
You can select it via. name in jQuery like so:
var bar = "Example"; // Example text, to be used in val().
var x = $('input[name="ASIN"]').val(bar);
// Sets the variable x to be the value bar for the input with the name ASIN.
Here's a working jQuery jsFiddle.
In pure Javascript *:
var bar = "Example";
document.getElementsByName("ASIN")[0].value = bar;
Here's a working Javascript jsFiddle.
*Please note that although document.getElementsByName is supported well in Firefox, Chrome and Safari, it has limited browser support. in IE and Opera.
Like this:
$('input[name="ASIN"]').val();
Var:
var hiddenAsin = $('input[name="ASIN"]').val();
You can filter your selection with any attribute.
$('input[name=ASIN]').val("New Value")
You can use selector that targets inputs of type hidden. It should look like that:
$('input[type=hidden]');
or simpler:
$(':hidden');
Use this method
var inputs = document.getElementsByTagName('input');
for(var i = 0...)
{
//go through each input and look for the name "ANSI" and the type is hidden.
//and do your changes.
}
this is for javascript remember.
with this you should be able to get that specific hidden form without an ID nor a Class assigned to that specific form.
For pure javascript:
Try document.getElementsByName('name').
Note that cmptrgeekken pointed out that this has limited browser-support (although that would not be an issue with greasemonkey in FF).
As an alternative, if that hidden element has a fixed place you could also access it by index-number in a predictable collection that you got from knownParent.getElementsByTagName('tag')[#] (So the first hidden inputtag inside a form would be number 0).
Another variation is to get (again) knownParent.getElementsByTagName('tag') and loop over that collection to see what element has the 'name' attribute set that you seek.
Simply do:
var target=knownParent.getElementsByTagName('input'), L=target.length;
while(L--){ if(target[L].name==='name'){target=target[L]; break;} }
alert(target.value); //target is now the element you seek.
Example fiddle here.
Good luck!
So I am using http://isotope.metafizzy.co to filter out different items on a site. The menu should be a "build up" type where when one category is clicked, it filters to those categories, when the next is clicked it adds those newly clicked categories to the existing filter of categories. When its clicked a second time it should remove that categorie from the filter.
More specifically, I have href with #filter and data-filter=".category-name" I need to have a function that would add ", .another-category" to the end of data-filter value for each of the links with name="filters" (or i can use a class instead of if easier)
<ul>
<li>Kitchens</li>
<li>Bathrooms</li>
<li>Living Rooms</li>
<li>Bedrooms</li>
</ul>
I know this function is wrong and doesnt work but its just some pseudo-code
function addFilter(filter) {
names = document.getElementsByName("filters");
for (var name in names) {
name.data-filter = "existing filter, " + filter; // this should be appended to all data-filters
}
}
so basically when a link is clicked it both filters to that category only (lets say kitchens), but also adds the category to the rest of the data-filters (.bedrooms, .kitchens)
javascript or jquery or anything else i may have not realized could work. the documentation for isotope has the option to filter multiple groups of items, but I need it to filter combinations of individual items. Maybe its possible to modify their combination filters to items instead of groups?
See the following article as placed in this post. It should put you in the right direction.
http://www.queness.com/post/7050/8-jquery-methods-you-need-to-know
Stackoverflow question
jQuery - How to add HTML 5 data attributes into the DOM
Well you tagged jQuery, which makes this easy, but I only see you using JS. Anyway, here's one way and some extra info, hope it helps:
jsFiddle {with replication}
jsFiddle {without}
Script
$('li a[name="filters"]').on("click", function(e) {
e.preventDefault();
$(this).data("filter", $(this).data("filter") + ".another-category");
/* and if i wanted to do it without replicating already existing info:
var f = $(this).data("filter");
if (f.indexOf(".another-category") == -1) f += ".another-category";
$(this).data("filter", f); */
});
HTML
<ul>
<li>Kitchens</li>
<li>Bathrooms</li>
<li>Living Rooms</li>
<li>Bedrooms</li>
</ul>
X-tra NFO
jQuery.data(): Biggest Deference - Returns the value that was set
jQuery's .data(): Biggest Deference - Returns the element that was manipulated