How do I programmatically set the value of a select box element using JavaScript?

后端 未结 17 1900
轮回少年
轮回少年 2020-11-22 06:33

I have the following HTML

17条回答
  •  不知归路
    2020-11-22 06:46

    If you are using jQuery you can also do this:

    $('#leaveCode').val('14');
    

    This will select the with the value of 14.


    With plain Javascript, this can also be achieved with two Document methods:

    • With document.querySelector, you can select an element based on a CSS selector:

      document.querySelector('#leaveCode').value = '14'
      
    • Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:

      document.getElementById('leaveCode').value = '14'
      

    You can run the below code snipped to see these methods and the jQuery function in action:

    const jQueryFunction = () => {
      
      $('#leaveCode').val('14'); 
      
    }
    
    const querySelectorFunction = () => {
      
      document.querySelector('#leaveCode').value = '14' 
      
    }
    
    const getElementByIdFunction = () => {
      
      document.getElementById('leaveCode').value='14' 
      
    }
    input {
      display:block;
      margin: 10px;
      padding: 10px
    }
    
    
    
    
    
    
    

提交回复
热议问题