Search code examples
jqueryparseint

Set value if entered value is more than a {number}


I have a block, width and height of which I want user to set by entering a value in the input.

I also want the value of inputs not to be more than certain number. Seems like I can't get parseInt to work..

if (parseInt($("#stwidth").val(), 10) > 113) {
  $("#stwidth").val("113");
}

if (parseInt($("#stwidth").val(), 10) > 62) {
	$("#stheight").val("62");
  
}

$("#stwidth, #stheight").keyup(function () {
  $('.preview').css({width: $("#stwidth").val() + "mm", height: $("#stheight").val() + "mm"});
});
.preview {
    width: 55mm;
    height: 19mm;
    background: #fff;
    overflow: hidden;
    border: 2px solid #3e6eb0;
    margin: 50px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="stwidth" id="stwidth" value="55" maxlength="3"> x 
<input type="text" name="stheight" id="stheight"  value="19" maxlength="2"> 

<div class="preview"></div>


Solution

  • What you're missing was using Jquery keyup event handler on document onload for those user inputs. Here I'm giving a working solution, it'll not allow the width to be greater than 113 and height to be greater than 62:

    <html>
    
    <head>
        <style>
            .preview {
                width: 55mm;
                height: 19mm;
                background: #fff;
                overflow: hidden;
                border: 2px solid #3e6eb0;
                margin: 50px 0;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script>
            $(function() {
                $("#stwidth").keyup(function() {
                    if (parseInt($("#stwidth").val(), 10) > 113) {
                        $("#stwidth").val("113");
                    }
                });
    
                $("#stheight").keyup(function() {
                    if (parseInt($("#stheight").val(), 10) > 62) {
                        $("#stheight").val("62");
    
                    }
                });
    
                $("#stwidth, #stheight").keyup(function() {
                    $('.preview').css({
                        width: $("#stwidth").val() + "mm",
                        height: $("#stheight").val() + "mm"
                    });
                });
            });
        </script>
    </head>
    
    <body>
    </body>
    <input type="text" name="stwidth" id="stwidth" value="55" maxlength="3"> x
    <input type="text" name="stheight" id="stheight" value="19" maxlength="2">
    
    <div class="preview"></div>
    
    </html>