I'm trying to capture the client-side IP address and automatically store it as the value inside of an input field. Here's my code so far:
var Ip;
fetch('https://api.ipify.org/?format=json')
.then(res => res.json())
.then(data => Ip = data.ip)
.then(() => console.log(Ip))
.then(() => document.getElementById('awf_field-106493013').value = Ip);
This is returning the error:
Uncaught (in promise) TypeError: Cannot set property 'value' of null
.value is the bit of code it doesn't like, which seems to mean awf_field-106493013 is null, but I know for a fact by the time this function has been called the input has populated, and I'm positive this is the correct input id.
What am I missing?
EDIT Here's what the input looks like:
<label class="previewLabel" for="awf_field-106493013">ipaddress:</label>
<div class="af-textWrap"><input type="text" id="awf_field-106493013" class="text" name="custom ipaddress" value="" onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} " tabindex="503" /></div>
This is all called before the javascript code so it should be there.
Edit 2 Here's all the javascript I currently have on my page, I just made it so when the document is ready, then the fetch is made:
<script type="text/javascript">
function getUrlParam(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, ' '));
}
var tid = getUrlParam("adid");
var date = Date(Date.now());
jQuery(document).ready(function () {
setIp();
jQuery('#awf_field-106493014').val(date.toString()); //Time
if (tid != null) {
jQuery('#awf_field-106493015').val(tid.toString()); //Tid
} else {
jQuery('#awf_field-106493015').val("nulltid"); //Tid
}
});
function setIp(){
var Ip;
fetch('https://api.ipify.org/?format=json')
.then(res => res.json())
.then(data => Ip = data.ip)
.then(() => console.log(Ip))
.then(() => document.getElementById('awf_field-106493013').value = Ip);
}
</script>
Returns the same
getElementByIdreturns a non-null value?.then(res => res.json()).then(data => data.ip).then(ip => { console.log(ip); return ip; }).then(ip => document.getElementById('awf_field-106493013').value = ip);should fix it.id="awf_field-106493013". "Return value: AnElementobject describing the DOM element object matching the specified ID, ornullif no matching element was found in the document." -Document.getElementById()documentation