Saturday, 20 January 2018

Read Array object in Javascript Based on Query String

Please check the previous article  Click here to see how we can read the value which we pass in query string
Now Framing the javascript array  Object,


var val = [
        { Id: 1, Image: 'Content/Images/2.jpg', Value:'This is 1 content' },
        { Id: 2, Image: 'Content/Images/2.jpg', Value:'This is 2 content' }
    ];

Code to read array of object is javascript



  $(document).ready(function ()
    {
         // it will use to read the value pass through query string
        var ist = getParameterValueByName('id');

        // Reading array values using loop
        for (var i = 0; i <= val.length; i++)
        {
            if (ist == i)
            {
                $("#ContentId").val(val[i].Id);
                $("#imgDish").attr("src", val[i].Image);
                $("#detailCont").text(val[i].Value);
            }
        }
     
    });

In the above code getParameterValueByName it uses to get the values of querystring
Method for reading query string in javascript.


function getParameterValueByName(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, " "));
    }


In below code  you can see assigning values to input control, image and Div
                $("#ContentId").val(val[i].Id);
                $("#imgDish").attr("src", val[i].Image);
                $("#detailCont").text(val[i].Value);

<body>
  <input id="ContentId" type="text" /> <br />

    <img id="imgDish" width="100" />
    <div id="detailCont" type="text"></div>

</body>



You will get the output like;



No comments:

Post a Comment