Amod Amod -4 years ago 83
HTML Question

How to insert data from a url to a HTML field with "data-field-id" or "data-val-type"?

(EDIT: I have not merged with the duplicate question mentioned because I am NOT a highly experienced coder, so have used language most 'non-coders' will use. So this question and the answer might actually provide value for people like us.)

I have this code which pre-populates an email input field based on the id of the field, with text taken from the url *

Example - mywebsite.com&?mail=some@example.com, then the email string will be inserted in the email field on the page.

CURRENT CODE:

var mail = document.querySelector('input.emailfieldclass');
if (mail) {
var t = document.location.href.split('?')[1];
if (t) {
var params = {};
var lst = t.split('&'), l = lst.length;
for (var i = 0; i < l; i++) {
var p = lst[i].split('=');
if (!p[1]) continue;
params[p[0]] = p[1];
}

if (params.mail) {
mail.value = params.mail;
}
}
}


PROBLEM:

1) The above code works for a normal html input element with an id and/or class.

2) But how to make it work when I have a form with the following email field attributes, without any specific id's:

<input placeholder="Email" data-field-id="field32" data-val-type="email">


Limitations:
Cannot add my own id or class to this field. Can only work with the above data attributes.

Answer Source

Here you go with the data-selector, mentioned in the comments by guradio.

var mail = document.querySelector('[data-val-type=email]');
console.log(mail);
/*
if (mail) {
  var t = document.location.href.split('?')[1];
  if (t) {
      var params = {};
      var lst = t.split('&'), l = lst.length;
      for (var i = 0; i < l; i++) {
          var p = lst[i].split('=');
          if (!p[1]) continue;
          params[p[0]] = p[1];
      }

      if (params.mail) {
          mail.value = params.mail;
      }
  }
}
*/
<input placeholder="Email" data-field-id="field32" data-val-type="email">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download