I try to create a button in php and increase or decrease its value (inside the text input) on click.
<?php
echo "<script>
function inc(elem)
{
x = elem.value;
//alert('dsadasdasdsadasdas');
if(x<31)
{
x= x+1;
}
alert(x);
elem.value = x;
}
</script>";
echo '<form action="tziros.php" method="post">';
echo '<input type="text" value="1" name="tziros_imeras">';
echo '<br>';
//echo '<input type="button" value="ADD +" onClick="inc(document.getElementById("tziros_imeras"))">';
echo '<input type="button" value="ADD +" onClick="inc(document.getElementById(\'tziros_imeras\'))">'
//echo '<input type="button" value="DEC -" onClick="dec();">';
echo '<input type="submit" name="submit_tziros_meras" value="OK">';
echo '</form>';
?>
Problem is that javascript is not running at all .
EDIT : after reading your answers i came up with this: js:
function inc(elem)
{
elem.value++;
}
and on the form:
echo '<input type="text" value="1" id="tziros_imeras" name="tziros_imeras">';
So now at last, the js is running .
You're looking for tziros_imeras
by ID (getElementByID
) but you have only the name
property set up to tziros_imeras
you have only the method inc()
- you're missing the method dec()
and most important:
you're incrementing x
which is a local variable (it doesn't affect the actual element), you should do instead:
elem.value += 1;
Update your PHP to use this form so it is easier to read and debug:
echo <<<END
content here will be printed
multiple lines!
END;
I'm not sure I believe you, that is is not "running". Insert an alert in your JavaScript to verify.
alert('I am alive');
This part of the code:
echo '<input type="button" value="ADD +" onClick="inc(document.getElementById("tziros_imeras"))">';
Needs to be like this:
echo '<input type="button" value="ADD +" onClick="inc(document.getElementById(\'tziros_imeras\'))">';
The JS being outputted was like this:
onClick="inc(document.getElementById("tziros_imeras"))"
Which, as you'll notice, has messed up quotes. This is what was causing the JS to fail to run (look in your browser console and you'll see the errors as well).
As some others have said, you have some JS errors as well, but this is the main issue related to your question.