0

I am trying to add a string to a string, but i can't seem to get it work.

Here is the code:

<input type="text" name="text" id="text">
<input type="button" id="button" value="Click">

And javascript

var htmlYes = false;
$("#text").keydown(function(){
    if(!htmlYes){
        var value = $("#text").val();
        value += ".html";
        $("#text").val(value);
        htmlYes = true;
    }
});
$("#button").click(function() {
    var fileName = $("#text").val();
    fileName = fileName.replace(".html", "")
    alert(fileName);
});

What i am trying to do is, when user starts typing the name of the file he want to export, i want that automaticly ".html" is attached to the end of string he is writing.

But whats happening, the .html is attached to the start. i tried concat(), but nothing seems to work. Any help?

So when i write test, it actually looks like .htmltest but i want to to look like test.html

user2945241
  • 360
  • 5
  • 19
  • is the htmlYes true in any moment? – QuarK Dec 17 '13 at 10:42
  • `keydown` or `keyup` won't work here. On either cases, the cursor will go to the end of the text being typed, so you would need to manage its position. Check this out: http://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox – emerson.marini Dec 17 '13 at 10:44

1 Answers1

0

First keydown is when useer starts typing

var value = $("#text").val(); //value is "" at firstkeydown

then you set the logic variable true so it never executes again

try bind to other events not keydown or see

    $("#button").click(function(){
    var value = $("#text").val();
    value += ".html";
    $("#text").val(value);
    var fileName = $("#text").val();
     alert(fileName);
    });

jsfiddle example

Chris
  • 195
  • 1
  • 13