I wonder if there is a way to get a certain element of an array, which is stored in a single value. Sounds weird, I know, but this is my problem:
HTML
<select id="select">
<option value='{"array":["a","b"]}'>Option</option>
</select>
<button onClick="getArrayIndex()">Button</button>
--> I got one array with two elements (a and b) stored isnide one value in an option tag.
JS
function getArrayIndex() {
alert(option.value[0]);
}
So what I need is that the alert message displays only one element of the array, I hope this is somehow possible, thanks for answers! As you can see I tried to display only element 0, in this case "a", but it doesn't work.
I also tried these:
alert(option.value.array[0]);
alert(option.value.array(0));
alert(option.value(0));
alert(option.value.[0]);
...and so on. But none of these work.
Your value is a string containing JSON defining an object containing an array property with an array, rather than actually being an array. To use just the first element in that array, you need to parse the JSON into the object and array, then access the array from the object and get its first element:
alert(JSON.parse(option.value).array[0]); // "a"
Note that your getArrayIndex function currently uses an option identifier that doesn't appear to be defined anywhere. If you want to use the currently-selected value in the select, then:
function getArrayIndex() {
const select = document.getElementById("select");
const value = select.value;
if (value) {
alert(JSON.parse(value).array[0]);
}
}
Side note: I would xyz-attribute-style event handlers. Instead, hook up the event handler using modern techniques (such as addEventListener). Also beware that the default type of the button element is "submit", so if that button is in a form, by default it will submit the form.
Related
When I click on a "trash" button I want to delete the message block. There are multiple message blocks but they all have unique data-values. The id of the targeted block I want to delete is stored in the data-value of .send-message-button.
I tried making a variable that I could pass onto the targeted .messageblock element. I checked with an alert to see if the variable gets the proper number, which it does. However when I alert the whole thing, it gives [object object] (without the .remove, of course).
How can I do this?
var trashid = $(".send-message-button").attr("data-value");
$('.message-block').attr("data-value", trashid).remove();
If you want to retrieve an element using the value of one of its attributes you need to use the attribute selector, not the setter of the attr() method.
There's two main ways to do this. Firstly if the data attribute is present in the DOM then you can use an attribute selector:
var trashid = $(".send-message-button").data('value');
$('.message-block[data-value="' + trashid + '"]').remove();
Alternatively if the data attribute is held in jQuery's cache (as will be the case if you use data() as a getter/setter, as you should be) then you can use filter() instead:
var trashid = $(".send-message-button").data('value');
$('.message-block').filter((i, e) => $(e).data('value') === trashid).remove();
I’m learning javascript and trying to write code that sorts a list, removing elements if they meet certain criteria.
I found this snippet that seems promising but don't have a clue how it works so I can adapt it to my needs:
list = document.getElementById("raffles-list").children; // Get a list of all open raffles on page
list = [].filter.call(list, function(j) {
if (j.getAttribute("style") === "") {
return true;
} else {
return false;
}
});
Can you guys help me learn by explaining what this code block does?
It's getting all the children of the "raffles-list" element, then returning a filtered list of those that contain an empty "style" attribute.
The first line is pretty self-evident - it just retrieves the children from the element with id "raffles-list".
The second line is a little more complicated; it's taking advantage of two things: that [], which is an empty array, is really just an object with various methods/properties on it, and that the logic on the right hand side of the equals sign needs to be evaluated before "list" gets the new value.
Uses a blank array in order to call the "filter" method
Tells the filter to use list as the array to filter, and uses function(j) to do the filtering, where j is the item in the list being tested
If the item has a style attribute that is empty, i.e. has no style applied, it returns true.
Edit:
As per OP comment, [].filter is a prototype, so essentially an object which has various properties just like everything else. In this case filter is a method - see here. Normally you just specify an anonymous function/method that does the testing, however the author here has used the .call in order to specify an arbitrary object to do the testing on. It appears this is already built into the standard filter method, so I don't know why they did it this way.
Array like objects are some of javascript objects which are similar to arrays but with differences for example they don't implement array prototypes. If you want to achieve benefits of array over them (for example like question filter children of an element )you can do it this way:
Array.prototype.functionName.call(arrayLikeObject, [arg1, [arg2 ...]]);
Here in question array like is html element collection; and it takes items without any styling.
list is assigned a collection of elements that are children of the raffles-list element
list is then reassigned by filtering its elements as follows
an empty array is filtered by calling it with the parameter list and a callback function. The formal parameters for call are this (which is the list) and optionally further objects (in this case a callback function)
The callback function receives a formal parameter j and is called for each element
If the element's value for the style attribute is empty the element is retained in the array. Otherwise it is discarded.
At the end list should contain all elements that don't have a value for its style attribute
I have a list of unique ID's of a parent nodes children stored into childrenIDs.
var childrenIDs=["8b69b08e-d75e-6ef6-2cf4-275ff130cd74","42325602-9312-3565-b7dc-37383ca53c17", "2c91dcd6-7436-eff5-393e-cea8cbef338c"]
I then assign those IDs to the second element of another array
nodeArray[index].splice(0,1,childrenIDs);
When nodeArray[index][0] is entered into the console, the right output (containing all of the IDs) is printed. However, if I type childrenIDs.length = 0 to clear the first array, calling nodeArray[index][0] produces a null output. It seems as if nodeArr[index][0] is almost acting as a pointer to childrenIDs in the way that when childrenIDs is cleared, so is nodeArray[index][0].
I need to be able to reuse childrenIDs. Is there something wrong with how I am clearing the array and is there a way for me to preserve the data in nodeArray[index][0] after clearing childrenIDs?
Can you try using this statement?
nodeArray[index].splice(0,1,childrenIDs.slice(0));
Instead of assigning the array as child, you should assign a copy of it.
childrenIDs.slice(0)
Which would look like this:
nodeArray[index].splice(0,1,childrenIDs.slice(0));
Inside a javascript function Im accessing a text box with a value of 'c29TMlzE4vmFlJHieICpso_u04oa'. Below is the javascript function i'm using.
function test(){
var txt = document.getElementsByName("consumerKey");
alert(txt.item[0].getPropertyValue);
}
The alert shows as 'undefined'. In console I'm getting below as NodeList value of the txt.
NodeList[input#consumerKey property value ="c29TMlzE4vmFlJHieICpso_u04oa" attribute value = "null"]
How can I extract 'c29TMlzE4vmFlJHieICpso_u04oa' from the nodelist.
Thanks
item is a method, so you call it with a parameter:
txt.item(0)
Or you could access it as
txt[0]
getPropertyValue is for getting CSS property values from a style object, and is not relevant here. You simply want to access the value member of the input element:
txt.item(0).value
txt[0].value
However, there is really no need to use name attributes, except in special situations such as to group radio buttons. You're better off using IDs and getElementById. Then you don't have to worry about taking the first item.
Im having a problem setting options to an array value in a jQuery plugin using data attributes.
If I reference the data attribute using a class selector
$('.tm-input').tagsManager(
{
prefilled: $('.tm-input').data('load')
})
It works but all the elements get the same values.
If I reference using "this" it sets the correct values but it comes across as a string not an array.
$('.tm-input').tagsManager(
{
prefilled: $(this).data('load')
})
I've tried using JSON.parse() but I get an error about an unexpected character. Any help would be appreciated!
Have you tried each
$('.tm-input').each (function () {
$(this).tagsManager( { prefilled: $(this).data('load') });
});
Explanation:
When a selector has more than 1 element, applying a method to it will typically affect all of the elements, but retrieving a property will typically only return that property from the 1st element.
So when you use .tagsManager on your $('.tm-input') selector, you are applying .tagsManger to all of the elements. But when you set prefilled:$('.tm-input').data('load'), the data method is only grabbing the data from the first element in the list, every single time.
When you use each, it applies the logic inside of the each block to each element individually, rather than all of them at once, so when you use $(this).data('load'), it grabs the load attribute from each individual element as well.