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 .
3 Answers 3
You're looking for
tziros_imerasby ID (getElementByID) but you have only thenameproperty set up totziros_imerasyou have only the method
inc()- you're missing the methoddec()
and most important:
you're incrementing
xwhich is a local variable (it doesn't affect the actual element), you should do instead:elem.value += 1;
2 Comments
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');
2 Comments
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.
?>PHP mode, or use a HEREDOC string.