JQuery.attr () and value

I want to use the following: .attr ();

selectbox.options[selectbox.selectedIndex].value 

Unfortunately,

 selectbox.options[selectbox.selectedIndex].attr("value") 

not the same, and seems to completely destroy the .attr target. My main question is: how should nested .attr () s be used?

Muchos gracias mi amigos

+2
source share
4 answers

To get the value of any type of input element (including <textarea> and <select> ), use .val() :

 var value = $(selectbox).val(); 

.attr() will look rude:

 $(selectBox).find(":selected").attr("value"); 

.... but just use .val() :)

The main problem is that .attr() is a jQuery method. This is on jQuery objects, not directly on DOM elements, the same goes for almost all jQuery methods and plugins.

+7
source

When using attr () you must work with the jQuery object. Therefore, first select the appropriate selection block, then call attr () (or val () in this case, when you need the value of the input element).

 var value = $(selectbox).val(); 
+1
source

If you want to get the selected field value using your current code, just pass it to the jquery object, for example:

 $(selectbox.options[selectbox.selectedIndex]).attr('value'); 
+1
source

The reason they do not match is because attr('value') gets the value of the value attribute directly from the HTML source code, does not update from the DOM , which means that if the value from value changes after the page loads or by input by the user (input to the <input> element, or by manipulating JavaScript, these changes will not be displayed in the returned .attr() value.

It is best to use the .val() method of the jQuery object.


Edit To get a value attribute from a DOM element (i.e. not returned by the $() or jQuery() function), use the element.getAttribute() method, which is native, you would use it like this:

 selectbox.options[selectbox.selectedIndex].getAttribute("value"); 
0
source

Source: https://habr.com/ru/post/1400240/