Javascript — Why does the getAttribute() function not work on certain attributes? - javascript

Why does the alert display the correct value (which is pl) when i use alert(el2.getAttribute("class"));but does not do so when I use alert(el2.getAttribute("value")); (which is supposed to be the value for each option such as sunny... etc).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Allowance updater example</title>
</head>
<body>
<label for="weather">Select the weather type today: </label>
<select id="weather">
<option value="" class = "pl">--Make a choice--</option>
<option value="sunny" class = "pl">Sunny</option>
<option value="rainy" class = "pl">Rainy</option>
<option value="snowing" class = "pl">Snowing</option>
<option value="overcast" class = "pl">Overcast</option>
</select>
<p></p>
<script>
var el = document.querySelector("select");
var el2 = document.querySelector("option");
el.addEventListener("click", x);
function x() {
alert(el2.getAttribute("value"));
alert(el2.getAttribute("class"));
}
</script>
</body>
</html>

which is supposed to be the value for each option such as sunny... etc
No. It is supposed to be the value attribute for the particular element that is stored in e2.
var el2 = document.querySelector("option");
… and that is the first option element in the document.
<option value="" class = "pl">
… which is an empty string.
If you want to get all the options then you need to get them all (querySelectorAll) and then loop over the resulting list of elements as if it were an array.

You can't like this?
<script>
var el = document.querySelector("select");
el.addEventListener("change", x);
function x() {
alert(el.value);
}
</script>

Related

JavaScript, how to grab the selected value from one list and simultaneously change in another list

I have 2 select lists. There is a check box that when it is clicked it needs to feed the selected value selected into the other list.
I am up to the stage where I have managed to alert back the selected value in the first select list, my question is how to get the value in the second select list when the checkbox is clicked:
Please check code below of how far I have got:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function displayResult() {
if(document.form1.billingtoo.checked == true) {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
alert(y[x].text);
}
}
</script>
</head>
<body>
<form name="form1">
Select your favorite fruit:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<br>
<input type="checkbox" name="billingtoo" onclick="displayResult()">
<br>
Select your favorite fruit 2:
<select id="mySelect2">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
</form>
</body>
</html>
thanks.
Just set the selected index of the other select element.
jsFiddle Example
if(document.form1.billingtoo.checked == true) {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
// Set selected index for mySelect2
document.getElementById("mySelect2").selectedIndex = x;
}
You could get and set the value property of the object, if you're worried about the order of options being different.
jsFiddle Example
if(document.form1.billingtoo.checked == true) {
var x = document.getElementById("mySelect").value;
var y = document.getElementById("mySelect").options;
document.getElementById("mySelect2").value = x;
}

JavaScript code for getting the selected value from a combo box

Can any one give me a sample code that gets the selected value from an existing combo box?
I have this code but its not doing anything:
function check ()
{
var e = document.getElementById("ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);​
heres a img of the code
and the code
<select id="ticket_category_clone" name="ticket[category]" hdpp="ticket_category">
<option value=""></option><option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Rede" selected="selected">Rede</option>
<option value="Pedidos">Pedidos</option>
<option value="Formação/Dúvida">Formação/Dúvida</option>
<option value="Outro">Outro</option><option value="#edit_categories#">Edit Categories...</option></select>
what i want its find a way to get the selected value fo that combobox
There is an unnecessary hashtag; change the code to this:
var e = document.getElementById("ticket_category_clone").value;
I use this
var e = document.getElementById('ticket_category_clone').value;
Notice that you don't need the '#' character in javascript.
function check () {
var str = document.getElementById('ticket_category_clone').value;
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);​
It probably is the # sign like tho others have mentioned because this appears to work just fine.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<select id="#ticket_category_clone">
<option value="hw">Hardware</option>
<option>fsdf</option>
<option>sfsd</option>
<option>sdfs</option>
</select>
<script type="text/javascript">
(function check() {
var e = document.getElementById("#ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str === "Hardware") {
alert('Hi');
}
})();
</script>
</body>

javascript with html select box

I have select box with default value,i want to retrieve default value and changed value using javascript,Below is my Html Select box:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST()">
<OPTION ID="1" VALUE="TEST1" SELECTED/>
<OPTION ID="2" VALUE="TEST2"/>
</SELECT>
Regards,
Raj
You can set custom attribute of the element in the onload event of the document:
window.onload = function() {
var oDDL = document.getElementById("TEST");
oDDL.setAttribute("default_value", oDDL.value);
};
Then to read it:
function Test() {
var oDDL = document.getElementById("TEST");
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Complete code and test case: http://jsfiddle.net/yahavbr/MbnH7/
Edit: to support more than one drop down, first pass reference in the onchange event like this:
<select id="TEST" name="TEST" onchange="Test(this);">
Then set the custom attribute in a loop:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("default_value", oDDL.value);
}
};
And the test function also need minor change as it's not getting the drop down as argument:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Updated test case: http://jsfiddle.net/yahavbr/MbnH7/1/
Edit II: to show the previously selected value some name changes are required, plus storing the value every time it's changing. The onload becomes this:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("previous_value", oDDL.value);
}
};
(Only change is the custom attribute name)
And the function becomes:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strPreviousValue = oDDL.getAttribute("previous_value");
alert("Previous value is: " + strPreviousValue + "\n Current value is: " + strCurrentValue);
oDDL.setAttribute("previous_value", strCurrentValue);
}
(Name change plus setting the custom attribute)
Updated and hopefully final test case: http://jsfiddle.net/yahavbr/MbnH7/4/
why not have the onfocus event (vs. onload) store the current value. one solution might be to do something like this:
$(t).data("prev",$(t).val())
and then have the onchange use that:
var oldVal = $(t).data("prev");
thus when someone clicks on, or tabs into, the ui element it stores the current state, and then can use that if there is a resulting change. also it would need to change the value if the change was accepted so that if focus was not changed (ie: they stayed in the pulldown and changed the value again) and they changed their mind and chose another option that the state was preserved.
many of the examples that i have seen of this store state in a that seemed to be vulnerable to change/events elsewhere.
HTML:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST(this)">
<OPTION ID="1" VALUE="TEST1" SELECTED>TEST 1</OPTION>
<OPTION ID="2" VALUE="TEST2">TEST 2</OPTION>
</SELECT>
javascript:
// store currently selected value
var previousValue = document.getElementById('TEST').value;
function TEST(e) {
alert('old value = ' + previousValue);
alert('new value = ' + e.value);
// store new value
previousValue = e.value;
}
example here
EDIT - I answered wrong before - Here's a sample HTML page that does it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>untitled</title>
<script type="text/javascript" language="javascript">
function showOptionValue(oSelect) {
var def;
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected){ //this option's defaultSelected property is set to true (from HTML: selected="selected")
def = oSelect[i].text; //or .value
}
var sel;
sel = oSelect[oSelect.selectedIndex].text;
alert (sel + ' : ' + def);
}
function resetSelect(oSelect) {
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected) //this option's defaultSelected property is set to true (from HTML: selected="selected")
oSelect.options[i].selected = true; //so, set its selected property to true, selecting it
showOptionValue(oSelect); //reset status
}
</script>
</head>
<body>
<form>
<!-- call handler function, pass Select object (represents drop-down list) -->
<SELECT NAME="cbo" onchange="showOptionValue(this)">
<OPTION VALUE="not_default">Not DEFAULT VALUE</OPTION>
<OPTION VALUE="1">Small</OPTION>
<!-- default value, preselected -->
<OPTION VALUE="2" selected="selected">Medium</OPTION>
<OPTION VALUE="3">Large</OPTION>
</SELECT>
<!-- call handler function, pass Select object using its name as a variable -->
<input type="button" value="Reset Drop-down" onclick="resetSelect(cbo)">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script type="text/javascript">
function fn(){
var select = document.getElementById("selectbox");
alert(select.options[select.selectedIndex].value)
}
</script>
</head>
<body>
<header style="margin-left: 50%;">Welcome</header>
<select id="selectbox">
<option value="number 01">Number 01</option>
<option value="number 01">Number 02</option>
<option value="number 01">Number 03</option>
<option value="number 01">Number 04</option>
</select>
<button style="margin-top:10px; margin-left:15px;" onclick="fn()">Click me</button>
</body>
</html>

How to make <option>s of <select> show or hide using JavaScript?

I want to make the options of < select > show or hide by program(JS),is it possible?
It is just like the interesting tags in the front page of StackOverFlow, when you type in some words, the drop list will expand and give you suggestions.
ps.I know StackOverFlow didn't use select in this case, anyway just take it as an example.
You add or remove items from the options collection of the select.
Here is an example that removes one item and adds another:
<html>
<head>
<title></title>
<script type="text/javascript">
function init() {
// get a reference to the element
var sel = document.getElementById('sel');
// remove an option
sel.options[2] = null;
// create a new option and add to the select
var opt = document.createElement('option');
opt.value = '5';
opt.text = 'five';
sel.options.add(opt);
}
</script>
</head>
<body onload="init();">
<form>
<select id="sel">
<option value="0">zero</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</form>
</body>
</html>
function getCatListdef(sel)
{
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'data.php?cat_code='+sel;
ajax[index].onCompletion = function(){ createCities(index) };
ajax[index].runAJAX();
}

Dynamic javascript select dropdown

This was interesting. In a select dropdown, trying not to use jQuery (with the exception of easing some of my pain on recreation), I ran into an issue that doesn't properly let any current browsers catch the proper selected option. Here is my code, for the page that recreates the issue (remember, no jQuery to necessarily solve issue, but more or less just telling me what I am doing wrong.
This one has me stumped.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
var options = new Array();
for ( var i = 0; i < 3; i++ ){
options.push(new Option("Option " + i, "Value" + i, false, false));
}
options[1].setAttribute("selected", "selected");
for ( var option in options ){
select_element.appendChild(options[option]);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
The html this creates is:
<select id="some-id" name="some-name">
<option value="Value0">Option 0</option>
<option value="Value1" selected="selected">Option 1</option>
<option value="Value2">Option 2</option>
</select>
But the anomaly here is that (in firefox at least), the selected option ends up being Option 0, which isn't the selected DOM element. In IE6, this select dropdown doesn't work at all.
There is an alternate method that does work, which includes piecing the options together manually, which works in all browsers that I have tested.
A small change made it work for me in Firefox:
...
//options[1].setAttribute("selected", "selected");
options[1].selected = true;
...
I'm manipulating the DOM element's attributes directly. Not sure why your method doesn't work. Maybe you should keep both lines so that the HTML generated has the selected = "selected" in it.
some old thread - however try something like this:
var idx=0;
while(obj.options[idx]) {
if(obj.options[idx].value==value) obj.options[idx].setAttribute('selected',true);
else obj.options[idx].removeAttribute('selected');
idx++;
}
Use selectedIndex to set the selected index of a select object.
options.selectedIndex = 1;
Here is the working code, which seems like more of a Hack!
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
for ( var i = 0; i < 3; i++ ){
var option_element = document.createElement('option');
option_element.setAttribute('value', "Value" + i);
option_element.appendChild( document.createTextNode( "Option " + i ) );
if (i == 1){
option_element.setAttribute("selected", "selected");
}
select_element.appendChild(option_element);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
options[1].setAttribute("selected", "selected");
is likely where your issue lies. The output you're getting is:
<option value="Value1" selected="selected">Option 1</option>
and the standard is:
<option value="Value1" selected>Option 1</option>
You may be able to do:
options[1].selected = true;

Categories

Resources