0
function ValueLimit(min, max, mode){

        var v;
        if(mode === "h"){
            v = document.getElementById("weight_imp").value;

            if(v < min){document.getElementById("weight_imp").value = min;}
            if(v > max){document.getElementById("weight_imp").value = max;}
        }

        if(mode === "w"){
            v = document.getElementById("weight_imp").value;

            if(v < min){document.getElementById("weight_imp").value = min;}
            if(v > max){document.getElementById("weight_imp").value = max;}
        }
    }

I need to replace mode with an ID of an input element This should in turn make the code significantly smaller I cannot seem to find a way to pass it through It should be able to target any element on the page

1
  • 4
    I don't understand what your asking. Can you be more specific please? Commented Apr 12, 2017 at 17:51

1 Answer 1

2

I would suggest that you pass your function an actual element instead of a selector (which has the added benefit of not requiring every input to have an id). You can also make the implementation much shorter using Math.min and Math.max.

function clampValue (e, min, max){
  e.value = Math.min(max, Math.max(min, +e.value))
}

var input = document.getElementById('weight_imp')

function exampleUsage () {
  clampValue(input, 0, 100)
}
<input type="number" id="weight_imp">
<button onclick="exampleUsage()">Clamp [0, 100]</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.