jQuery value in H3 Tag replace by value from Text Box

时光总嘲笑我的痴心妄想 提交于 2019-12-01 12:19:40

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!