Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính value của HTML DOM Input URL

Thuộc tính value của đối tượng Input URL (<input type="url">) trong HTML DOM trả về hoặc thiết lập giá trị chuỗi URL. Trình duyệt thường validate định dạng URL khi submit form.

Cú pháp

Lấy giá trị chuỗi

inputURLObject.value

Thiết lập giá trị chuỗi

inputURLObject.value = 'Chuỗi_URL'

Ví dụ minh họa

Form chuyển hướng: chọn Google hoặc Bing điền URL, nhấn "Go" để chuyển hướng (mô phỏng):

<!DOCTYPE html>
<html>
<head>
<title>Input URL value</title>
<style>
  form { width: 70%; margin: 0 auto; text-align: center; }
  * { padding: 2px; margin: 5px; }
  input[type="button"] { border-radius: 10px; }
</style>
</head>
<body>
<form>
  <fieldset>
    <legend>URL-value</legend>
    <label for="URLSelect">URL: <input type="url" id="URLSelect"> 
    <input type="button" onclick="chonURL('google')" value="Google"> 
    <input type="button" onclick="chonURL('bing')" value="Bing"><br> 
    <input type="button" onclick="chuyenHuong()" value="Go"> 
    </label> 
    <div id="divDisplay"></div> 
  </fieldset> 
</form> 
<script> 
  var divDisplay = document.getElementById("divDisplay"); 
  var inputURL = document.getElementById("URLSelect"); 
  function chonURL(userName) { 
    if(userName === 'google') 
      inputURL.value = 'https://www.google.com'; 
    else 
      inputURL.value = 'https://www.bing.com'; 
  } 
  function chuyenHuong() { 
    if(inputURL.value !== '') 
      divDisplay.textContent = 'Đang chuyển hướng đến ' + inputURL.value; 
    else 
      divDisplay.textContent = 'Nhập URL'; 
  } 
</script> 
</body> 
</html>

Kết quả

  • Nhấn Go khi ô trống: "Nhập URL".
  • Nhấn Bing: ô URL = https://www.bing.com.
  • Nhấn Go sau khi có URL: "Đang chuyển hướng đến https://www.bing.com".

Ưu điểm type="url": Trình duyệt hiển thị bàn phím có .com, / trên mobile, tự validate định dạng URL (phải có scheme http/https).