Search code examples
htmlservicenow

How to stop refreshing the select box option after pressing OK button


I have created a UI Page in Servicenow below is my simple HTML snipped that creates a Select box and a OK button

Now i selected the select box as Mango and i typed ok, once i click on ok it is setting the value but when i refresh the browser it going to back to previous view. how to keep the same option which user select until user changes it

function validation(){
	var value=document.getElementById("selectedValue").value;
	
	if(value=='disabled selected')
		{
			alert("Please select any value before submitting");
		}
	else if(value=="1"){
				alert("hello this is mango");
	}
	
}
<div class="container">
			<div class="row">
				
				<div class="form-group" style="margin-top:12px;">
					
					<select class="form-control" name="selectedValue" id="selectedValue" style="width:150px;">
						<option value="disabled selected">Choose your option</option>
						<option value="1" >Mango</option>
						<option value="2">Orange</option> 
						<option value="3">Grapes</option> 
						
					</select>
				<!--<h4 id="number_of_updates" style="display:none"><span class="label label-danger"></span></h4> -->

				</div>
					<button type="button" class="btn btn-primary" onclick="validation()"  style="padding: 0px 8px;">Ok</button>
				
			</div>
		</div>

It is working as required, when i refresh the browser it will be set to Choose your option. Can anyone please help me how to save the selected value till it is changed


Solution

  • To achieve the desired result I would use localStorage. I would set localStorage item inside your validation() function:

    function validation(){
        var value=document.getElementById("selectedValue").value;
        localStorage.setItem('MyValue', value);
        if(value=='disabled selected')
            {
                alert("Please select any value before submitting");
            }
        else if(value=="1"){
                    alert("hello this is mango");
        }
    
    }
    

    Note, that I'm setting it to selected value from selectList. Then we need to retrieve this saved value on page load(in case someone refreshes the page):

    window.onload = function (){ //function that is called when your page 
    var selectList = document.getElementById('selectedValue');
      var stored = localStorage.getItem('MyValue');
      console.log(stored);
      if(stored && selectList){
        selectList.value = stored //setting saved value to as selected in selectList
      }
    }
    

    EDIT: Even though localStorage is supported by majority of browsers, its is recommended to check if its accessible. Like if (typeof localStorage !== 'undefined') ...