Search code examples
javascriptjqueryscramble

text gets scrambled when inserted through .html() jquery method


In a web page I'm doing there's a table where by clicking on each row you can modify it. This is done by substituting the content of each cell with an input field containing the relative value. In order to let the user cancel the changes made I save the contents of the whole table row before making the substitution, which I then use to compose the new html string to put in the table row (basically, I just put it in a function call which is then called when a button is pressed to revert the changes). if I try to display it through alerts the string looks fine. However, firebug returns an error because apparently the string gets scrambled after I put it in the page by calling .html on the . What I mean is that instead of being

<tr><td>somedata</td><td><input type=button onclick=fun('oldTrContent')/></td></tr>

it's

<tr><td>somedata</td><td><input type=button oldTrContentNotInOrder') onclick=fun(/></td></tr>

which clearly can't work. I tried putting some alerts in the function in order to see if this behavior was caused by some formatting error, but everything looks fine up to the moment of the call to .html(). The code I used is this:

function mostraModificaCompet(ids, nome){
var id='#'+nome;
var statoPrec=escape($(id).html());
alert(statoPrec);
var d=$(id+" .data").html();
var c=$(id+" .caus span").html();
var de=$(id+" .descr").html();
var pu=$(id+" .prezzou").html();
var q=$(id+" .qta").html();
var pt=$(id+" .prezzot").html();
var iu=$(id+" .ivau").html();
var it=$(id+" .ivat").html();
var t=$(id+" .tot").html();
var r=$(id+" .res").html();
var pr=$(id+" .progr").html();
var str="<td class=data ><input type=text value="+d+" /></td><td class=caus ><select class=selcaus ></select></td><td class=descr ><input type=text value="+de+" />\
</td><td class=prezzou ><input type=text value="+pu+" /></td><td class=qta ><input type=text value="+q+" /></td><td class=prezzot ><input type=text value="+pt+" disabled /></td>\
<td class=ivau ><input type=text value="+iu+" /></td><td class=ivat ><input type=text value="+it+" disabled /></td><td class=tot ><input type=text value="+t+" disabled /></td><td>\
<input type=button value='Conferma' onclick=modificaCompet("+ids+", '"+nome+"') /></td><td><input type=button value=Annulla onclick=ripristinaCompet('"+nome+"', '"+statoPrec+"') /></td>";
alert(str);
$(id).html(str);
}

the variable where I save the old content is statoPrec, which I then use when composing str (it's at the end of the string). Thanks in advance to anyone who answers.


Solution

  • You're trying to set the value to invalid html, onclick=modificaCompet("+ids+", '"+nome+"') needs some quotes around it so it's onclick=\"onclick=modificaCompet("+ids+", '"+nome+"')\". And any other attributes you failed to quote.