erol_smsr erol_smsr - 2 months ago 8
jQuery Question

Javascript input.value not working

I'm using the Domready.js library as an alternative to the jQuery

document.ready()
function and inside the ready function I have this code:

DomReady.ready( function() {

/*
DOM elements
*/
var tel_input = document.getElementsByClassName( 'tel-input' );

/*
When .tel-input is focused, `06` should be added automatically
*/
tel_input.onfocus = function() {
tel_input.value = '06';
};

});


This code doesn't do anything and the console doesn't throw an error. When putting an alert in the
tel_input.onfocus = function() {
it works, but inserting a value when the input is focused doesn't do anything.

Answer

As @Frédéric Hamidi said in the comment - getElementsByClassName return a list of DOM elements.

You only have one element but you still have to get the first element of the list

$( function() {

    /*
        DOM elements
    */ 
    var tel_input = document.getElementsByClassName( 'tel-input' );
    /*
        When .tel-input is focused, `06` should be added automatically
    */
    tel_input[0].onfocus = function() {
        tel_input[0].value = '06';
    };

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="tel-input" />