javascript - JQuery Variables for Arithmetic being treated as strings -
this question has answer here:
i trying month 3 months selected month using html select box , jquery in below code. code not adding 2 variables instead treating them 2 strings. assist me right?
<body> <form role="form" class="form-inline"> <div class="form-group"> <label class="control-label" for="q1month"> quarter 1 month </label> <select class="form-control" id="q1month"> <option selected value=''>--select month--</option> <option value='1'>january</option> <option value='2'>february</option> <option value='3'>march</option> <option value='4'>april</option> <option value='5'>may</option> <option value='6'>june</option> <option value='7'>july</option> <option value='8'>august</option> <option value='9'>september</option> <option value='10'>october</option> <option value='11'>november</option> <option value='12'>december</option> </select> </div> </form> <script src="js/jquery.js"></script> <script> $(function() { $('#q1month').change(function() { var month = $(this).val(); $('#q2month').val(month); var advanceby = 3; var newmonth = month + advanceby; window.alert(newmonth); }); }); </script> </body>
when value read dom, string. convert number can use unary +
operator.
add +
in front of value
var month = +$(this).val();
+
concatenation operator in javascript, when 1 of operand string +
used string concatenation.
$(function() { $('#q1month').change( function() { var month = $(this).val(); $('#q2month').val(month); var advanceby = 3; var newmonth = month + advanceby; window.alert(newmonth); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <form role="form" class="form-inline"> <div class="form-group"> <label class="control-label" for="q1month"> quarter 1 month </label> <select class="form-control" id="q1month"> <option selected value=''>--select month--</option> <option value='1'>january</option> <option value='2'>february</option> <option value='3'>march</option> <option value='4'>april</option> <option value='5'>may</option> <option value='6'>june</option> <option value='7'>july</option> <option value='8'>august</option> <option value='9'>september</option> <option value='10'>october</option> <option value='11'>november</option> <option value='12'>december</option> </select> </div> </form>
Comments
Post a Comment