Pinch
Pinch

Reputation: 4207

Best reverse compatible approach to nullifying value in hidden field using JQuery

I would like to know the best reverse compatible approach to nullifying the value property in a hidden field using JQuery.

Thanks!

Note:

$('#MyHiddenField').val('');

is not good enough.

I need a good old fasioned null.

Upvotes: 0

Views: 78

Answers (1)

Fabrício Matté
Fabrício Matté

Reputation: 70149

You can't. The value property always holds a string. If you assign anything to it besides a string, it will be converted to a string.

That is because the HTMLInputElement interface's value property is of type DOMString. Independently of being a hidden input or not, the input element interface forces any value set to the input's value property to be of type string, otherwise it'd render input elements unusable to the end-user - this is the purpose of input elements after all. Also it'd be impossible to make a regular application/x-www-form-urlencoded request if the input values weren't strings.

You may be looking for something else than a hidden input, but what you can do without major changes in your code is simply checking if the value is an empty string before using it and assigning it to null:

var v = $('#MyHiddenField').val();
if (v === '') v = null;
//use v as null in your code now

And if you need it for posting to server-side, the operation is the same. Post it as an empty string then check if the posted data is an empty string and assign it to null.

Upvotes: 2

Related Questions