Reputation: 99
I want to change my Input text value by clicking on a p html element.
The code snippet is like this
input type="text" id="query" name="quer" runat="server"/>
p id="demo" click="myFunction()"></p>
myFunction() is in abc.js file that is included in the main Html file.
function myFunction(){
var elem = document.getElementById("query"); // Get text field
elem.setAttribute('value','Insert a correct email');
}
Please help. Thanks in advance
Upvotes: 0
Views: 306
Reputation: 13848
click
should be onclick
<p id="demo" onclick="myFunction()"></p>
However, I suggest you use .value
over setAttribute
:
elem.value = 'Insert a correct email';
setAttribute
is actually changing HTML attribute, you can see it if you open devtool and observe the structure. But what you want is manipulate the DOM property.
For example, you have <input value="123">
in an HTML file. And in page you input something, say "456". Now you can see the difference:
document.querySelector('input').getAttribute('value') // '123', HTML attribute
document.querySelector('input').value // '456', DOM property
At the beginning, HTML attribute will populate to DOM property as initial value. But once you touched DOM property, e.g. you input something in the field, after that changing HTML attribute will NOT dynamically change DOM property. And by the way, on submitting form, the value actually sent out is DOM property, not HTML attribute.
function myFunction(){
var elem = document.getElementById("query"); // Get text field
elem.value = 'Insert a correct email';
}
<input type="text" id="query" name="quer" runat="server"/>
<p id="demo" onclick="myFunction()">Click Here</p>
Upvotes: 1
Reputation: 4038
The event on p tag should be onclick, not click. Update your p tag as following,
<p id="demo" onclick="myFunction()">Click Here</p>
That's it, your code just works fine.
References : onclick
Upvotes: 2