-3

In a set of options can I determine if the currently selected value is manually set vs defaulting using only javascript (I can't modify the html since I'm using build in framework functionality).

<select>
  <option value="a">A</option>
  <option value="b">B</option>
<select>

should be distinguishable from

<select>
    <option value="a" selected="selected">A</option>
    <option value="b">B</option>
<select>

Even though both will have A selected.

Javascript will run on page load. I need to tell if html was sent from server with selected and if not then set the selectedIndex = -1

18
  • Have you actually tried anything? The solution becomes quite obvious if you look into it.
    – Etheryte
    Jun 19, 2014 at 22:51
  • You could check to see if the attribute selected exists for that particular element in a for-each loop that loops on your select. You'll need to give it an ID though for that to work. Jun 19, 2014 at 22:52
  • @ScottMcGready How does that help? What if the user manually selects the default option? The attribute will exist.
    – Barmar
    Jun 19, 2014 at 22:53
  • @Baramar Perhaps then instead of defaulting to "a" it should have a "Please Select" option. Jun 19, 2014 at 22:53
  • He said he can't change the HTML
    – Barmar
    Jun 19, 2014 at 22:54

2 Answers 2

1

Using the onchange event we can just flag that the user has selected it.

var selection = document.getElementById('selection');

selection.onchange = function(){

  user_selected = true;

}

With some markup like this:

<select id="selection">
  <option value="a">A</option>
  <option value="b">B</option>
<select>

Here's a fiddle...

0

try working an if statement into this for your value to match the selection...also, there are super easy jquery options...if you can use jquery.

  
<script>  
var selectedOption = document.getElementsByTagName("select");  
if (!selectedOption.options[selectedOption.selectedIndex].defaultSelected) alert("select has changed");  
</script>  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.