Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Add http:// to text input if there is none

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #34629

    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

    #88455
    Mottie
    Member

    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);
    }
    }
    });

    #88459

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

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.