prparmar prparmar - 4 months ago 10
HTML Question

How to get url data in html textbox

i have a simple code of javascript which displays text from url.
example: index.html?id=001
then its output displays in html page as 001. but i want that data (id=001) into html text box which display only "001" into textbox.

here is my code.

<script type="text/javascript">
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
return data;
}
</script>

<br />
<script type="text/javascript"> document.write(GET("id")[0]); </script>
<br /><br />
<input type="text" id="" value="" name="" />


Actually i want that "001" into textbox as a textbox value.

Answer

Regular expressions are probably overkill for this, and your expression will only find the querystring value if it immediately follows the ?.

You should use location.search rather than the full URL, because then you just need to take everything after the first character (which will be ? if there is anything), and it will eliminate hashes.

I used simple string splitting to create a reusable map of key/value pairs for lookup.

function GET() {
  var data = [];
  for (var i = 0; i < arguments.length; i++) {
    data.push(getQueryMap()[arguments[i]]);
  }
  return data;
}

var queryMap = null;
function getQueryMap() {
  if (queryMap) { return queryMap; }
  queryMap = {};
  var querySplit = location.search.substring(1).split('&');
  for (var i = 0; i < querySplit.length; i++) {
    var thisQuery = querySplit[i].split('=', 2);
    queryMap[thisQuery[0]] = thisQuery[1];
  }
  return queryMap;
}

To use the input and get the value into it, you need an ID on it or another way to identify it:

<input type="text" id="someInput" value="" name="" />

Then, after it, put a script like so:

<script type="text/javascript">
  document.getElementById('someInput').value = GET('id')[0];  
</script>