Endrit
Endrit

Reputation: 1

When user inputs a number in a textbox will get an array element dynamically javascript or PHP

i have an array:

var array = ['Mon','Tue','Wen','Thur','Fri','Sat','Sun']; //JS

or i can get it like this:

$arr = array('Mon','Tue','Wen','Thur','Fri','Sat','Sun'); //PHP

i want to get "Mon" dynamically when a user inputs in a textbox num 1, 'Tue' when inputs num 2... JS or PHP whatever. please help.

Upvotes: 0

Views: 80

Answers (2)

ern
ern

Reputation: 71

If the goal is just get the value of index then return the related value to user I would use javascript..

<html> 
    <head> </head> 
    <script type="text/javascript">
    function myfunction() { 
       var array = ['Mon','Tue','Wen','Thur','Fri','Sat','Sun']; //JS
       var first =parseInt( document.getElementById("textbox1").value);//store user input for control

       //Control user input.
       if(first<1 || first > 7 ||!Number.isInteger(first) )
       {
           alert("Please enter a number between 1 and 7");

       }

       var textbox2 = document.getElementById('textbox2');//get textbox2
       //control if index is defined and assign it to textbox2.value
       if(array[first-1]){
            textbox2.value= array[first-1];

       }
       //if not assign empty string
       else{
            textbox2.value= "";
       }
     } 
    </script>
    <body> 
    <input type="text" name="textbox1" id="textbox1" /> 
    <input type="submit" name="button" id="button1" onclick="myfunction()" value="get" />
    <br/>

    <input type="text" name="textbox2" id="textbox2" readonly="true"/>
    </body>
 </html>

Upvotes: 0

mickadoo
mickadoo

Reputation: 3483

If you just want the value of the array at that index in PHP you can use the form:

$dayName = $arr[$number];

And similarly in javascript

var dayName = array[number];

You need to remember arrays start at index 0, and the user input might start at 1.

Upvotes: 0

Related Questions