document.getElementById works, but $ is throwing an error - javascript

I have this code here :
<select id="test">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
In my script I have these two line of code, one is JavaScript and another one is jquery like so :
var e = document.getElementById("user");
var e1 = $("#user");
I even printed out those in my console like this :
console.log(e)
console.log(e1)
They are printing same thing. But when I write a on change event code like this :
$("#user").change(function() {
console.log(e.options[e.selectedIndex].text)
});
It is exactly printing what I choose from drop down. That this javascript way of fetching from dom is working. The same thing with e1 like so :
$("#user").change(function() {
console.log(e1.options[e1.selectedIndex].text)
});
is throwing an error :
Uncaught TypeError: Cannot read property 'undefined' of undefined
(anonymous function)create:167
f.event.dispatchjquery-1.7.1.min.js:3
f.event.add.i.h.handle.i
(seen from chrome's developer tools)
Whats going on? I'm new to both Javascript and jquery! Why in my case jquery is not working?

Since you're using jquery and e1 is a jquery object try:
console.log(e1.find('option:selected').text())
To grab the actual element you can use get():
var select = $('#select').get(0) // Grab original DOM element
select.options // It'll work now...

var e = document.getElementById("user");
this creates an javascript object.
var e1 = $("#user");
This creates an jquery object. You can't use javascript properties on this. You must use jquery properties.

The select menu you give at the top of your article has an id of 'test' not 'user'. I assume the code you're actually working with has an id of 'user'. e1 is a jQuery object, so to access it's value use e1.val() instead of e1.options[e1.selectedIndex].text. You're mixing javascript code with jQuery code.

e1 is a jQuery object because you used jQuery to select it. It is not the normal js dom element, which is how you are trying to use it.
This should work better:
$("#user").change(function() {
    console.log(e1.val());
 });
val() is a jQuery function that provides a unified wrapper around form element values so you don't need to find the selected index, access that from the select obj, etc. This is one of the things jQuery does that makes life easier.

console.log(e1[0].options[e1[0].selectedIndex].text)

Related

how to reformat jQuery / JS function properly?

can't figure out how to write this as a function without the jQuery
This works & returns what I need:
var state = $('#order_ship_address_attributes_state_id option:selected').text()
Which is the text from an options list aka "Florda" instead of "3534"
<option value="3534">Florida</option>
However, I would like it written in this convention instead:
var city = ((document.getElementById('order_ship_address_attributes_city')||{}).value)||"";
... to match the rest of my variable declarations.
Trying this but error read "Uncaught TypeError: Cannot read property 'text' of null"
var state = ((document.getElementById('order_ship_address_attributes_state_id option:selected')).text())
Can't figure out the correct way to write this — any help would be much appreciated : )
As #benvc pointed out. You want to use .textContent instead of calling the .text() jquery method.

textContent returns undefined

I have a table in which I want to extract the text of the active item. I do this with the following code:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
console.log(addedWorkout);
addedWorkout = addedWorkout.textContent;
console.log(addedWorkout);
The problem is that I keep getting undefined. I checked the console and it indeed finds the element I want without fail.
I am relatively new to Javascript, but after over an hour of Googling I could not find the issue and I don't understand why. I know that I can get the text element if I hardcore it using the following line:
document.querySelector("#selectiona1").textContent
but not with:
$("#selectiona1").textContent
What is the difference between these 2? I read that textContent is part of the DOM, to my understanding it relates to objects and according to my console i think it is an object. I made some crazy attempts like putting the object I got into the querySelector, but nothing works.
With this line:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
you're using jQuery to select the .dropdown-item.active inside #custDropDownMenuA, and when you select with jQuery, you get a jQuery object in response. So, addedWorkout is a jQuery object, and jQuery objects generally do not have the same properties/methods as standard HTMLElements. (querySelector is the vanilla Javascript method to retrieve an element)
Either select the [0]th item in the jQuery collection to get to the first matching element:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active")[0];
Or use the jQuery method to get the text of the first matching element, which is .text():
var addedWorkoutText = addedWorkout.text();
(note the use of a new variable - you will likely find it easier to read and debug code when you create new variables rather than reassigning old ones, when possible)
Your var 'addedWorkout' is a Jquery object, not a html element.
To show the text use:
addedWorkout.text();
Alternatively, you can change the 'addedWorkout' to a html element by adding the index [0], like this:
addedWorkout[0].textContent;

jQuery version of simple javascript doesnt work

I have this code in javascript
var greet;
greet = function() {
var textoNombre;
textoNombre = document.getElementById("textoNombre");
return alert(textoNombre.value);
};
what is working on the HTML document. But if I change document.getElementById("textoNombre") by the jQuery version $("#textoNombre") it just dont work. The alert says "undefined".
I have the jQuery script linked on the head of the HTML before to my custom js file.
This is a very basic question but I tried different things and no one work, can you help me please? Thank you in advance.
That's because jQuery objects don't have a value property, the equivelant is $('#someId').val().
To get the underlying DOM object, you can use $('#someId')[0]. This is because jQuery objects are actually like arrays, and their elements are the DOM objects themselves. That means $('#someId')[0].value would work as you'd expect.
jQuery objects are not DOM objects and don't share all their properties.
To get the current value of a form control, you would use the .val() method, not the .value property.

How to set attributeName to "value"

I'm trying to assign "value" as attributeName to a jQuery object. However, I am getting the "Object doesn't support this property or method" error. Here is the line:
$(rowElem).attr("value","");
I think I am getting this error because jQuery treats the word "value" as another method and not as an attribute. I will gladly appreciate help from you guys. Thanks in advance! :)
Hi you are doing it wrong , Jquery need a selector whether its id , class or tagname
for Id you need to add prefix "#" For Class you need to add prefix "."
and tag name as it is....
So your fixed code is something like that
$("#rowElem").attr("value","My New VAlue");
When ever you use value I think the only jquery you will use is
$(rowElem).val("");
It is however, not a good practice to use 'value' as any other attribute, what you can do is with HTML5, make your own attribute as
<tr data-value="somevalue" />
and use the attribute like
$(rowElem).attr("data-value", "");
and you can use that attribute's value like
var val = $(rowElem).attr("data-value");
There is nothing wrong with the code that we can see. It looks like you don't have jQuery loaded in the DOM. See my tests below.
i.e. If you go to backbonejs.org and type in the following in the console:
if(jQuery)
console.log('jQuery has loaded');
// logs 'jQuery has loaded'
var rowElem = 'div';
$(rowElem).attr('value', '');
It successfully adds 'value' to the divs.
However, if you use a site without jQuery like underscorejs.org, it won't work:
if(jQuery)
console.log('jQuery has loaded');
// ReferenceError: jQuery is not defined
var rowElem = 'div';
$(rowElem).attr('value', '');
// TypeError: Object #<HTMLDivElement> has no method 'attr'
You need to get it access to jQuery and your problem should be solved.
There is no such attribute in jquery or javascript. Both treats value as a separate function.
You can try using:
jquery: $(rowElem).val("urVal");
javascript: rowElement.value = "urVal";
use this.. provide value in val
$(rowElem).val("value");
hope it works...

Add non-standard attribute to a select tag with Javascript

I want to create a select element through JavaScript and I want to set an attribute to it called data-placeholder.
How can we assign non-standard attributes with JavaScript without the browser complaining with:
Uncaught referenceError: Invalid left-hand side in assignment
Code that cause the error:
select1.data-placeholder="Choose ...";
Since it says with javascript not jquery...
yourElement.setAttribute('data-placeholder','value');
Here's a pretty simple non-jQuery way to achieve this;
var el = document.createElement('select');
el.setAttribute('data-placeholder', 'placeholder value');
document.body.appendChild(el);​
I've created a very simple JSFiddle to demonstrate it.
Hope that helps!
JQuery makes this easy:
$("<select></select>").attr("data-placeholder", "value").appendTo($element);

Categories

Resources