Loading variable from url, only works for numbers?

My url is example.com/load_item.html?item=QB123

Where QB123 is a random assortment of letters and numbers we will call item_code.

I need to parse the url to grab the item_code and enter it into a form on the page.

Here's what I have:

<div class="col_full">
<label for="item_code">Item Number:</label>
<input type="text" id="item_code1" name="item_code" class="form-control"  required/>
</div>

      

<script type="text/javascript">
document.getElementById('item_code1').value=+window.location.search.substr(6) ; 
</script>

      

It works if item_code is all numbers (for example 12345). However, when there are letters, the form value is represented as NaN. Any ideas

+3


source to share


2 answers


the plus sign must be to the left of the equal sign to concatenate the strings:

document.getElementById('item_code1').value += window.location.search.substr(6) ;

      



Otherwise, you treat it window.location.search.substr(6)

as a number.

+4


source


This will give you an object with your request parameters:

 var obj = {};
 location.search.replace('?','').split('&').forEach(
    function(item){
      arr = item.split('='); 
      obj[arr[0]] = arr[1]; 
    }
 );

      



So, for your example, if you console.log the obj variable, you get:

 Object {item: "QB123"}

      

+2


source







All Articles