How to add dynamically attribute value using Jquery? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to add dynamically attribute value using Jquery? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have logic where i am trying to add host url dynamically so it work in all env based on hosst, so below trying to find a file that is there in host but its never going into $.each statement , if call url directly http://18.35.168.87:6000/Sdk/wrapper-sdk/client/out.json it worked and rendered data, any idea what could have wrong in below code to achieve this task ?

main.js

function myFunction(val) {
    var url = "../../wrapper-sdk/" + client + "/out.json";
        if (window.location.hostname.indexOf("localhost") !== -1 ||
            window.location.host.indexOf("localhost") !== -1) {
            var scripts = document.getElementsByTagName('script');
            var host = '';
            $.each(scripts, function (idx, item) {
                if (item.src.indexOf('Sdk/wrapper-sdk') !== -1 && (item.src.indexOf('out.json') !== -1)) {
                    host = item.src.split('?')[0];
                    host = host.replace('wrapper-sdk/' + client + '/out.json', '');
                }
            });

   url = url.replace('../../', host);
        }
        $.ajax({
            url: url + "?no_cache=" + new Date().getTime(),
            dataType: "json",
            "async": false,
            success: function (data) {
                console.log(data);
            },
            error: function () {
                console.log('error while accessing api.json.')
            }
        });
}

Answer

I would suggest breaking up some of your checks into their own function. Makes it just a bit easier to follow the logic.

function validIp(str) {
  var parts = str.split(".");
  var result = true;
  $.each(parts, function(i, p) {
    if (parseInt(p) > 0 && parseInt(p) < 255) {
      result = result && true;
    }
  });
  return result;
}

function checkLocalUrl(str) {
  var result = 0;
  if (str.indexOf("localhost") >= 0) {
    result = 1;
  }
  if (validIp(str)) {
    result = -1;
  }
  /*
  0 = Some Domain or Host Name, not LocalHost
  1 = LocalHost 
  -1 = IP Address
  */
  return result;
}

function changeSources(client) {
  if (checkLocalUrl(window.location.hostname) || checkLocalUrl(window.location.host) {
      var scripts = $("script");
      var host = '';
      scripts.each(function(i, el) {
        var src = $(el).attr("src");
        var nUrl = new URL(src);
        var pro = nUrl.protocol;
        var hn = nUrl.hostname;
        if (nUrl.pathname.indexOf('/Sdk/wrapper-sdk') == 0 && nUrl.pathname.indexOf('out.json') > 0) {
          host = pro + "://" + hn + "/wrapper-sdk/" + client + "/out.json";
        }
        $.ajax({
          url: host
          data: { no_cache: new Date().getTime() },
          dataType: "json",
          async: false,
          success: function(data) {
            console.log(data);
          },
          error: function() {
            console.log('error while accessing api.json.')
          }
        });
      });
    }
  }
}

See also: new URL()

You can send a string to checkLocalUrl() and it will return 1 or true if it’s potentially a localhost URL. It will return 0 or false if it’s any other domain pattern or -1 or false if it’s an IP address.

In changeSources() we can use this to check for local urls and perform the AJAX you defined.

We are here to answer your question about How to add dynamically attribute value using Jquery? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji