Trying to get updated text based on user selection

I am trying to get the selected text when a user selects a record from the dropdown menu. My JS code is as follows:

$(function(){
	
		
	$.ajax({
	    url : 'https://someurl/getEmployeeSets?user_name=JACK',
	    type : 'GET',
 
	    dataType:'json',
	    success : function(data) {              
	      	       
	            $.each(data.empSetsList, function (i) { 
	            $("#empSets").append('<option><a href="#" >'+data.empSetsList[i].description+' | '+data.empSetsList[i].resultInstanceID+' | '+moment(data.empSetsList[i].queryStartDate).format('MM/DD/YYYY')+'</a></option>');
	          	  
	            
	            }); 
	            
	            
	     },
	    error : function(request,error)
	    {
	        alert("Request Failed inside Js file: "+JSON.stringify(request));
	    }
	});
	
	//To test the item selected
	//alert("Selected Value by the user"+$("#empSets").val());
	alert("Selected Value by the user"+$("#empSets option:selected").text());
   
})

My HTML has the following:

<div class="dropdown ">
               
				<p><label class="custom-select">
					    Select your employee sets:
					    <select id = "emptSets">
					       <option>---------------------------------------Click here to select---------------------------------</option>
					    </select>
					</label></p>
				</div>

What I want:

Whenever a user selects an item from the list, I want the text related to data.patientSetsList[i].resultInstanceID so that I can store it into sessionStorage. Similarly, if auser selects something different, I would like to get the value of data.patientSetsList[i].resultInstanceID related to that selection so that I can update the session storage value.

I tried using the two selects as shown in the alert window above but it displays ---------------------------------------Click here to select--------------------------------- which makes sense as it’s the first text value. But how can I keep displaying the updated text value when a user selects something else? Thanks

You really think it’s a good idea to put that kind data into sessions?

What would be an alternate approach? The reason I am thinking to do is that there is another react application which is independent of above one , where I plan to use those session variables.

I think what Pepster is referring to is that ‘patientSetsList’ sounds like HIPAA (and probably GDPR) violating information, and needs to be highly controlled.

Be extremely careful about transmitting private information from a server to a client, especially when it comes to storing said private information at the client end.

Instead of just appending a…very interestingly constructed option tag, save the result into a variable that exists outside the ajax context, and then you can reference it in the code.

var mydata = {}
...
$.each(data.empSetsList, function (i,e) { 
  $("#empsets").append("<option value='"+e.resultInstanceID+"'>"+e.description+"</option>");
  mydata[e.resultInstanceID] = e;
}
.....
//User selects option....
$('#empsets').on('change', function(e) { 
   let dobject = mydata[$(this).val()];
   ......
});

Thanks. I double checked and what I’m planning to store is not a sensitive information. Thanks for bringing this up though!

Thanks. I came up something like this. This works as well. Please take a look and let me know if yours option is better or mine is okay as well:

$("select#empSets").change(function(){
		var selectedText = $(this).find("option:selected").text();
		console.log("Selected Text");
		console.log(selectedText);
		
		let splitText = selectedText.split('|');
		console.log(splitText[1]);
		sessionStorage.setItem("resultInstanceID",splitText[1]);
		console.log("Stored ResultInstance ID in Session Storage");
		console.log(sessionStorage.getItem("resultInstanceID"))
	 })

In addition to above I have one more question. Let’s say if a user doesn’t selects anything, then change event won’t get fired. But I want them to select atleast one thing. Basically, I want the change event to get fired. Is it possible to add validation for such scenario? Thanks

This is why we name functions. For example with the above code, here’s the function expression commented out, and replaced with a named function.

// $("select#empSets").change(function() {
$("select#empSets").change(function storeSelectedTextInSession() {
    ...
});

We can then move that function out, so that it can be called both from the change event, and separately too.

function storeSelectedTextInSession() {
    ...
}
// use function with change event
$("select#empSets").change(storeSelectedTextInSession);

// and can also call the function separately
storeSelectedTextInSession();

Er… well, that’s… one way to do it, I suppose.

Paul’s suggestion doesn’t quite read the same as what you said; namely that calling the function outside of a user flow means that you’re not saying “The user selected at least once”, you’re saying “Assume a default answer”.

You could call the function at the end of your AJAX filling, and that would achieve the result.

If however you actually want to force the user to change the dropdown, first you’d have to have an ‘empty’ option. (Otherwise, how can you know if the user has changed anything, rather than choosing the first option in the list?). The second thing about this option comes as an incomplete thought to your statement:

To wit the missing thought is “… by when?”

Thanks Paul. I’m trying to understand your changes. So is the following is what you are trying to refer?

$(function(){
	
function storeSelectedTextInSession() {
    ...
}
		
	$.ajax({
	    url : 'https://someurl/getEmployeeSets?user_name=JACK',
	    type : 'GET',
 
	    dataType:'json',
	    success : function(data) {              
	      	       
	            $.each(data.empSetsList, function (i) { 
	            $("#empSets").append('<option><a href="#" >'+data.empSetsList[i].description+' | '+data.empSetsList[i].resultInstanceID+' | '+moment(data.empSetsList[i].queryStartDate).format('MM/DD/YYYY')+'</a></option>');
	          	  
	            
	            }); 
	            
	            
	     },
	    error : function(request,error)
	    {
	        alert("Request Failed inside Js file: "+JSON.stringify(request));
	    }

$("select#empSets").change(storeSelectedTextInSession);

	});

I’m still not very clear on how it is going to have the user select at least one thing from the drop down and not the default one. Maybe I didn’t understand this part properly. Please elaborate. Thanks !

When you said that you want the change event to be fired, is that even when nobody selects anything?

Are you instead wanting to enforce a restriction, where the user is not allowed to submit anything unless they have selected at least one item?

I think it would make more sense to display user some notification when they hit submit button without selecting anything.

Yes, this is what I’m looking for as well.

That is most easily achieved by adding required to the HTML element, so that the form is not allowed to submit while the required field is empty. It also gives a suitable error message too.

No JavaScript is needed for that at all.

Here’s a simple example:

<form>
    <select required>
      <option value="">Please choose</option>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
      <option value="option3">Option 3</option>
    </select>
  <p><input type="submit"></p>
</form>

And here’s some css that helps provide color-hints about whether it is valid or not too.

select:valid {
  background: lightgreen;
}

You can see it in action at https://jsfiddle.net/pmw57/2dwvx48k/7/

1 Like

Hmm, thanks !

Adding form in my case might be difficult I guess as I’m dynamically generating option tags and storing the selected value data.empSetsList[i].resultInstanceID in sessionStorage.

The other thing I have done is to make sure I get some value of data.empSetsList[i].resultInstanceID from session storage. If this is null, I don’t allow them to submit and throw an error.