Problema cod javascript in input adaugat cu ajax

Discutii si intrebari legate de scripturi si functii JavaScript, jQuery si Ajax, cod JavaScript in general.
andras
Mesaje: 430

Problema cod javascript in input adaugat cu ajax

Salut,
am urmatoarea instructiune in HTML cu JS care functioneaza corect (simplificat):

Cod: Selectaţi tot

<th><input type="checkbox" id="cec'"  onchange="if (this.checked) {this.parentNode.style.background="#ef4d35"; } else {this.parentNode.style.background="white";}" /></th>
daca aceeasi instructiune o pun in PHP (simplificat, intr-un fisier apelat cu ajax):

Cod: Selectaţi tot

<?php
$re_html .='<th><input type="checkbox" id="cec" onchange="if (this.checked) {this.parentNode.style.background="#ef4d35"; } else {this.parentNode.style.background="white";}" /></th>';
...........
echo $re_html;  
?>
nu mai functioneaza corect (nu se coloreaza checkbox-ul). Am mai intilnit astfel de situatii. Care este cauza? Multumesc.

MarPlo Mesaje: 4343
Salut
Problema e de la ghilimele imbricate incorect. Incearca asa:

Cod: Selectaţi tot

$re_html .='<th><input type="checkbox" id="cec" onchange="if(this.checked) {this.parentNode.style.background=\'#ef4d35\'; } else {this.parentNode.style.background=\'white\';}" /></th>';
...........
echo $re_html; 
Indicat ar fi sa ai codul javascript separat de html, iar in <input>-ul incarcat cu ajax apelezi o functie JS care e deja in pagina. Cam asa:

Cod: Selectaţi tot

$re_html .='<th><input type="checkbox" id="cec" onclick="parentBG(this)" /></th>';
...........
echo $re_html; 
Iar in pagina, functia JS apelata (parentBG() ):

Cod: Selectaţi tot

<script>
function parentBG(elm){
  elm.parentNode.style.background = (elm.checked) ? '#ef4d35' :'white';
}
</script>

andras Mesaje: 430
Am adoptat ultima varianta si functioneaza foarte corect. Multumesc!

Subiecte similare