开发者

Use JS to add characters into textfield

I want to add a $ symbol before a users entry into a text field without actually submitting the $ when the user clicks submit. Additionally, I need to prohibit the user from entering anything but numerical values in to the text input. I know about the JQuery input mask (http://www.conetrees.com/2009/03/blog/jquery-开发者_高级运维masked-input-plugin-increase-usability-for-masked-format-input-fields) but this plugin requires you to set the exact number of digits/letters that the user is supposed to enter, which is no good for my current project. Can anyone think of a way to accomplish what I have described above?


One way would be to grab everything except for the dollar from the input, and store it in a hidden field:

$("form").submit(function() {
    var total = $("#total").val();
    $("#hidden").val(total.replace("$", ""));
});

Here's a full working solution (bear in mind, it probably needs refinement before it meets the real world):

$("form").submit(function() {
    var total = $(".total").val();
    $("#hidden").val(total.replace("$", ""));
});
$("#total").keypress(function() {
    validateNumeric();
}).keyup(function() {

    // if the user has pressed backspace and removed the dollar, put it back
    if($(this).val() == null || $(this).val() == "") {
        $(this).val("$");
    }
});

function validateNumeric(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    if(key == 8) {
        return true;
    }
    key = String.fromCharCode( key );
    var regex = /[0-9]/;
    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        theEvent.preventDefault();
    }
}

Test markup:

<form>
    <input type="text" id="total" value="$"/>
    <input type="hidden" id="hidden"/>
    <input type="submit" value="Submit"/>
</form>


If the $ will always be there, how about putting it before the text field?

Personally I avoid inserting extraneous things (units, watermarks, whatnot) into the value of a text field like the plague. They always end up getting interpreted as actual content in ways they're not supposed to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜