0

While this is not a perfect solution for creating a unique id, using a date stamp will meet my needs for referencing form submissions sent via email without the need for a database. The odds of two people submitting a form at the exact same millisecond are far fetched and if it did happen I can differentiate between the two based on the individual emails. Using a GUID approach is a bit over kill for my needs(long number).

FYI - I split the datestamp with hyphons and reversed it for easier lookup.

So here is my jquery code using three textboxes. I want to consolidate the code so I only need to use one textbox. I have not been successful in example 2. Any tips/suggestions on how to do this would be appreciated.

EXAMPLE 1 - works

<script>
$(document).ready(function(){
    var ms = +new Date;
    $('#test').val(ms);
    var ms2 = $('#test').val();
    $('#test2').val(ms2.match(new RegExp('.{1,4}', 'g')).join("-"));
    var ms3 = $('#test2').val().split('').reverse().join('');
    $('#test3').val(ms3);
});
</script>


<input id="test" name="test" type="text">
<input id="test2" name="test2" type="text">
<input id="test3" name="test3" type="text">

EXAMPLE 2 - does not work

<script>
$(document).ready(function(){
    var ms = +new Date;
    var ms2 = $(ms).text.match(new RegExp('.{1,4}', 'g')).join("-"));
    var ms3 = $(ms2).text.split('').reverse().join('');
    $('#test4').val(ms3);
});
</script>
<input id="test4" name="test4" type="text">
Cliff T
  • 227
  • 2
  • 11

1 Answers1

1

The issue is that the match function is a string function, but you've cast the ms variable as a number.

Here's the revised code, which works, as well as a Working Fiddle

// shorter, conflict-safer document ready function
jQuery(function($) {
    // String operations (match) need the variable to be a string
    // Cast ms as a string 
    var ms = '' + +new Date;
    ms = ms.match(new RegExp('.{1,4}', 'g')).join("-").split('').reverse().join('');
    $('#test').val(ms);
});
random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • I was unaware that you have to treat a string differently even though the result of a string is a number. Still learning. Thanks for the help. – Cliff T Feb 25 '16 at 15:48
  • I think I get it. The match is no longer a number with hyphons. Thanks again. – Cliff T Feb 25 '16 at 16:20