简体   繁体   中英

Replace an input value next to span element

I have to this input:

<input type="text" id="my_input" />

After a user enters anything in the input I have to append this next to the span.

<p id="patient_provider" >
  <span>
    Name
  </span>
  Sam
</p>

The code I used is(It should be something like below):

  $("#patient_provider").html($('#patient_provider').children()[0]+$('#my_input').val());

But this is not working.

It is showing something like:

[object HTMLSpanElement] Sam

Also please note :

There are some css implemented on the span directly and I can not add another span

$('#patient_provider').children()[0] is an element and is converted to a [object HTMLSpanElement] string

The right is:

 $("#patient_provider").html($('#patient_provider').children()[0].outerHTML+$('#my_input').val());

If you have the ability to change the markup, I would do so. Something like so - wrapping the place where the name should appear in an element with a useful class. In this case, I went with a span with class name :

<input type="text" name="name" id="my_input">
<p id="patient_provider" >
  <span>Name</span>
  <span class="name">Sam</span>
</p>

Then, your javascript could be improved by doing something like so:

// No-conflict-mode-safe document ready
jQuery(function($) {
    // Find the right input based on the name, and bind to keyup
    $('input[name="name"]).on('keyup', function() {
        // Put the value of the input into the span.name element
        $('#patient_provider .name').text($(this).val());
    );
});

try this,

HTML

<input type="text" id="my_input" />

<p id="patient_provider" >
  <span>
    Name:
  </span>
  <span class="patient_name">
      Sam
  </span>
</p>

JS

 var patientName = $(".patient_name").text();
 var editedName = false;

 $('#my_input').bind('keydown', function(){
    if(editedName == false){
        $(".patient_name").html($(this).val());
         patientName = $(".patient_name").text();
        editedName = true;
    }
 });

 $('#my_input').bind('keyup', function(){
    if(editedName == true){
            $(".patient_name").text(patientName + $(this).val());
    }
 });

JS Fiddle

https://jsfiddle.net/guruling/8afzf4dv/

The way you have it now, that code is only going to run once. You need to wrap it in an event listener so that it runs whenever a users changes the input or when they click an enter button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM