copenndthagen
copenndthagen

Reputation: 50752

Javascript set boolean value for dropdown

I have the below code to map "Active" as true and InActive as false

var statusJSON = {
  '- Select -' : '', 
  'Active' : true, 
  'Inactive': false
};
$.each(statusJSON, function(key, val){
  $statusFlag.append('<option value=' + val + '>' + key + '</option>');
});

Also I do the following on change of dropdown;

$("#statusFlag").change(function() {
  self.model.set({
    statusFlag: $('#statusFlag').val()
  });
});

Now the issue is when I submit the form, the value in statusFlag is submitted as string ("true" or "false"). How do I ensure that only boolean value is set for statusFlag?

Upvotes: 0

Views: 4677

Answers (2)

David
David

Reputation: 218877

Since the actual "value" of the element is a string, and .val() returns a string, to get a boolean you'll need to examine that string and return a boolean of your own. Something like that:

statusFlag: $('#statusFlag').val() == 'true'

This should set statusFlag to true if the strings match, false otherwise.

How do I ensure that only boolean value is set for statusFlag?

Define "ensure" in this case. The above example will always set statusFlag to a boolean value because a == comparison always results in a boolean value. However, other code elsewhere can set statusFlag to anything. JavaScript is dynamically typed, so there's no way to guarantee from the property itself that it will only ever be set to a specific type.

You could perhaps wrap the property in a closure (making it "private") and expose a custom setter function which would internally examine whatever gets passed to it and only ever set that value to a boolean. But that seems like overkill, especially since at that point it doesn't really matter what type it is since it's privately encapsulated anyway.

Upvotes: 1

Vivek Parekh
Vivek Parekh

Reputation: 1085

I am not sure if this works but give it try

$("#statusFlag").change(function() {
   self.model.set({
      statusFlag: $('#statusFlag').val().toLowerCase() == "true" ? true : false
   });
});

Upvotes: 1

Related Questions