0

I have two input fields. First is a field where user writes in any text (ex. product name) and another one is the field called "Alias" of the product name, it is creadet automatically in real time when user writes the product name. it is done with javascript, so my question is how to add some javascript code in order to add some random code like (aSDAS55AD546) AT THE END OF EACH ALIAS.

Here is the code:

the input fields:

product name:

<input id="asd" onKeyUp="keypress()" name="editname_<? echo $languages[$i][0]; ?>[<? echo $key; ?>]" type="text" value="<? echo $item['name'][$languages[$i][0]];?>" />

Alias field:

<input name="editalias[<? echo $key; ?>]" id="sdf" onFocus="javascript:stripspaces(this)" readonly="readonly" type="text" value="<? echo $item['alias'];?>" />

and this is the javascript code:

<script type="text/javascript"> 

function keypress()
{ 
var txt=document.getElementById('asd').value;
str1 = " \",'!=:;\йцукенгшщзхъжэдлорпавыфячсмитьбюЙЦУКЕНГШЩЗХЪЭЖДЛОРПАВЫФЯЧСМИТЬБЮăîșțĂÎȘȚ"; 
str2 = "00000000icukengsszhijedlorpavifacsmitibuICUKENGSSZHIEJDLORPAVIFACSMITIBUaistAIST";
for(i=0; i<str1.length; i++) 
   { 
 txt = txt.replace(new RegExp(str1[i],"g"), str2[i]); 
} 

document.getElementById('sdf').value=txt;
} 
</script> 


<script type="text/javascript">
$().ready(function(){
    $("input#asd").keyup(removeextra).blur(removeextra);
});
function removeextra() {
    var initVal = $(this).val();
    outputVal = initVal.replace(/[^0-9a-zA-Zа-яА-Я\s'",!ăîșțĂÎȘȚ]/g,"");       
    if (initVal != outputVal) {
        $(this).val(outputVal);
    }
};
</script>

This javascript is saving me alot of time. My website is for Russia, and it also translates from russian to english letters.

So please how can i make a random code for alias?

Thanks in advance!

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
  • name field: – user1890185 Dec 11 '12 at 19:03
  • You should create an example on jsfiddle.net that demonstrates your problem. – jbabey Dec 11 '12 at 19:07
  • Should that code to be unique or simply random? If it is not necessary to have unique codes, just random, than take a look here: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript. Othwerise it is better to add it on server – Viktor S. Dec 11 '12 at 19:12

1 Answers1

0

The underscore library has a function for just this purpose. I highly recommend the library, but if you just want that one function's logic it's essentially just:

var idCounter = 0;
function uniqueId(prefix) {
    var id = idCounter++;
    return prefix ? prefix + id : id;
};

With that you can do:

var aliasOfFoo = uniqueId(originalFoo);

Now if you need for the suffix to be random things get a little trickier. Instead of having an idCounter, you'd need an idArray to store all the previously-generated random strings, and then inside uniqueId you'd want to keep generating random strings until you find one that's not in idArray.

machineghost
  • 33,529
  • 30
  • 159
  • 234