Js gets the Option selected by default in select that is not the current selected value

  • 2020-03-30 02:50:32
  • OfStack

Js function method:
 
<script> 
function getDefaultSelectedOption(selectId, valIfNull) { 
var dom, selectId = selectId.replace(/^#/, ''), opts; 
try { 
opts = document.getElementById(selectId).getElementsByTagName('option'); 
for (var i in opts) { 
if (opts[i].defaultSelected) { 
dom = opts[i]; 
break; 
} 
} 
} catch (e) { 
} 
return dom||valIfNull; 
} 
</script> 

The Demo:
 
<body> 
<select id="sel"> 
<option value="1">1</option> 
<option value="2" selected="">2</option> 
<option value="3">3</option> 
</select> 
<button id="btn">test</button> 
<script> 
function getDefaultSelectedOption(selectId, valIfNull) { 
var dom, selectId = selectId.replace(/^#/, ''), opts; 
try { 
opts = document.getElementById(selectId).getElementsByTagName('option'); 
for (var i in opts) { 
if (opts[i].defaultSelected) { 
dom = opts[i]; 
break; 
} 
} 
} catch (e) { 
} 
return dom||valIfNull; 
} 
</script> 
<script> 
document.getElementById('btn').onclick = function () { 
alert((getDefaultSelectedOption('sel1', {})).value); 
}; 
</script> 
</body> 

I don't know if there is a more convenient and quick way, but I tried to get $('#sel option[defaultSelected]') through jQuery, but it always returns nothing.

Friends, I want the value of the select control initialization, not the current selected value of the select, the value of the initialization does not change with the select value, you can do a Demo, when the select value changes, the value of the initialization is not changed.

Related articles: