Get value of <select> the modern way? - javascript

I was under the impression that in order to get the value from <select> you essentially had to do this:
var sel = document.getElementById("my-select");
var val = sel.options[sel.selectedIndex].value;
But I ran into some code today that simply does document.getElementById('my-select').value, which seems to work perfectly fine in Chrome and Firefox.
Has this changed recently, or has it always been this way? How far back is this supported?

mySelect.value is a W3C standard at least since October 1st, 1998. See the DOM Level 1 Specification. However, some IE browsers released after that date do not support it, including IE8 (I just tested it).
Edit: As #kennebec pointed out, the issue with IE8 is that it wont use the option's text when there is no value set. If all your options do have a value set, then myselect.value will work on IE8.

Related

HTML dropdown's custom attribute empty in chrome, works fine in IE

This is my code.
var arrSelectElements = document.getElementsByTagName( "SELECT" );
for (var i = 0; i < arrSelectElements.length; i++) {
alert(arrSelectElements[i].DataSource); //code to use datasource value
}
It simply gets a list of all select elements in aspx file, and finds out the datasource name. Here is the code that binds the dropdown in C# file.
ddlSubsidiary.Attributes.Add("DataSource", "Subsidiary");
ddlSubsidiary.Attributes.Add("DataMember", "DISubsidiary");
Now, this code in IE works perfect. alert returns the name properly. But in Chrome, it always returns undefined.
Is it by design or am I missing something here?
In order to get the attribute value with the DOM element property in Internet Explorer, you have to use IE8 or older, or to run in compatibility mode (equivalent to IE7). In these old versions, the custom attributes can be retrieved in client code using the expando property with the same name:
var dataSource = ctl.DataSource;
var dataMember = ctl.DataMember;
From what I have read, this technique worked only in Internet Explorer, not in other browsers (HTML Custom Attributes Not Working in Chrome).
Since version 9, it doesn't work in Internet Explorer either. The getAttribute method must be used to get the attribute value in client code:
var dataSource = ctl.getAttribute('DataSource');
var dataMember = ctl.getAttribute('DataMember');
It is hard to say why IE6+ browser returns undefined, but my guess is that the checking event gets executed before the assignment event actually occurred. Quirk mode only uses 1 thread for everything while newer browser uses separate thread for DOM manipulation and render.

Does $() work differently in Internet Explorer?

I am running the following JavaScript in both Firefox Developer Edition 38 and Internet Explorer 8 and 9.
console.log('+++++++++++++++++++++++++++++++');
console.log('jquery version = ' + $.fn.jquery);
var myHtmlString = "<!-- my comment -->" +
"<optgroup label='my label'>" +
"<option value='1'>option one</option>" +
"</optgroup>";
console.log($(myHtmlString));
console.log($(myHtmlString)[0]);
console.log($(myHtmlString)[1]);
console.log($(myHtmlString).length);
In Firefox, I get:
In IE, I get:
So, apparently in Firefox, an HTML comment is getting added in as an element of this object but in IE, it's not. Why is this behaving this way, is there a bug, or is there another way I should be creating this object?
NOTE: I tried $.parseHTML(myHtmlString) but it does the same thing.
UPDATE: This answer How does jQuery treat comment elements? provides a potential workaround.
So it depends on the browser you're using, but since you're passing in more than 1 simply tag, (as an example $('<div>example html creation</div>')) jQuery lets the browser handle the creation.
If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in.
jQuery documentation
Firefox for example is looking through each of your < > areas, and it finds 2. While IE doesn't care, and processes it all as 1 (hence the length 1).
Long story short, you're doing it fine. That's just internally how the browser is handling it, you don't have to worry about any of that!

How to make this code compatible with IE7?

This code works in all browsers except for older IE versions. It'll be accessed by users, some of whom are still using IE7. I'm not a coder and the author isn't available until next week so I'm at loss how to refactor it so that all browsers show only the options defined in chk.
for (var x=1;x<5;x++){
var st='select[name="Score_'+x+'e"] option';
$(st).each(function(){
var chk=',0,1,2,3,4,5,,,,,,--,';
var sn=','+$.trim(this.innerHTML)+',';
if (chk.indexOf(sn)==-1){$(this).hide();}
});
st='#tableScoringInfoBox'+x+' strong';
$(st).html('1-10 Ratings explained');
}
A quick fix would be to simply replace .hide() with .remove(), though there's no way of knowing without seeing more code if that will impact something else.

Firefox Javascript: Why does .all not work?

In IE, I can go like:
var x = document.getElementById("header");
alert(x.all[0].tagName);
If I try that in Firefox, I get the error "all is undefined".
What is the Firefox equivalent of IE's .all property?
.all is a Microsoft-specific extension to the DOM, and is not supported by any other browsers (except Opera, I believe, who simulate it in order to improve compatibility with sites written for IE).
You can use things like x.children and x.childNodes, or x.getElementById() and x.getElementsByTagName() to reference elements below the current one in the tree, depending on your usage. I suspect in this case x.children is what you're after.
all would be the name of an array. It is not a native javascript keyword.
You may want to look at childNodes instead.

Is Math.ceil() & Math.round() supported on IE8?

I have a Javascript function that calculates a value and re-inserts the value into a <td> while also injecting the value into a hidden <input>.
This is my function:
$("input[name^='policies']:checkbox").change(function() {
var el = $(this);
if (el.is(":checked")) {
no_policies++;
}
if (el.is(":not(:checked)")) {
no_policies--;
}
subscription = no_policies*policy_cost;
first_payment = Math.ceil(subscription+no_policies*(policy_cost/days_month)*days_left).toFixed(2);
alert(first_payment);
$("td#first_payment").text("R "+first_payment);
$("input#first_payment_txt").val(first_payment);
$("td#subscription").text("R "+subscription.toFixed(2));
});
Everything works on IE8 up until this statement:
first_payment = Math.ceil(subscription+no_policies*(policy_cost/days_month)*days_left).toFixed(2);
I suspect IE8 is having trouble with Math.ceil, is that true? Also, is there any other function/method I can use to circumvent this?
Thanks in advance.
Answer is yes to both your questions:
Math.ceil()
Math.round()
Supported in the following document
modes: Quirks, Internet Explorer 6
standards, Internet Explorer 7
standards, Internet Explorer 8
standards, Internet Explorer 9
standards.
See also general table of Javascript compatibility for different IE versions:
Seems like microsoft supports Math.ceil on all versions beginning from ie6 (msdn), maybe one of the variables use is undefined or you devide by 0 or one of the variables is not a number so the result cannot be ceiled/rounded.
IE8 actually has a fairly good debugger. I recommend hitting F12 to open it, then going to the Script tab and selecting the Start Debugging button. This will let you set breakpoints along the script, letting it stop and wait for you to analyze variables as it executes at your own pace. As Adriano mentions in his comment, it's most likely an issue with one of your variables.

Categories

Resources