Home > Back-end >  JavaScript - Calling a function in for loop error
JavaScript - Calling a function in for loop error

Time:09-28

I have the following script which is supposed to take parameters from the URL querystring, put them into an array, and then put the values into text fields.

<script type="text/javascript">
    function getUtms(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]"   name   "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\ /g, " "));
    }
    
    var utmArray = ['utm_campaign','utm_medium','utm_source'];
    for (var i = 0; i < utmArray.length; i  ) {
      console.log(utmArray[i]);
      document.querySelector("p."   utmArray[i]   " input").value = getUtms(utmArray[i]);
    }
    </script>

    <input type="text" name="utm_campaign">
    <input type="text" name="utm_medium">
    <input type="text" name="utm_source">

However I am getting the following error

Uncaught TypeError: Cannot set properties of null (setting 'value')

related to the line

document.querySelector("p."   utmArray[i]   " input").value = getUtms(utmArray[i]);

Thanks in advance!

CodePudding user response:

The selector you need is not "p." utmArray[i] " input" but rather "input[name=" utmArray[i] "]"

i.e. get the input tag with the name attribute equal to utmArray[i]

So in full...

document.querySelector("input[name=" utmArray[i] "]").value = getUtms(utmArray[i]);

CodePudding user response:

You need to query the input elements. In your code, as @Reyno pointed out you're querying p tags which do not have a value property. You can also use getElementsByName in order to access the values of each input by the specified name at the current index.

You can rewrite your code like so:

function getUtms(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]"   name   "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\ /g, " "));
    }
    
    var utmArray = ['utm_campaign','utm_medium','utm_source'];
    for (var i = 0; i < utmArray.length; i  ) {
      console.log(utmArray[i]);
      document.getElementsByName(utmArray[i])[0].value = getUtms(utmArray[i]);
    }
<input type="text" name="utm_campaign">
<input type="text" name="utm_medium">
<input type="text" name="utm_source">

  • Related