blubberbo blubberbo - 5 months ago 22
jQuery Question

jQuery select case inside set val function

I assume there is a way to make this code more concise but I am not sure how in jQuery:

$('#originTypeToggle').change(function () {
if ($(this).prop('checked')) { $('#OriginType').val('1') }
else { $('#OriginType').val('2') }
});


logically, what I am looking for is:

$('#OriginType').val() = $(this).prop('checked') ? '1' : '2'


Basically to reduce the redundancy of
$('#OriginType').val('1')
and
$('#OriginType').val('2')

Thanks!

Answer

Try this:

$('#OriginType').val($(this).is(':checked') ? "1":"2");

Or

$('#OriginType').val($(this).prop('checked') ? "1":"2");
Comments