i have a h3 tag
<h3> <a href="#"> Initial Text</a></h3>
and i have a TextBox.
When a Some values is typed in that TextBox
<input id="Medication" name="Medication" size="50" type="text" value="">
The value in that anchor link (Initial Text)
Should be replaced with the Value in the TextBox.
How can i do that?
can any one help me with this?
Thanks
Try:
$('#medication').blur(function(){
var objVal = $(this).val();
if(objVal != ''){
$('h3 a').text(objVal);
}
});
This will attach the blur() event handler to execute the provided function when the text box loses focus. The function will check if the value is set and if it is then it will update the text in your <a>
tag.
Well it depends on when you want the text in the anchor to change, but it's going to involve binding an event handler to the input
element. If you want the a
text to change whenever a key is pressed, you could bind to the keypress
or keyup
event:
$("#medication").keyup(function() {
$("h3 a").text($(this).val());
});
If you want the text to change when the user leaves the input
(in other words, on the blur
event), you can bind to the blur
event:
$("#medication").blur(function() {
$("h3 a").text($(this).val());
});
You may want the text to change when the input
is blurred, but only if the value has changed. If that's the case, bind to the change
event.
You may even want to bind a handler to more than one of these events, in which case you could use bind
, which takes a string representing multiple events:
$("#medication").bind("keyup blur change", function() {
$("h3 a").text($(this).val());
});
The important parts of the above code are the $(this).val()
which will get the value entered into the input
by the user, and the $("h3 a").text(...)
which is what actually changes the text of the anchor.
OK, first you bind to the blur event of the input, then, get the value of the text input and replace the link text with that value:
$('#Medication').bind('blur', function(){
var val = $(this).val(); // get value of input
$('h3 a').html(val); // replace text of link
});
I would first place an ID on the <a>
tag or the <h3>
tag. This will allow for quick reference to the anchor you are trying to modify and will make the code more efficient.
<h3> <a id="myAnchor" href="#"> Initial Text</a></h3>
JavaScript/jQuery
$(document).ready(function () {
$('#Medication').change(function () {
$('#myAnchor').text($(this).val());
});
});
Note the above makes use of the .change().