Javascript function inside php - php

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 reference
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.

Related

Quiz FORM POST with radio checkboxes issue

I have a quiz test page where I want to test the user for knowledge.
I did it so it works, but it has a flaw.
This is my code for populating the quiz with questions and (possible) answers from a mysql database:
echo '<form action="'.$_SERVER["PHP_SELF"].'" method="post" id="quiz">';
$sql=mysql_query("SELECT idtest,no_q,title_q,q,idteste_dtl,corect_a from teste_dtl where idtest=".$idtest." order by no_q");
$num = mysql_num_rows($sql);
$i=0;
while ($row=mysql_fetch_row($sql)) {
echo '<h3 style="color:#e74c3c">'.$row[2].'</h3>';
echo '<p data-toggle="tooltip"><strong>'.$row[3].'</strong></p>';
$ssql=mysql_query("select letter,answer from tests_answers where idtest=".$idtest." and idq=".$row[4]." order by letter");
while ($rrow=mysql_fetch_row($ssql)) {
$Label = 'question-'.$row[1].'-answers-'.$rrow[0];
echo '<div>';
echo '<label class="radio">';
echo '<input type="radio" data-toggle="radio" name="answers['.$row[1].']" id="'.$Label.'" value="'.$rrow[0].'" unchecked>';
echo $rrow[0].') '.$rrow[1];
echo '</label>';
echo '</div>';
}
echo ' <br>';
echo '<input type="hidden" name="question['.$row[1].']" value="'.$row[2].'">';
echo '<input type="hidden" name="corect_a['.$row[1].']" value="'.$row[5].'">';
echo '<input type="hidden" name="idemp" value="'.$idemp.'">';
echo '<input type="hidden" name="idtest" value="'.$idtest.'">';
echo '<input type="hidden" name="idfirm" value="'.$idfirm.'">';
echo '<input type="hidden" name="namefirm" value="'.$namefirm.'">';
echo '<input type="hidden" name="totalq" value="'.$num.'">';
}
echo' <input type="submit" class="btn btn-hg btn-primary" value="Check answers" />';
echo '</form>';
So basically I generate a pair of text (question) + radioboxes (possible answers) from 2 tables. Table 1 is called "teste_dtl" and Table 2 is called "tests_answers".
All works perfectly except there is a bug. If the user does not check a radio box in a question... my code seems to think that the first radio box was checked.
So I have something like:
Question ONE
Body of question one... some text... and so on
A) first answer
B) second answer
C) third answer
D) fourth answer
Question TWO
Body of question two... some text... and so on
A) first answer
B) second answer
C) third answer
D) fourth answer
...
So the A,B,C,D... are checkboxes (input type radio). They are all unchecked from the start.
When I POST the results... apparently the questions that were not answered (no radio was checked) are considered as "answered with answer A)"
How can I avoid this?
Thank you
Radio buttons are supposed to always have a value.
The HTML specification says: "If no radio button in a set sharing the same control name is initially 'on', user agent behavior for choosing which control is initially 'on' is undefined." This means, practically, that depending on the browser and/or the Javascript library used to submit the form (if you're using AJAX), you can get unpredictable results.
You should force one of the buttons to be selected either by inserting checked="checked" like this:
$first_answer = true; // Set a flag for the first answer
while ($rrow=mysql_fetch_row($ssql)) {
$Label = 'question-'.$row[1].'-answers-'.$rrow[0];
echo '<div>';
echo '<label class="radio">';
// Output the beginning of the INPUT tag
echo '<input type="radio" data-toggle="radio" name="answers['.$row[1].']" id="'.$Label.'" value="'.$rrow[0].'"';
if ( $first_answer ) { // When the flag is true...
echo ' checked="checked"'; // ...add the 'checked' parameter...
$first_answer = false; // ...and set the flag to false for the next round
}
echo '/>'; // Close the INPUT tag
echo $rrow[0].') '.$rrow[1];
echo '</label>';
echo '</div>';
}
Another option is to add some Javascript to check that the user has selected an answer.

jQuery - Display a textbox when a link/button is clicked

I'm trying to put a reply button for each comment so when someone click on the button (for example "Reply"), a textbox will come up automatically where users can fill in a form.
I didn't do much so far...
PHP
<div id='replycomment' class='reply' onclick='jsReply($comment_id);'>Reply</div>
<div id='showreply'></div>
jQuery
function jsReply(comment_id) {
var form = '<form id="showReplyForm" action"add_reply.php" method="post">';
form += '<textarea name="replybody" cols="35" rows="2" maxlength="299"</textarea>';
form += '<input type="hidden" name="replybodyId" value="' + comment_id + '" />'
form += '<input type="submit" name="replysubmit" value="Reply"/></form>';
jQuery('#replybody').replaceWith(form); }
Can anyone PLEASE help me with that? it would be much appreciated.
I'm a bit confused with the way I need to link the id from jquery to php...
Thank you
To make your code work, do this: http://jsfiddle.net/MaqLQ/1/
within head:
var jsReply = function(comment_id) {
var form = '<form id="showReplyForm" action"add_reply.php" method="post">';
form += '<textarea name="replybody" cols="35" rows="2" maxlength="299"></textarea>';
form += '<input type="hidden" name="replybodyId" value="' + comment_id + '" />';
form += '<input type="submit" name="replysubmit" value="Reply"/></form>';
jQuery('#showreply').replaceWith(form);
}
you were missing a semi-colin at the end of one of your form concatenations. you were looking at 'replyBody' rather than the 'showreply' that exists in your html, and if your code wasn't global your html it wouldn't have been defined for the onclick. you were also missing the end angle bracket for your opening textarea tag.
also, i don't know your context and i'm not here for a code review, but among a few other things... you should really avoid using onclick within your html elements.
I recommend using the jQuery library.
Hide #showreply via CSS display: none; and place the HTML form within it.
$('#replycomment').click(function() {
$('#showreply').show();
});
I also recommend changing your IDs to classes since you will have multiple instances.
PHP
<div class='reply'>Reply</div>
<form action='add_reply.php' method='POST' class='reply-form'>
<textarea name='replybody'></textarea>
<input type='hidden' name='comment_id' value='<?php echo $comment_id; ?>' />
<input type='submit' value='Reply' />
</form>
CSS
.reply-form {
display: none;
}
Javascript
$(".reply").click(function() {
$(this).siblings(".reply-form").show();
$(this).hide();
});

Enable and Disable array of textBoxes by check boxes

i have been working on this code !
and i couldn't done it right .
what i want is the text box to be enabled when the corresponding checkbox is checked .
but when apply the function nothing happens :(
in my code the text and check boxes are dynamically generated from database using php .
here is my code :
<div><div class="ac-container">
<div id="accordion">
<?php
$qry="SELECT * FROM catalog";
$result= mysql_query($qry);
if($result){
while($info = mysql_fetch_array($result))
{
print "<h3> cat:".$info['name']."</h3><div>";
$qryitem="SELECT * FROM item WHERE Id=". $info['Cid'];
$resultitem=mysql_query($qryitem);
if($resultitem){
?>
<form name="form1" id="form" method="post" action="manage_item_action.php" >
<?php
while($info=mysql_fetch_array($resultitem))
{
?>
<input type="checkbox" id="checkB" name="op[]" value="<?php echo $info['Id'];?>" /> <?php echo $info['name'];?>
<label> Quantity <input disabled="disabled" id="textB" type="text"
name="Quantit[]" value="<?php echo $info['Quantity'];?>"/>
</label>
<script>
checkBoxes=document.form1.elements['op[]'];
textBoxes=document.form1.elements['Quantit[]'];
for(var i=0 ; i<checkBoxes.length;i++){
checkBoxes[i].onchange = function() {
textBoxes[i].disabled =!(this.checked);};
}
</script>
<br/>
<?php
}
}
else echo "There are no items.";
print "</div>";
}
}
?>
</div>
<input type="submit" value="update" name="submit"/>
<input type=reset value="clear"></td></tr> </form>
The problem you are having is that inside your event handler the variable i is not defined. To overcome this problem, you could add a property to each checkbox to save what index they are referring to:
checkBoxes=document.form1.elements['op[]'];
textBoxes=document.form1.elements['Quantit[]'];
for(var i=0 ; i<checkBoxes.length;i++)
{
checkBoxes[i].myIndex = i;
checkBoxes[i].onchange = function() {
textBoxes[this.myIndex].disabled =!(this.checked);
};
}
Other methods to solve this problem: http://www.howtocreate.co.uk/referencedvariables.html
Your code is still pretty messed up. For instance you are generating too many closing <div/>-tags with your first print-statement. I would suggest you just remove the PHP-code from your question, as the question is only related to html and javascript.
I would also suggest to use a library for manipulating DOM elements like jQuery.
When writing and debugging javascript, you should always make sure that you get error messages. "nothing happens" is a sign that you are just ignoring errors. For Firefox download the addon Firebug. Safari also has developer tools that you can activate in the settings. Using these tools will make it very easy to spot and solve problems like this.

Rendering javascript code in php document

I'm a beginner to PHP and I have a quick question. Is it possible to have javscript code injected into a document through php?
For example, suppose I wanted to inject a button that called a function after a form is filled out:
<html>
<head>
<script type = text/javascript>
function func() {
...
}
</script>
</head>
<body>
<form action = 'welcome.php' method = 'post>
Name: <input type = 'text' name = 'fname' />
<input type = 'submit' value = 'submit' />
</form>
<?php
if (isset($_POST['fname'])) {
echo '<input type = button onclick = func />'
}
?>
</body>
</html>
Would this work? If not, why not?
Any help would be great
Will work fine - just remember to close your quoted strings :
<form action='welcome.php' method='post'> // add ' here
Name: <input type='text' name='fname' />
<input type='submit' value='submit' /> // removed a couple of spaces (not required)
</form>
<?php
if (isset($_POST['fname'])) {
echo '<input type="button" onclick="func" />'; // added some quotes and a semicolon
}
?>
I have removed the spaces between the attributes and the values in HTML from type = "something" to type="something" although I can't find the "official" specification on this. It seems that the spaces are perfectly valid ...I think its my personal preference to have no white space there .....
Try:
echo '<input type="button" onclick="' . $_POST['fname'] . '" />';
SAMPLE
If fname=doSomething then use:
echo '<input type="button" onclick="' . $_POST['fname'] . '()" />';
and your rendered HTML would be:
<input type="button" onclick="doSomething()" />
Then you'd just need your function somewhere:
<script>
function doSomething() { }
</script>
If your current page is welcome.php and you ran this code, you would press the Submit button and the page would reload and have your new button.
But the best way to see whether this works for you or not is to run it. Why don't you try that first?

Invalid argument supplied for foreach() loop

Hi Stackoverflow i hope you are all well today,
i seem to have run into an issue and am kindly requesting your assistance;
Basically i am using jQuery to manipulate a form, the form then stores in the session and upon returning to the page a foreach loop is used to return the values from the session into the page.
The issue is if I create more than one instance of this foreach loop it gives me an invalid argument (if i add the same code over and over again it works fine)
So firstly here is the code;
jQuery
$(function(){
$('.add_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
var lineBreak = $('<br/>');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.children_form').append(input);
$('.children_form').append(lineBreak);
})
$('.add_s_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
var lineBreak = $('<br/>');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.spouce_children').append(input);
$('.spouce_children').append(lineBreak);
})
});
and the PHP / HTML CODE -> Button One (add_child)
Children, please name your natural and / or addopted children
<?php foreach($_SESSION['children'] as $index=>$child){ ?>
<?php echo "<input type='text' name='children[{$index}]' value='{$child}'/>";?>
<?php } ?>
<input type="button" count='<?php echo count($_SESSION['children']);?>' name="children" class="add_child" value="Add Another Child"/>
<div class="children_form">
<?php //add the inputs here?>
</div>
and the PHP / HTML CODE -> Button Two (spouce_children)
<label>Spouces Children, please name all natural and addopted children</label>
<input type="text" name="spoucechild" id="spoucechild" />
<?php foreach($_SESSION['spoucechild'] as $index=>$child){ ?>
<?php echo "<input type='text' name='spoucechild[{$index}]' value='{$child}'/>";?>
<?php } ?>
<input type="button" count='<?php echo count($_SESSION['spoucechild']);?>' name="spoucechild" class="add_s_child" value="Add Another Child"/>
<div class="spouce_children">
<?php //add the inputs here?>
</div>
I would like to thank you for any help you can / will provide <3
Error Occurs here:
<?php foreach($_SESSION['spoucechild'] as $index=>$child){ ?>
#Xavier: You could try --
<?php
if (isset($_SESSION['spoucechild'])) {
foreach($_SESSION['spoucechild'] as $index=>$child){
echo '<input type="text" name="spoucechild[' . $index . ']" value="' . $child . '" />' . "\n";
}
}
?>

Categories