redirect knockout js observable if containing string

I have a input field in my html which basically sends the amount to an observable and then redirects to different pages depending on the amount, but I want to make sure that even if a person who doesnt write amount and types in "string values" should still be able to get redirected, but I am not sure how to accomplish that.

HTML CODE

<input id="amount"  type="text" data-bind="value : amount" />
<button class="btn button2" type="submit"  data-bind=" valueUpdate:'afterkeydown' , click: $root.borrow_first_pageview" ></button>

I do not want to write the type= number in the HTML since I want to know how its checked in the JS.

here is the rest code using knockout.js

self.borrow_first_pageview = function () {
        if(self.amount()){
            window.location.href = BASEURL + "index.php/moneyexchange/borrow_first_page/" + self.amount(); 
        }else if(typeof self.amount() == 'string'){
            window.location.href = BASEURL + "index.php/moneyexchange/borrow_first_page/" + 2500;
        }else {
             window.location.href = BASEURL + "index.php/moneyexchange/borrow_first_page/" + 2500;
        }

    };

Is there a way to check if self.amount() is a String and then redirect the user. Need help.


So we can reverse the problem and see if the amount is a number or not and then act accordingly:

var value = self.amount();
if((+value == value) && !isNaN(+value)){
    //Yey we have a valid number.
}

This is probably one of the few valid uses of a loose equality operator I have found (it guards against null and "" being passed in). It uses the unary plus operator plus a little bit of magic and it's a nice short way of checking if a value is a number or not.

You can put this into a function if you like, 'IsNumber' for example:

function isNumber(value){
    //loose equality operator used to guard against nulls, undefined and empty string
    return ((+value == value) && !isNaN(+value));
}
链接地址: http://www.djcxy.com/p/94990.html

上一篇: 只允许某些类型的属性

下一篇: 如果包含字符串,则重定向knockout js可观察