Reputation: 23
My code is programmed to set width and height on a div. The thing is, it runs ok unless you set for example 375 x 80. I take a while to figure out why and i discover that the first number 375, if you take the first two numbers 37 and you set the height a number between 37 and 99 it not work. Can anyone explain why ?
https://jsfiddle.net/1erugkgz/
<script type="text/javascript">
$(document).ready(function(){
$(".custom-form").keyup(function(e){
if(e.keyCode == 13) {
var n1 = $('#n1').val();
var n2 = $('#n2').val();
$('.rotate').width(n1);
$('.rotate').height(n2);
}
});
$('.icon').click( function() {
var n1 = $('#n1').val();
var n2 = $('#n2').val();
if (n1 != '' && n2 != '') {
if (n1 > n2 ) {
if ($('.rotate').height() < $('.rotate').width()) {
$('.rotate').width(n2);
$('.rotate').height(n1);
} else {
$('.rotate').width(n1);
$('.rotate').height(n2);
}
}
if (n2 > n1) {
if ($('.rotate').height() > $('.rotate').width()) {
$('.rotate').width(n2);
$('.rotate').height(n1);
} else {
$('.rotate').width(n1);
$('.rotate').height(n2);
}
}
}
});
});
</script>
<div class="icon" style="background: grey;">ROTATE</div>
<form class="custom-form">
<input type="text" name="n1" id="n1"> x
<input type="text" name="n2" id="n2">
</form>
<div class="rotate" style="background: #000;width: 100px;height: 300px;"></div>
Upvotes: 0
Views: 53
Reputation: 1829
The problem is you're retrieving a value from an HTML input
of type "text", which will always return as a String. As a result, the comparison of '375' to '99' finds 99 to be pseudo-larger because it comes after '375' assuming those are Strings.
Instead, if you're expecting only numbers to be keyed into your inputs (and make sure you validate for that if so) then you need to use parseInt to cast the String values to integers:
var n1 = parseInt($('#n1').val());
var n2 = parseInt($('#n2').val());
Forked your jsFiddle with a working implementation here: https://jsfiddle.net/Ldf6g4qh/4/
Upvotes: 4