-2

I have issue with script js inside php so i want ipnut get the somme of the value return by function js in dispaly in input with condition in php inside the input in below my script php:

function getSum(){               
    let NotePresence= document.getElementById("NotePresence").value;
    let NoteValidation= document.getElementById("NoteValidation").value;
    let NoteEvaluation= document.getElementById("NoteEvaluation").value;
    let t=NotePresence+NoteValidation+NoteEvaluation;
    return t;
}

calling in php:

<div class="form-group" style="display: flex">
    <input readonly="" style='width: auto' type="text" 
            name="NoteFinale" id="NoteFinale" 
            class="form-control" maxlength="2" 
            value="<?php echo '<script type="text/javascript">getSum();</script>';?>
            size="4" />
    <label for="">&nbsp;/80</label>
</div>

Thanks in advance

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Feb 18 '22 at 11:53
  • If you insert HTML tags inside a `value` attribute it'll be handled as plain text. You won't get scripts executed or HTML rendered. Whether you use PHP to print this markup doesn't make any change. – Álvaro González Feb 18 '22 at 11:55

1 Answers1

1

You can't put a script element inside an attribute value.

If you want to assign a value to the attribute from JS, then:

  • Put the script somewhere after the element in the DOM
  • Find the element with DOM methods (e.g. document.getElementById)
  • Assign the value to the element with DOM

Note, however, that since you should know the initial values for the three elements you are reading from, you should be able to eliminate JS entirely and just do this with PHP.


$NotePresence = 50;
$NoteValidation = 100;
$NoteEvaluation = 150;

<input name="NotePresence" value="<?=htmlspecialchars($NotePresence)">
<input name="NoteValidation" value="<?=htmlspecialchars($NoteValidation)">
<input name="NotePresence" value="<?=htmlspecialchars($NotePresence)">
<input name="NoteFinale" value="<?=htmlspecialchars($NotePresence + $NoteValidation = $NoteEvaluation)">

That is, assuming you want to combine them when the document loads.

If you want to do it later, then…

In JavaScript you would need to move the code into a function that you call when a suitable event (e.g. change on an input or submit on a form occurs).

In PHP you would need to move the code to the place the data is submitted to and combine the data from $_POST.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335