views:

75

answers:

2

I have an input field which when the enter key is pressed (as there is no submit field) I would like javascript to add the @ character infront of each keyword when the form is submitted.

For example:

The text would be entered as...

home, personal, call

But the value that is submitted would be...

@home, @personal, @call

So far I have:

$("#inputfield").keydown(function(e){
    if (e.keyCode == 13) {
     $("#inputfield") // Not sure what to add next
     .submit();
    }
+2  A: 

This should do the trick:

$("#inputfield").keydown(function(e){
if (e.keyCode == 13) {
    $('#inputfield').val($('#inputfield').val().split(',').map(function(item) {
            return '@'+item;
         }).join(',')); 
    $(this).submit();
}
altCognito
Yours however is smaller and thought me about the map function (which I didn't know about). Thanks for that and the compliment.
Pim Jager
small nitpick, should split/join on ','
Chad Grant
@Deviant, no you shouldn't that will produce: @home,@ personal,@ call
Pim Jager
no, he's right, that's actually what he asked for :) -
altCognito
Ah ok, then I misread the question.
Pim Jager
Thanks guys both of these solutions work a treat.
Sevenupcan
+1  A: 

You would have to split the value of the field at spaces and then add an @ in front of each array value, then add that back as the value for the input. Also I recommend listening for the submit event of the form instead of the enter key in the input field.

 $('#form').submit( function() {
   var words = $('#inputfield').val().split(' ');
   var newwords = new Array();
   for(i=0, x=words.length; i<x; i++){
    newwords.push('@'+words[i]);
   }
   $('#inputfield').val( newwords.join(' ') );
   //we do not return false because we want the form to submit
 });
Pim Jager
Yours is much neater and easier to read :)
altCognito
+1 this is much better than toying around with keyup/keydown and keycodes.
Paolo Bergantino
Thanks for the tip about listening for the submit event rather than using the enter key.
Sevenupcan