1

I found a code which allows me to re format the phone number in a form. It works great, I have to give the form input id for it recognize which field the script will be checking but the problem is every time i update the form the input id changes and I Cannot change the input id and make it static.

I was wondering if I could use the placeholder or data-label-inside or name instead of the ID.

Here is the snippet of the code which does refers to the input ID (the full formatting code is below)

const inputElement = document.getElementById('1d72b826f2fca893b7198aa3f208265f-3');
inputElement.addEventListener('keydown',enforceFormat);
inputElement.addEventListener('keyup',formatToPhone);

The form code looks like this

<input id="1d72b826f2fca893b7198aa3f208265f-3" name="UGhvbmUgTnVtYmVy" value="" placeholder="Phone Number" data-label-inside="Phone Number" class="shortnice form-input  required  shadow-inside  checknumericvalue  validatePhone" type="text">

Below is the whole code just in-case:

ijQuery(document).ready(function () {
  const isNumericInput = (event) => {
    const key = event.keyCode;
    var test = event.target.value.replace(/\D/g,'').substring(0,1);
    if(test.length <= 0){
        return ((key >= 50 && key <= 57) || // Allow number line
            (key >= 98 && key <= 105) // Allow number pad
        );
  }else{
        return ((key >= 48 && key <= 57) || // Allow number line
            (key >= 96 && key <= 105) // Allow number pad
        );
    }
};

const isModifierKey = (event) => {
    const key = event.keyCode;
    return (event.shiftKey === true || key === 35 || key === 36) || // Allow Shift, Home, End
        (key === 8 || key === 9 || key === 13 || key === 46) || // Allow Backspace, Tab, Enter, Delete
        (key > 36 && key < 41) || // Allow left, up, right, down
        (
            // Allow Ctrl/Command + A,C,V,X,Z
            (event.ctrlKey === true || event.metaKey === true) &&
            (key === 65 || key === 67 || key === 86 || key === 88 || key === 90)
        )
};

const enforceFormat = (event) => {
    // Input must be of a valid number format or a modifier key, and not longer than ten digits
    if(!isNumericInput(event) && !isModifierKey(event)){
        event.preventDefault();
    }
};

const formatToPhone = (event) => {
    if(isModifierKey(event)) {return;}

    // I am lazy and don't like to type things more than once
    const target = event.target;
    const input = event.target.value.replace(/\D/g,'').substring(0,10); // First ten digits of input only
    const zip = input.substring(0,3);
    const middle = input.substring(3,6);
    const last = input.substring(6,10);

    if(input.length > 6){target.value = `${zip}${middle}${last}`;}
    else if(input.length > 3){target.value = `${zip}${middle}`;}
    else if(input.length > 0){target.value = `${zip}`;}
};

const inputElement = document.getElementById('1d72b826f2fca893b7198aa3f208265f-3');
inputElement.addEventListener('keydown',enforceFormat);
inputElement.addEventListener('keyup',formatToPhone);
var fieldLabel = 'Phone Number';
    ijQuery.validator.addMethod('validatePhone', function (value, element) {
    if (value.length>=10) {
     return true;
       } else {
     return false;
       }
 });
 ijQuery('form [name="' + base64_encode(fieldLabel) + '"]').addClass('validatePhone');
 ijQuery.extend(ijQuery.validator.messages, {
 validatePhone: 'is invalid.'
});
});
  • Possible duplicate of [How can I select an element by name with jQuery?](https://stackoverflow.com/questions/1107220/how-can-i-select-an-element-by-name-with-jquery) – No Name Aug 15 '18 at 19:20
  • 2
    yes you can use attributes too to select element like in your case `document.querySelector('input[placeholder="Phone Number"]')` – MJN Aug 15 '18 at 19:24

4 Answers4

0

First we need to get the element with document.getElementById. Then we can access the value property of the input elemement and change this.

function change() {
document.getElementById('input').value = 'Other value';
}
<input id="input" value="heythere" /> 
<button onclick="change()">click me</button>
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
0

You can use give the input a specific class to select it by. To select elements by class, simply do this:

$('.nameofclass'); //jQuery)

or

document.querySelectorAll('.nameofclass'); //native Javascript

This way, you can check the values of multiple inputs instead of just one (by id).

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="myClass" type="text">
<script>
$('.myClass').val("--==SomeValue==--");
</script>

You can also select the element by its data-attribute data-label-inside:

$('[data-label-inside="Phone Number"]') //jQuery

or

document.querySelector('[data-label-inside="Phone Number"]')

<input data-label-inside="Phone Number" type="text">
<script>
document.querySelector('[data-label-inside="Phone Number"]').value = "!!!value!!!";
</script>

You can also select the element by its placeholder.

$('input[placeholder="Phone Number"]'); //jQuery

or

document.querySelector('input[placeholder="Phone Number"]');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Phone Number" type="text">
<script>
console.log($('input[placeholder="Phone Number"]').attr('type'));
</script>

You can select the input by its name in the same way as its placeholder and data-attributes.

$('input[name=nameofinput]'); 

or

document.querySelector('input[name=nameofinput]');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input" type="text">
<script>
$('input[name=input]').prop('value', "value");
$('input[name=input]').prop('disabled', true);
</script>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Use the jQuery [attribute=value] selector to find your input

Like this:

$('placeholder="Phone Number"')

or

$('data-label-inside="Phone Number"')

This will give you the input you're looking for.

Note: if there are multiple elements on the page with this attribute and value it will return all of them.

See this for more info on how this works and a working demo.

agDev
  • 855
  • 10
  • 20
-1

I think you are using jQuery.

So you could use a selector like $('[name="UGhvbmUgTnVtYmVy"]') or $('[data-label-inside="Phone Number"]') or $('[placeholder="Phone Number"]').

You could also add input before the brackets to only select input fields example $('input[name="UGhvbmUgTnVtYmVy"]').

Maybe you need to call it like that: jQuery('[name="UGhvbmUgTnVtYmVy"]').

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
kSp
  • 224
  • 2
  • 13