How to print JavaScript variable value in HTML tag? [closed]

2

I would like to limit the selection of input date in this way, but it is not working.

<script type="text/javascript">
  var data = new Date();
  var dia     = data.getDate();          
  var mes     = data.getMonth();         
  var ano4    = data.getFullYear();
  var str_data = ano4 + '-' + (mes+1) + '-' + dia;
  <?php $data=str_data;?>
</script>
<input type="date" name="data" max="<?=$data?>"/>
    
asked by anonymous 13.10.2017 / 17:40

3 answers

2

I think it's easier to work by filling in the maximum direct date on PHP :

<input type="date" name="data" max="<?=date('Y-m-d H:i:s')?>" />

But if you want to limit by JavaScript remember that HTML5 allows users to change the value in Input with the keyboard and the arrows, so you have to remove those entries to ensure that the date maximum of its Input is respected (of course this does not dispense with the need to validate on the server as well).

var dateInput = document.getElementById("data");
var d         = new Date();
var dia       = d.getDate();          
var mes       = d.getMonth();         
var ano       = d.getFullYear();
var data      = ano + '-' + (mes+1) + '-' + dia;
dateInput.setAttribute("max", data);
.no-spin::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
<input type="date" name="data" id="data" class="no-spin" onkeydown="return false"/>
    
13.10.2017 / 18:19
4

You can do this:

var data = new Date();
var dia     = data.getDate();          
var mes     = data.getMonth();         
var ano4    = data.getFullYear();
var str_data = ano4 + '-' + (mes+1) + '-' + dia;
inp = document.getElementsByName('data')[0];
inp.setAttribute("max", str_data);
<input type="date" name="data"/>

Or instead of inp.setAttribute("max", str_data); :

...
inp.max = str_data;
    
13.10.2017 / 17:47
0

You can not get a JavaScript-generated variable and assign its value inside a PHP script in this way.

Instead, assign to the input tag the JavaScript value using setAttribute() :

var data = new Date();
var dia     = data.getDate();          
var mes     = data.getMonth();         
var ano4    = data.getFullYear();
var str_data = ano4 + '-' + (mes+1) + '-' + dia;
el = document.getElementsByName("data")[0];
el.setAttribute("max", str_data); // ou, de forma mais curta: el.max = str_data;
    
13.10.2017 / 17:50