Get Default Value From select field Javascript

自作多情 提交于 2020-01-11 09:42:11

问题


I have a select field that have have present options and I have a php script check a mysql database and add a select tag to the one currently being used.

I need to find a way to know if the user have changed the select field or not before submitting it.

var Access = document.forms[UIDF]["Access"].value;
var DAccess = document.forms[UIDF]["Access"].defaultIndex; <--- This is my problem. I just need to know how to get the selected option value as this keep changing with every user

<select name="Access">
  <option value="0" selected='selected'>Employee</option>
  <option value="1">Team Leader</option>
  <option value="2">Admin</option>
</select>

回答1:


The Option tag has a javascript attribute defaultSelected that's set to true if the option had a selected value on page load. Note that this is the option tag and not the select one, so you'll have to loop through the options and check for the attribute.

Something like

var DAccess;
var AccessSelect = document.forms[UIDF]["Access"];

for (var i = 0 ; i<AccessSelect.length ; i++)
{
    if (AccessSelect[i].defaultSelected)
        DAccess = AccessSelect[i].value;
}

Or, more to the point:

var AccessHasChanged = false;
var AccessSelect = document.forms[UIDF]["Access"];

for (var i = 0 ; i<AccessSelect.length ; i++)
{
    if (AccessSelect[i].defaultSelected && 
        AccessSelect.value != AccessSelect[i].value)
        AccessHasChanged = true;
}


来源:https://stackoverflow.com/questions/13215586/get-default-value-from-select-field-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!