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>
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');
For document.getElementById(“id”) vs $(“#id”) see this question
var x = $("#mySelect").selectedIndex;
var y = $("#mySelect").options;
selectedIndex and options are undefined. You should use .text() and .val()
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
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.
$() 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
$("...") 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()
);
$("#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>
Related
I’d like to add a button to certain text fields to allow for additional input methods. Since the button should be able to reference the text field it belongs to, I'm adding a parameter to the function call within the button’s onClick() handler, containing the ID of the text field.
At least, this is my plan. When I obtain the ID of the text field, and display it in an alert, it displays nicely. However, when I use the result of $(this).attr('id') as a function parameter, I'd expect a string to be given to the function (the id of the element). Instead some weird object is given.
How do I convert that object to a string? Or is there a conceptual flaw?
<form>
<input class="joeDateTime" type="text" name="n1" id="n1" value="2014-09-01 17:30:00">
</form>
<script>
function handleJoeDateTime(e)
{
alert('Edit '+e); // shows 'Edit [object HTMLInputElement]'
}
$(document).ready(function() {
$('.joeDateTime').each(function(){
var i = $(this).attr('id');
alert(i); // shows 'n1'
$('<button onclick="handleJoeDateTime(' + i + ');return false;">📅</button>').insertAfter($(this));
});
});
</script>
You are not passing i as a string value, you are passing it as an variable. In modern browsers the element's id are copied to properties of the window object(so you can access then as global variables).
So you need to enclose them using quotes to pass i as a string value
$('<button onclick="handleJoeDateTime(\'' + i + '\');return false;">📅</button>').insertAfter($(this));
Demo: Fiddle
Also Instead of using inlined event handlers, I would recommend using jQuery event handlres
$('.joeDateTime').each(function () {
var i = $(this).attr('id');
console.log(i); // shows 'n1'
$('<button />', {
text: '📅',
click: function () {
handleJoeDateTime(i);
return false;
}
}).insertAfter(this);
});
Demo: Fiddle
Your problem lies here:
$('<button onclick="handleJoeDateTime(' + i + ');return false;">📅</button>')
where this should be
$('<button onclick=\"handleJoeDateTime(\"' + i + '\");return false;\">📅</button>')
When you're passing an element to jQuery ( $ ), it becomes a jquery object.
It had been made to handle id, class, elements, not html chunks.
What you want is inserting a piece of concatenated elements as an html node.
so first concatenate your elements then append it with the jQuery's after() method.
(or create/append it with vanilia js var btn = document.createElement("BUTTON");)
var Button = '<button class=\"AltBut\" id=\"' + i + '\">📅</button>';
$(this).after(Button);
or ( for compacity )
$(this).after('<button class=\"AltBut\" id=\"' + i + '\">📅</button>');
In this exemple, I'm adding an id to each enabled buttons where I store your variable i
Then add a click listener to those buttons, avoid inline js at all price, for maintainability's sacke.
$('.AltBut').on('click',function(){
var i = $(this).attr("id");
alert("i= "+i);
return false;
})
The whole demo is here: http://jsfiddle.net/x6x4v90y/1/
Fiddle is here, containing this code: http://jsfiddle.net/enp2T/6/
<select id="aList">
<option value="0">0</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
</select>
<div id="newListContainer"></div>
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
var listHtml = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
I thought that my selected value of 300 would be maintained, but listHtml just contains a clone of the original list. I'm in a situation where it would be painful to try to re-find the object and set its value after it gets drawn (passing it to another external libraries function defers rendering till later, no complete callback unless I modify that library directly which I'm trying to avoid).
So am I doing something horribly wrong? Missing a quirk?
Clarification: I need to pass the HTML as a string, as the library that is using it is expecting a string.
There's no reason to make a round-trip to markup for this, and I suspect that's the problem, as jQuery's val sets the selectedIndex of the select element, which doesn't get serialized.
Just use the cloned element:
var wrappedList = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent();
// Note: Not doing `.html()` at the end
// html(...) would empty the container and then add the HTML, so
// we empty the container and then append the wrapped, cloned list
$('#newListContainer').empty().append(wrappedList);
Updated working fiddle
jQuery clones the list with whatever you have selected - the problem here is that you don't have anything selected, so you're cloning a dropdown without a selected value (see here).
For an updated version of that script, check this updated jsFiddle.
Code:
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
clonedList.find('option[value="' + value + '"]').attr('selected', 'selected');
var listHtml = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
See this link. You can't set value to the select, you must set selected attribute to item with value=300.
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
clonedList.find('option[value="' + value + '"]').attr("selected", true);
var listHtml = clonedList
.removeAttr('id')
//.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
I have a mistake. #T.J. Crowder is right. jQuery can set value of select by .val(value) function. link
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
var holderCloned = clonedList.removeAttr('id').val(value).wrap('<div/>').parent();
$('#newListContainer').empty().append(holderCloned);
});
I have written a code for dropdown selected index changed event at client side using onchange event and create one JavaScript function.
Now, I want to retrieve selected values in this function. How can I get this value?
$("#DropDownlist:selected").val();
This will give you selected text.
$("#mydropdownid option:selected").text();
This will give you selected value
$('#mydropdownid').val();
HTML :
<select id="mySelect" class="myClass">
<option value='1'>One</option>
</select>
jQuery :
Now for getting selected value you can use the one of the following:
ONE :
var selected_value = $("#mySelect").val();
TWO :
var selected_value = $(".myClass").val();
THREE :
var dropdown = $("#mySelect option:selected");
var selected_value = dropdown.val();
The simplest, inside the event handler:
$('#elementID').change(function(event) {
event.target.value;
};
event is the event object sent to the handler, target is the object in the DOM from which the event generated, and value it's the DOM element current value. In the case of a select box this will work perfectly to get your selected value.
As you have tagged jQuery, I assume that's what you are using.
Simply use jQuery val()
var v = $("#yourSelectID").val();
alert("The value is: " + v);
You should also be able to use plain javascript:
var e = document.getElementById("yourSelectID");
var v = e.options[e.selectedIndex].value;
alert("The value is: " + v);
I am a javascript noob.
I would like to select the second 'p' element of the div.box.
How do I do this?
Thanks a lot!
Tom
To get second p element of div with class box you'd do this:
var paragraph = null;
var divs = document.findElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
if (div.class == 'box') {
var paragraphs = div.getElementsByTagName('p');
if (paragraphs.length > 1)
paragraph = paragraphs[1];
break;
}
}
The paragraph would then be in the paragraph variable (or null if it wasn't found).
However you can do this much easier with a library such as jQuery:
var paragraph = $('div.box p:eq(1)');
Without using jQuery, the basic method would be to attach an unique ID to your Dom element
<p id="second_p_elmt"> [...] </p>
and then accessing it through the getElementById() method:
<script ...>
var second_p_elmt = document.getElementById('second_p_elmt');
</script>
<script type="text/javascript">
var boxElem = document.getElementById('box'),
pElems = boxElem.getElementsByTagName('p'),
whatYouWant = pElems[1]; // [1] is the second element in the response from getElementsByTagName
</script>
You have several options. As stated above, you could use one of the excellent frameworks, like jQuery or prototype. Or you give the <p/> an ID, that you can use simply with document.getElementById().
Then, as reko_t pointed out, without the above, you must write a lengthy DOM traversing code (which is preferable, if you don't use JS frameworks elsewhere, over embedding them only for this task).
In the most recent browsers (namely, IE>=8, FF>=3.5, recent Opera and Safari > 3) you can also use this simple snippet:
var p = document.querySelectorAll("div.box p");
Given the following HTML:
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
How do I grab the string "displayed text 1" using Javascript/the DOM?
var sel = document.getElementById("my_dropdown");
//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;
//or get the first option
var optionText = sel.options[0].text;
//or get the option with value="1"
for(var i=0; i<sel.options.length; i++){
if(sel.options[i].value == "1"){
var valueIsOneText = sel.options[i].text;
}
}
var mySelect = document.forms["my_form"].my_dropdown;
// or if you select has a id
var mySelect = document.getElementById("my_dropdown");
var text = mySelect.options[mySelect.selectedIndex].text;
Assuming you want the selected option's text:
var select = document.getElementById('my_dropdown');
for(var i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
break;
}
}
var selectText = select.options[i].text;
In Prototype:
var selectText = $$('#my_dropdown option[selected]')[0].text;
Edit: And jQuery for completeness' sake (assuming jQuery's CSS selector support is roughly equivalent to that of Prototype's):
var selectText = $('#my_dropdown option[selected]').get(0).text;
The displayed text is a child node of the option node. You can use:
myOptionNode.childNodes[0];
to access it, assuming the text node is the only thing inside the option (and not other tags).
EDIT: Oh yeah, as others mentioned, I completely forgot about:
myOptionNode.text;
Assuming you modified your code a bit to have an id / class on the and were using jQuery you could have something like the following. It will pop up an alert for each option with the text of the option. You probably won't want to alert for all the text, but it illustrates how to get at the text in the first place:
$('select#id option').each(function() {
alert($(this).text());
});
If you use a class instead of an id, then you'd just have to change the 'select#id' to 'select.class'. If you didn't want to add a class/id there are other ways to get at the select.
I leave figuring those ways out if you want to go that route as an activity for the reader.
If you were using Prototype, you could get at it like this:
$$('#my_dropdown option[value=1]').each( function(elem){
alert(elem.text);
});
The above is using a CSS selector that says find all option tags with value="1" that are inside the element that has id="my_dropdown".