Pradeep Dhakad
Pradeep Dhakad

Reputation: 65

How to pass value in input tag?

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.

Upvotes: 1

Views: 3911

Answers (3)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

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>

Upvotes: 2

Scott Flodin
Scott Flodin

Reputation: 330

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

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

Upvotes: 2

Khaleb Sealey
Khaleb Sealey

Reputation: 21

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

Upvotes: 2

Related Questions