views:

157

answers:

6

I dynamically assign a textbox value in JavaScript:

var html = '';
for( var s=0;  s++ ; s<10){
  html += '<input type="hidden" name="hfstepDescription'+s+'" id="hfstepDescription'+s+'" value="'+ sstepDescriptionHTML +'">';

}

sstepDescriptionHTML's conntent may like this

<input type="hidden" name="hfstepDescription11" id="hfstepDescription11" value="test1 <div class="">context1</div>">

But when I use document.getElementById('hfstepDescription11').value I would get test1 <div class=, not test1 <div class="">context1</div>

How do I get the right value -> test1 <div class="">context1</div>?

A: 

I'm not sure where you're setting sstepDescriptionHTML but you really need to HTML encode the value of the <input>. The value is only going to be whatever is found between the double quotes, hence why it will only return: test1 <div class=

Check out JavaScript's escape() function.

Jason Berry
A: 

You have to replace the double quotes with single quotes for the class attribute in div.

<input type="hidden" name="hfstepDescription11" id="hfstepDescription11" value="test1 <div class=''>context1</div>" />
rahul
A: 

I use escape() to encode textbox's value and using php code below to decode the textbox's value

then i can get the correct value

$str = uniDecode($str,'big-5');

function uniDecode($str,$charcode){ $text = preg_replace_callback("/%u[0-9A-Za-z]{4}/",toUtf8,$str); return mb_convert_encoding($text, $charcode, 'utf-8'); } function toUtf8($ar){ foreach($ar as $val){ $val = intval(substr($val,2),16); if($val < 0x7F){ // 0000-007F $c .= chr($val); }elseif($val < 0x800) { // 0080-0800 $c .= chr(0xC0 | ($val / 64)); $c .= chr(0x80 | ($val % 64)); }else{ // 0800-FFFF $c .= chr(0xE0 | (($val / 64) / 64)); $c .= chr(0x80 | (($val / 64) % 64)); $c .= chr(0x80 | ($val % 64)); } } return $c; }

nick
A: 

I use escape() to encode textbox's value and using php code - http://www.neo.com.tw/archives/000152 - to decode the textbox's value

then i can get the correct value

nick
+1  A: 

The problem is encoding; if your value contains the same character enclosing the value, you basically have to encode it or to set the value otherwise.

You can choose two different paths:

First option is to escape the value before inserting it to the generated HTML:

var escapedValue = value.replace(/&/, "&amp;").replace(/\"/, "&quot;");

html += "<input type=\"hidden\" name=\"test\" id=\"test\" value=\"" + value + "\"/>";

Another option is to set the value after appending your HTML to the DOM:

document.getElementById("test").value = value;
troethom
A: 

You can escape it using the method described in the following post

http://hemanshubhojak.com/Home/Post?postId=7

Hemanshu Bhojak