Extract Property value from NodeList - javascript

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.

Related

How to get element of an array stored in one value

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.

Trying to remove an element with data-value equal to a previously created variable?

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();

jQuery data function returning the first value

I have a one span tag with data attribute, data-kr-id. On clicks of different items of the list, I update this span's data-kr-id attributes and it gets updated.
When for the first time I retrieve this(data-kr-id) value using jQuery's data method, I get the correct value. But from the subsequent time, I always get the same value as of the first time. But on using jQuery's attr function, I get the correct value. Can't figure out why.
CODE: Where I set the data-kr-id value:
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
CODE: Where I retrieve the values:
var topicId = $applozic(this).data("kr-id");
topicId = $applozic(this).attr("data-kr-id");
In the above code where I retrieve values, using data method gives me old value(the value of the first item I retrieved), but using attr method gives me correct value.
UPDATE :
As informed by everyone, I was setting the data attributes with attr method and retrieving the value with data method. After using data method for setting the attribute, When I was retrieving the values, I was getting a getting empty string. After digging a bit deeper, I realized there are two different versions of the jQuery are being used here.
Sorry for the incomplete information and late update.
You set value only using attr, Second time when you set data-kr-id value using attr then data value remains same, so need to set value with data also
// With Attr
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
// With Data
$_applozicWtLauncherBtn.data('kr-id', seller.UserId);
Actually jquery's .data() fetches value from the property (same as .prop()) not from attributes. Main difference is .attr() fetches data from HTML tag which you can see it will reflect on your HTML when you update it with .attr(). But when you use .prop() or .data() it will not reflect in HTML tag but it will update value in it's property for that HTML tag as per the DOM tree.
You'll find out more about difference property and attribute from here.
Initially this property will set when your element is created. So for the first time your .data() and .attr() will work fine. When you update value from .attr() it will manipulate DOM but property will be remain same.

Locating user input from a form and assigning it to a property

I have a form, that takes user[name, age, photo], as inputs of type text.
I want to locate it the input in the HTML and then assign it to a property;
newProductData.name = $('#new-product-name').val;
I used this, but newProduct.name, doesn't get assigned the value, which would be say for instance "ibrahim". How would I go about getting the string value entered into the form, and assigning it as a property.
You need to call the function actually instead of just referencing it. Add ():
newProductData.name = $('#new-product-name').val();

Editing objects in jQuery

$(function(){
var z = document.body.children[0];
var x=$("li", z);
x.name="Johnny";
alert(x.prop(name));
});
x should be an object containing all the elements within the first ul in the body.
Regardless of what the object contains, I would like to add a property with a value, and then use the prop() method to show it - but that doesn't seem to work. Why is that?
I saw a script containing the following: var $x = $("div"); - Do I have to add $ to the variable name if it's a jQuery object?
To select the first ul element inside a page you can do:
$("ul:first li")
This way you are going to select all lines inside the first list in the page.
To store arbitrary data in an element you can use the method data, like this:
$("element").data('key', 'value');
and to retrieve the data:
$("element").data('key');
More info, for the data method.
If you really want to add an attribute you can use the attr method, it works the same way as the data method, but it would reflect in the DOM.
If you want all li elements in the first ul element, then this should do the trick:
var elements = $("ul:eq(0) li");
Here is a very simple example of this in action.
In regards to setting a property, you can do element.name = "test" and it will work ok. But what you need to understand is that this is setting a name property on the jquery collection object and NOT on any of the actual elements.
What you can do however, is set the property like so:
elements.prop("name", "test");
and the access it like so:
var name = elements.prop("name");//name will be "test"
Here is a working example
As I mentioned in my comment, you don't need to prefix the variable with $. But this can be helpful to easily see which variables are JQuery objects.
Number 1. x is a jQuery object, you added to that instance a name property, then you're using name though it wasn't defined.
If you want to change a property of the element you got with jQuery the ways are:
$('selector').prop('property', 'value');
$('selector').attr('attribute', 'value');
$('selector').get(index).property = "value";
Number 2. no you don't have to, $ prefix is simply a convention to make the code more readable.
Is there any specific reason behind using $ with variable in jQuery
Using the selector from #musefan answer, you can take the collection returned, and use the attr() method to add an attribute and value to each item selected. However, I've modified his selector slightly to actually grab "all" elements in there, (just in case future visitors wonder)
var elements = $("ul:eq(0)").children();
elements.attr("attrName", value);
So if you wanted to set the title:
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny");
You probably don't want to alert these values, browsers may ask you to stop allowing alerts on the page... but if you really did, then you could throw in an .each() after that.
var elements = $("ul:eq(0)").children();
elements.attr("title", "Johnny").each(function(){
alert($(this).attr("title");
});

Categories