根据前四个字符串输入字符更改图像

时间:2015-09-29 10:48:32

标签: javascript string forms input

我有一个NIB表单输入,它接收数字并删除空格。 我希望它在用户点击按钮后向我显示图像。此图像取决于前4个字符。

这是我的代码:

<h2>Nib Form:</h2>
    <form id="form-data">
        <input id="nib" type="text" onblur="this.value=removeSpaces(this.value);">
        <input type="button" value="Verificar NIB">
    </form>
    <img src="default.png" id="bankimage" style="margin-top:20px;">


    <!-- SCRIPTS -->
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        function removeSpaces(string) {
            return string.split(' ').join('');
        }
        $('#form-data').submit(function(ev) {
            ev.preventDefault();
            var verification = $('#nib').val().slice(0,3);

            switch (verification) {
                case "0035":
                document.getElementById("bankimage").src = img.src.replace("default.png", "cgd.png");
                break;

                case "0033":
                document.getElementById("bankimage").src = img.src.replace("default.png", "mbcp.png");
                break;

                case "0063":
                document.getElementById("bankimage").src = img.src.replace("default.png", "banif.png");
                break;

                case "0027":
                document.getElementById("bankimage").src = img.src.replace("default.png", "bpi.png");
                break;

                default:
                console.log("Não reconhecido.")
            }
        });
    </script>

1 个答案:

答案 0 :(得分:0)

我建议您在验证按钮中添加一个类,然后使用模糊和点击事件http://jsfiddle.net/vvy623L3/2/

<h2>Nib Form:</h2>
    <form id="form-data">
        <input id="nib" type="text">
        <input class="verify" type="button" value="Verificar NIB">
    </form>
    <img src="default.png" id="bankimage" style="margin-top:20px;">

然后:

   function removeSpaces(string) {
        return string.split(' ').join('');
     }
    $('#form-data #nib').unbind('blur').blur(function(){
        var v = $(this).val();
        $(this).val( removeSpaces(v) );
    });
    $('#form-data .verify').unbind('click').click(function(ev) {

        var verification = $('#nib').val().slice(0,4);

        switch (verification) {
            case "0035":
            document.getElementById("bankimage").src = "cgd.png";
            break;

            case "0033":
            document.getElementById("bankimage").src = "mbcp.png";
            break;

            case "0063":
            document.getElementById("bankimage").src = "banif.png";
            break;

            case "0027":
            document.getElementById("bankimage").src = "bpi.png";
            break;

            default:
            console.log("Não reconhecido.");
        }
    });