Search code examples
javascripthtmljqueryinnerhtml

Using jQuery to edit innerHTML()


I am a total beginner to jQuery. I'm trying to make the page replace the spans inner html with the value that the user types before pressing the button.

$(document).ready(function() {
      // Get value on button click
      $('button').click(function() {
          var str = $('#formValue').val();
        } else {
          str = "empty"
        }
        $('#adVar').html(str);
      }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="formValue" placeholder="type 
        something here">
<button id="submitButton">enter</button>
<p>So now whatever you put in that field should appear here: "<span id="adVar">this 
         is the value we're replacing</span>".
</p>

function advancedFunction() {
  
  if ( document.getElementById("formValue").value ) {
    // grab the value from the form, but we'll need to set a listener (below) since it changes when you click the button
    var theVar = document.getElementById("formValue").value;
  } else {
    theVar = "empty";
  }
  // now that we have a value for the form field, let's output it to the field
  document.getElementById("advancedVar").innerHTML = theVar;


document.getElementById("submitButton").addEventListener("click", advancedFunction);

});

Solution

  • You can try this method :

    $("#submitButton").click(function(){
       var value=$("#formValue").val()
       var advar=$('#adVar')
       if(value.length>1){
          advar.html(value);
       }else{
          advar.html("empty");
        }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input id="formValue" placeholder="type something here">
    <button id="submitButton">enter</button>
    <p>So now whatever you put in that field should appear here: "       
       <span id="adVar">this is the value we're replacing</span>".
    </p>