简体   繁体   中英

value of textarea returned empty

I have a HTML form that contains a textarea and submit button. and a JS script that takes the value of the textarea.

The issue I'm facing is when I type text into the textarea and hit submit, the textarea value is empty. HOWEVER, if I hard code text into the textarea the hardcoded value is returned. If I erase the hardcoded value and delete the hardcoded value and type in my own, the hardcoded vale is still returned.

HTML

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1"> 

<script src="js/jquery/jquery-1.9.1.min.js"></script>

<script src="contentForm.js"></script>
</head>

<body>
<form method="post" >
    <textarea name ="editor" id="editBox" rows="5" cols="2">type</textarea>
    <p><input type="submit" id="submit" value="Submit"></p>
 </form>
</body>
</html>

JS

    function add() {
$("#submit").click(function() {
var message = "start js";
console.log(message);

var contents = $("textarea").val();

if(contents === undefined) {
  console.log("contents undefined");
}
console.log(contents);
var item = {"id":"12", "content": contents};
var obj = JSON.stringify(item);
var obj2 = JSON.parse(obj);
console.log(obj2.id);
console.log(obj2.content);
});
}

$(document).ready(function () {

 add(); 

});

Notice how the textarea above has "type" preloaded. That's the returned value. If I leave it empty, type in my own text in the form and hit submit, the console log shows empty for the value of contents.

I've tried this as well (using textarea id)

var contents = $("#editBox").val();

I'm assuming the issue lies with POST. Because when I hit enter, the text I entered is replaced with "type" (pre-loaded text).

Can POST interfere with it? How else can I go about retrieving the value?

I am not sure of the actual problem, but something strange I have noticed in past few days. console.log() does not work in chrome in few cases like this one. May be it is a firebug bug? Anyways, replaced console.log() with alert and removed the default value from textarea .

Updated fiddle: http://jsfiddle.net/eVmQ9/2/

This seems to work on chrome and firefox.

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