Grow your CSS skills. Land your dream job.

Add http:// to text input if there is none

  • # October 4, 2011 at 9:30 am

    Hello i have a text input that need an url as value (complete of http://)
    and i want that if the user don’t writes it himself if gets added automatically…

    I came up with this code (jQuery)

    $('.textin').keypress(function(e) {
    if(e.keyCode == 13) {
    var ini = $(this).val().substring(0,3);
    if (ini === 'http'){
    $.noop()
    }
    else {
    cur_val = $(this).val(); // grab what's in the field
    // do stuff with cur_val so that it's what you want
    $(this).val('http://' + cur_val);
    }

    }
    });

    Somehow the function gets executed even if ini is = to http any help would be appreciated, thanks

    # October 4, 2011 at 9:38 am

    The problem is that the substring is only getting the first three letters “htt” and it’s being compared to “http” – here is a demo.

    Also there is no need for the “$.noop()” function:

    $('.textin').keypress(function(e) {
    if (e.keyCode == 13) {
    var ini = $(this).val().substring(0, 4);
    if (ini !== 'http') {
    cur_val = $(this).val(); // grab what's in the field
    // do stuff with cur_val so that it's what you want
    $(this).val('http://' + cur_val);
    }
    }
    });

    # October 4, 2011 at 9:54 am

    Thanks i tought that 0 was corrisponding to the first letter.
    DERP!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".