通过网址预填充表单无效

时间:2016-07-17 05:40:55

标签: html forms url auto-populate

您好我尝试使用此功能自动填充 http://www.justsnaps.in/test?option=2  但它不起作用。

表单的HTML

<select name="option" onchange="document.getElementById('youriframe').src = this.options[this.selectedIndex].value">
    <option>choice</option>
    <option value="http://thumbnails116.imagebam.com/49530/fb7601495291146.jpg" 
value="1">Image 1</option>
    <option value="http://thumbnails116.imagebam.com/49529/cbe8b5495287000.jpg" value="2">Image 2</option>
    <option value="http://thumbnails115.imagebam.com/49530/50d2e2495291163.jpg" value="3">Image 3</option>
</select>

<img id="youriframe" class="form-image" src="choise" alt="" border="0" />

请发布正确的网址以实现此目的。

1 个答案:

答案 0 :(得分:0)

请注意我从内联中删除了onchange并将其添加到脚本中。如果传递了选项

,我也会触发onchange

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}
window.onload = function() { // when page loads
  var imgSel = document.getElementById("imgSel");
  imgSel.onchange = function() { // when changing
    var val = this.value; // get the value
    if (val) document.getElementById('yourImage').src = val;
  }

  var opt = getParameterByName("option"); // get the option from url
  if (opt) { // change options and trigger
    imgSel.selectedIndex = opt; 
    imgSel.onchange();
  }
}
<select name="option" id="imgSel">
  <option>choice</option>
  <option value="http://thumbnails116.imagebam.com/49530/fb7601495291146.jpg" value="1">Image 1</option>
  <option value="http://thumbnails116.imagebam.com/49529/cbe8b5495287000.jpg" value="2">Image 2</option>
  <option value="http://thumbnails115.imagebam.com/49530/50d2e2495291163.jpg" value="3">Image 3</option>
</select>

<img id="yourImage" class="form-image" src="" alt="" border="0" />