Dyneskye
Dyneskye

Reputation: 33

$("#id").val() not working the same as document.getElementById("id").value

I am trying to create a function that converts plain text to HTML as a bit of coding practice. This is the code for it.

function convert() {
  var input_str = "";
  var text_input = "";
  var output_html = "";
  var counter = 0;

  input_str=$("#in").val();
  text_input = input_str.trim();

  if (text_input.length > 0) {
    output_html += "<p>";
    for (counter=0; counter < text_input.length; counter++) {
      switch (text_input[counter]){
        case '\n':
          if (text_input[counter+1]==='\n'){
            output_html+="</p>\n<p>";
            counter++;
          }
          else output_html+="<br>";
          break;

        case ' ':
          if(text_input[counter-1] != ' ' && text_input[counter-1] != '\t')
            output_html+=" ";
          break;

        case '\t':
          if(text_input[counter-1] != '\t')
            output_html+=" ";
          break;
        case '&':
          output_html+="%amp;";
          break;
        case '"':
          output_html+="&quot;";
          break;
        case '>':
          output_html+="&gt;";
        case '<':
          output_html+="&lt;";
        default:
          output_html+=text_input[counter];
      }
    }
    $("#out").val() = output_html; 
  }
}

I can't seem to figure out why $("#out").val() = output_html isn't working, but changing $("#out") to the JavaScript equivalent document.getElementById("id").value works absolutely fine. I don't mind using the latter to fix the problem but I am a bit mind boggled and would love to know the solution.

<div id="wrapper">
  <div id="html" class="tabs">
    <textarea id="out">OUTPUT</textarea>
  </div>
  <div id="plain" class="tabs">
    <textarea id="in">INPUT</textarea>
  </div>
</div>

EDIT I have changed the HTML id="output" to id="out" (as it is on the original file, I accidentally edited it when pasting it into stackoverflow

Upvotes: 2

Views: 855

Answers (3)

Jonathan Arias
Jonathan Arias

Reputation: 570

The correct way to assign/set a value with JQuery is:

$("#out").val(output_html)

An just .val() to retrieve the value.

Here is the full reference

Upvotes: 0

qiAlex
qiAlex

Reputation: 4346

id in HTML and JS not matching

<textarea id="OUTPUT"></textarea>

$("#out")

Upvotes: 0

ggg
ggg

Reputation: 1192

to set a value, do it like that:

$("#out").val(output_html)  ; 

Upvotes: 2

Related Questions