Get the value of an entry Select

5

I want to get the value of a select without having to choose an option and with this value fill an input, what I mean is that if the select comes with first option texto1 and value is 1 , that when doing the refresh I automatically fill in the input without having to choose another option of the select to load the value 1 of texto1 . I do not know if I can explain myself well, I publish my code: HTML:

 <select name="Proveedor" id="Proveedor" onchange="LLenarInput();"style="width:110px;height:20px;" required>
     <option value="1" >texto1</option>
     <option value="2" >texto2</option>
    </select>

<input type="text" id="proveedor2">

jquery

function LLenarInput() {
        var select = document.getElementById("Proveedor");
        document.getElementById("proveedor2").value = select.options[select.selectedIndex].value;
    }

Thank you very much!

    
asked by Nacho Carpintero 19.04.2018 в 14:07
source

1 answer

5

If I understand you correctly you just have to assign the value in $(document).ready()

$(document).ready(function(){

var select = document.getElementById("Proveedor");
        document.getElementById("proveedor2").value = select.value;
        
});

function LLenarInput() {
    var select = document.getElementById("Proveedor");
    document.getElementById("proveedor2").value = select.value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="Proveedor" id="Proveedor" style="width:110px;height:20px;" required>
     <option value="1" >texto1</option>
     <option value="2" >texto2</option>
    </select>

<input type="text" id="proveedor2">

Edito : Now that I have more time I put the solution to you using jQuery (that's why you have it:))

$(document).ready(function(){

   $("#Proveedor").on("change",function(){
     LLenarInput()
    });
   $("#proveedor2").val($("#Proveedor").val());            
});

function LLenarInput() {
    $("#proveedor2").val($("#Proveedor").val()); 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="Proveedor" id="Proveedor" onchange="LLenarInput();"style="width:110px;height:20px;" required>
     <option value="1" >texto1</option>
     <option value="2" >texto2</option>
    </select>

<input type="text" id="proveedor2">

Info

    
answered by 19.04.2018 / 14:13
source