1

normally, i am trying passing value in p,div and pre tag and values are show in above tag now i am passing country name in input tag. but value are not show in input tag. Here is my code:

<!DOCTYPE html>
<html>
<head>
    <title>Get browser and ip address </title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<input type="text" name="country_name" id="country_name" value="">
<p id="country_name"></p>
<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>

<script> 

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#city").html(response.country_name + ", " + response.region);
    $("#country_name").html(response.country_name);
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");

</script>

</body>
</html>

Thanks.

Pradeep Dhakad
  • 65
  • 1
  • 10
  • FYI `id` tags should be unique within an HTML page. You have two elements with the `id=country_name`. So the selector, `$('#country_name')` is going to match two elements on your page. – lurker May 26 '19 at 13:56

3 Answers3

2

Only one item can have a specific id. Try using classes if you want them to share something. Since both the

and have the same id it will not work Note that you can getElementSByClassName but you can only getElementById with the class allowing multiple and ID only allowing for one

2

input fields take value attribute. Try changing this line: $("#country_name").val(response.country_name);

Also, like @Khaleb said, element IDs must be unique.

Scott Flodin
  • 320
  • 1
  • 5
2

You are trying to set input value using .html(). Which is not supported in jquery. You need to use .val() to set input value. Here is the explanation for the same.

Try this:

<!DOCTYPE html>
<html>
<head>
    <title>Get browser and ip address </title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<input type="text" name="country_name" id="country_name" value="">
<p id="country_name"></p>
<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>

<script> 

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#city").html(response.country_name + ", " + response.region);
    $("#country_name").val(response.country_name);
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");

</script>

</body>
</html>
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51