Have an idea?

Visit Sawtooth Software Feedback to share your ideas on how we can improve our products.

HTML for Free Format qeustions

Hi Sawtoothers,

I am creating a free format question to gather user data at the start of my survey. I have successfully created the entry boxes and recorded the data.

I am having an issue getting the phone number entry to format properly. I would like the phone number to format automatically when it is typed by the user. I have researched html using masking and it hasn't worked. Does anyone have experience with this?

Thanks!
asked Oct 3, 2019 by nphilli12 (160 points)
I've seen mask libraries in JavaScript before, but before we go that route, I would recommend considering using "Phone Number" from the Community Question Library:

https://sawtoothsoftware.com/community-question-library/1750-phone-number

Would something like that satisfy your needs?
here is the code for my final product. To format the phone number using masking required java or CSS, which only appeared in the header and not where the actual question/variables were. Below is my code for gathering user info. My work around for the phone number issue was to set the max character length at 10 and include a formatting hint next to it. Hope this is helpful for someone.

<label>
  First name:<br>
  <input type="text" name="InfoGather_firstname"><br>
  Last name:<br>
  <input type="text" name="InfoGather_lastname"><br><br>
  
<label for="phone">Phone:</label>
    <input type="tel" id="phone" name="InfoGather_phone"  maxlength="10" >
    <small>Format: 1234567890</small><br><br>

<label>
  E-mail:
  <input type="email" name="InfoGather_email"><br><br>

   
<label>
  Birthday:
  <input type="date" name="InfoGather_birthday"><br>

1 Answer

+2 votes
 
Best answer
As per my understanding of the question, I would like to share two different solutions to this.

1. If you have already created an open-end box with the limitation of length. Paste following code in the footer to restrict only numeric entries -

<script>
 $("#phone").on("keypress keyup blur",function (event) {    
    $(this).val($(this).val().replace(/[^\d].+/, ""));
    if ((event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
});
</script>


2. If you want to separate boxes of STD code and number, create an open-end question and paste following code in footer -

 
<style>
#[% QuestionName() %] {
    display: none;
}

#[% QuestionName() %]_div .phoneInput {
    margin-left: 0px;
    margin-right: 0px;
}
</style>

<script>
$(document).ready(function(){
    // Parameters
    var phoneFormat = [
    
        [7, '5555555'],
        ' - ',
        [3, '555']
    ];
    
    // Append strings and inputs
    var phoneInputCount = 0;
    phoneFormat.forEach(function(elem){
        // String
        if (typeof elem === 'string') {
            $('#[% QuestionName() %]_div .question_body').append('<span>' + elem + '</span>');
        }
        
        // Input
        else {
            // Read param
            var min, max, placeholder;
            if (!Array.isArray(elem)) {
                min = elem;
                max = elem;
            }
            else {
                min = elem[0];
                max = (typeof elem[1] === 'number') ? elem[1] : min;
                placeholder = (typeof elem[1] === 'string') ? elem[1] : elem[2];
            }
            
            // Append input
            phoneInputCount++;
            placeholder = placeholder ? placeholder : '';
            var html = '<input type="text" class="phoneInput" data-order="' + phoneInputCount + '" data-min="' + min + '" maxlength="' + max + '" placeholder="' + placeholder + '"/>';
            $('#[% QuestionName() %]_div .question_body').append(html);
            $('#[% QuestionName() %]_div .phoneInput[data-order="' + phoneInputCount + '"]').css('width', Math.max(max, placeholder.length) * 10 + 'px');
        }
    });
    
    // Fill inputs
    var phoneNumberArr = SSI_GetValue('[% QuestionName() %]').split(' ');
    for (var i = 1; i <= phoneNumberArr.length; i++) {
        $('#[% QuestionName() %]_div .phoneInput[data-order="' + i + '"]').val(phoneNumberArr[i - 1]);
    }
    
    // Key up
    $('#[% QuestionName() %]_div .phoneInput').keyup(function(){
        // Numeric characters only
        var nonNumericMatch = $(this).val().match(/\D/g);
        if (nonNumericMatch) {
            var selectionStart = this.selectionStart;
            var selectionEnd = this.selectionEnd;
            var nonNumerics = nonNumericMatch.length;
            $(this).val($(this).val().replace(/\D/g, ''));
            this.setSelectionRange(selectionStart - nonNumerics, selectionEnd - nonNumerics);
        }
        
        // Switch focus automatically
        if ($(this).val().length == $(this).attr('maxlength')) {
            var order = Number($(this).data('order'));
            $('#[% QuestionName() %]_div .phoneInput[data-order="' + (order + 1) + '"]').focus();
        }
        
        // Update response
        var resp = $('#[% QuestionName() %]_div .phoneInput').map(function(){ return $(this).val(); }).get().join(' ');
        $('#[% QuestionName() %]').val(resp);
    });
})
</script>
answered Oct 14, 2019 by Vinay Agrawal Bronze (1,550 points)
selected Oct 14, 2019 by nphilli12
Thanks so much- this is super helpful. My only other question is where in this code does the variable name go, in order for the question to properly record the data when it is entered. Thanks!
Both of these code accomplishes formatting/validation of data being entered in the Open-End variable and nothing to do with data capturing. In the first solution '#phone' should be replaced with the id of the element.
Warning: This code broke on the mobile platform, but still works on the desktop platform
...