Question

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();
    }
Was it helpful?

Solution

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

OTHER TIPS

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top