0

I have a problem getting the id element to show in the <p>. Below is my sample coding, it cannot show my id element in the <p>. Hope someone can guide me on which part I a getting wrong. Thanks.

<!DOCTYPE html>
<html>
<body>

Name: <input id="try" type="text" value="testing"><br>


<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {

  var x = $('#try').attr('id');
  document.getElementById("demo").innerHTML = x;
  
 
}
</script>

</body>
</html>

Actually, I want the expected result like below the picture:

enter image description here

  • Where is "fname"? Do you want to show the "input" element "id" attribute value? – Amit Saini Jan 23 '21 at 11:08
  • You are using jQuery, but haven't included the library/framework to your page. – Ivar Jan 23 '21 at 11:08
  • Does this answer your question? [JQuery - $ is not defined](https://stackoverflow.com/questions/2194992/jquery-is-not-defined) – Ivar Jan 23 '21 at 11:13

3 Answers3

3

You are using an jQuery selector and method but you haven't include jQuery.

var x = $('#try').attr('id');

If you want to use it then include jquery with

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you are looking for a plain JS solution then use getElementById as you did above and then read the id property .id

document.getElementById('try').id;

<!DOCTYPE html>
<html>
<body>

Name: <input id="try" type="text" value="testing"><br>


<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {

  var x = document.getElementById('try').id;
  document.getElementById("demo").innerHTML = x;
  
 
}
</script>

</body>
</html>
Aalexander
  • 4,987
  • 3
  • 11
  • 34
2

If you want to go with plain javascript then you need to replace the below line code:

var x = $('#try').attr('id');

with this one:

var x = document.getElementById("try").getAttribute("id");
Amit Saini
  • 575
  • 4
  • 11
1

I do believe that you are using jquery library? Did you import the library itself?

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

Because otherwise you are going to get a problem in console tag like this "$ is not defined"