-1

if iam getting value of x and y by document method than its ok but if i get value of x and y by directly as below which is commented out by me than i get error why this is so?

 <!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
 <body>

    Select a fruit and click the button:
    <select id="mySelect">
      <option value="11">Apple</option>
      <option value="12">Orange</option>
      <option value="13">Pineapple</option>
      <option value="14">Banana</option>
    </select>

    <button type="button" onclick="myFunction()">Display index</button>

    <script>
    function myFunction() {

        var x = document.getElementById("mySelect").selectedIndex;
        var y = document.getElementById("mySelect").options;

        //var x = $("#mySelect").selectedIndex;
        //var y = $("#mySelect").options;


        alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " +  y[x].value);
    }
    </script>

    </body>
    </html>
sampathsris
  • 21,564
  • 12
  • 71
  • 98
kki3908050
  • 165
  • 2
  • 9

6 Answers6

3

i get error why this is so

Because the object returned by the jQuery constructor doesn't have selectedIndex or options properties.


$('selector') creates a jQuery collection out of matches in the DOM whereas document.getElementId('selector') is a reference to a specific DOM element.

$('selector') contains a reference to the DOM element, but doesn't have DOM element properties/methods, instead it has jQuery methods.

To use DOM element properties/methods, you can 'get' the DOM element from the jQuery collection using square bracket notation, since our jQuery collection is an array-like object:

var x = $("#mySelect")[0].selectedIndex;
var y = $("#mySelect")[0].options;

Or, using .get():

var x = $("#mySelect").get(0).selectedIndex;
var y = $("#mySelect").get(0).options;

Or, return a property value using .prop():

var x = $("#mySelect").prop('selectedIndex');
var y = $("#mySelect").prop('options');
George
  • 36,413
  • 9
  • 66
  • 103
2
  1. For document.getElementById(“id”) vs $(“#id”) see this question

  1. var x = $("#mySelect").selectedIndex;
    var y = $("#mySelect").options;
    

selectedIndex and options are undefined. You should use .text() and .val()


  1. Solution for your snippet
    $('#btn').on('click', function() {
      // var x = document.getElementById("mySelect").selectedIndex;
      //    var y = document.getElementById("mySelect").options;
    
      var x = $("#mySelect").val();
      var y = $("#mySelect option:selected").text();
    
      alert(x + " :: " + y);
      //alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " + y[x].value);
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    Select a fruit and click the button:
    <select id="mySelect">
      <option value="11">Apple</option>
      <option value="12">Orange</option>
      <option value="13">Pineapple</option>
      <option value="14">Banana</option>
    </select>
    <button type="button" id="btn">Display index</button>

the fiddle

Community
  • 1
  • 1
Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
1

Those methods dont live on the jQuery object, you can console.log the object and see what they inherit through their prototype chain.

From MDN:

Summary Returns a reference to the element by its ID.

Syntax element = document.getElementById(id); where

element is a reference to an Element object, or null if an element with the specified ID is not in the document.

The important part to take away is the reference to the Element object.

Here you can see the methods that are available from this object.

Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
1

$("...") returns a jQuery collection that contains the matched elements. You cannot access the elements and their properties directly, instead:

Use the jQuery.get accessor method:

var x = $("#mySelect").get(0).selectedIndex;
var y = $("#mySelect").get(0).options;

Dereference the element:

var x = $("#mySelect")[0].selectedIndex;
var y = $("#mySelect")[0].options;

Use jQuery.prop:

var x = $("#mySelect").prop("selectedIndex");
var y = $("#mySelect").prop("options");

Having said all that, you can change your code to this:

var $selectedOption = $("#mySelect option:selected");
console.log(
    $selectedOption.index(),
    $selectedOption.text(),
    $selectedOption.val()
);
Salman A
  • 262,204
  • 82
  • 430
  • 521
1

$() is a jQuery Object Constructor, it will make a jQuery object and wrap the selected elements inside this object (all DOM properties can still be accesed but not directly).

getElementById() is a native javascript function that retrieves the DOM element which has its normal properties.

You usually don't need to access the DOM element within the jQuery Object as you can use the jQuery methods living inside the Object that will manipulate the selected elements. It's a little bit tricky with selects as I don't see any methods just to retrieve the options list however:

$('#select option'); //Selects all the options of the select
$('#select option').each(function(){
  //iterate all options of the select.
});
$('#select option:selected'); //Get the selected option.

Would be fair equivalent. From then on you can use jQuery methods to manipulate the options, for example:

$('#select option:selected').text(); //Option text
$('#select option:selected').val(); //Value of option
MinusFour
  • 13,913
  • 3
  • 30
  • 39
1

$("#element"); is a jquery css-syntax-like DOM selector gathering all matching results in an array of jQuery objects which can access the full scale of jQuery functions which are very handy and easy to use out of the box.

while "doucment.getElementById("element);" is a native JavaScript function.

JQuery is an abstraction layer for JavaScript with an easier syntax, powerful tools/functions out of the box and is also fixing browser compatiblity issues for you.

Short to say it executes JavaScript for you in the background you do not have to bother with.

You should try to get used to code jQuery whenever possible as it makes your life easier and you dont have to bother with complex and tons of lins of code with only small effect such as for example: writing a AJAX request natively in JavaScript is like 15 more lins of code compared to jQuery with the total same effect.

Some examples that do exactly the same thing:

Access element

JavaScript:

alert(document.getElementById("element").name);

JQuery:

alert($("#element").attr("name"));

Loop elements

JavaScript:

var elements = document.getElementsByClassName("class");
for(var i = 0; i < elements.length; i++) {
    alert(var element = elements[i].name);
}

JQuery:

$(".class").each(function() { 
    alert($(this).attr("name")); //This accesses the current element of each function as a full useable and handy object
});

This are only two examples and you can see that it is indeed very powerful. Small code doing exactly the same as big code in plain JavaSCript. When you are including jQUery you should always try to use its full potential.

--

Your code in JQuery style:

<button id="btn_display_index" type="button">Display index</button>

<script type="text/javascript">
    //Will be executed any time the button with id "btn_display_index" is clicked!
    $("#btn_display_index").on("click", function() { 
        var currentOption = $("#mySelect option:selected");
        alert("Index: " + currentOption.attr("value") + " - Value: " + currentOption.html());
    });
</script>
Steini
  • 2,753
  • 15
  • 24
  • i tried your suggestion once on jsfiddle but i does'nt seems to be wrking.. it gives me undefied alert http://jsfiddle.net/wbo2nhsq/12/ – kki3908050 Nov 10 '14 at 18:22
  • I had a little syntax error in the alert. However i fixed your fiddle to work now jQuery style: http://jsfiddle.net/wbo2nhsq/13/ – Steini Nov 11 '14 at 06:24