-1

(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.

Amod
  • 283
  • 8
  • 18
  • 2
    use data selector `$("[data-field-id=field32]")` – guradio Feb 27 '17 at 08:19
  • take a look a this stackoverflow post http://stackoverflow.com/questions/23592030/get-data-attribute – Brent Boden Feb 27 '17 at 08:20
  • Possible duplicate of [Select elements by HTML5 data attribute in jQuery](http://stackoverflow.com/questions/4993447/select-elements-by-html5-data-attribute-in-jquery) – JJJ Feb 27 '17 at 08:20
  • you can take examples from these links http://stackoverflow.com/questions/2487747/selecting-element-by-data-attribute , http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value . Also, I would suggest you do a quick search before putting on questions here. – mane Feb 27 '17 at 08:21

1 Answers1

1

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">
DomeTune
  • 1,401
  • 10
  • 21