Invalid argument supplied for foreach() loop - php

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";
}
}
?>

Related

Javascript function inside 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.

Call a javascript function through the use of PHP variables

In the current example I have a form set up that takes a unique id. There is also a link that takes a unique id. The javascript function will fade in that form when the link is selected. Is it possible to call a javascript function based on the PHP variables used to id the form and the link? And so that it will fade in the correct when that corresponds to the unique id of the form?
PHP
while($row = mysql_fetch_array($query)){ $form_id = $row[id]; ?><a href="#"
id="askedClick"><?php echo $row[post_text].'<br>'?></a>
<form action="<?php $curent_file ?>"
method="POST" id="<?php echo $row[id] ?>">Do you know the anwer?
<input type="submit" value="Yes" name="<?php echo $form_id.'yes'?>"
/>
<input type="submit" value="No" name="<?php echo $form_id.'no'?>" />
</form>
<?php } ?>
JAVASCRIPT
$(document).ready(function () {
$("phpvariable").hide();
$("#phpvariable").click(function () {
$("#phpvariable").fadeIn(1200)
});
});
You could use ids, but it will be much easier to just give your link a class of say "showForm" and use HTML traversal to hide the form that follows it
$('.showForm').click(function(){
$(this).nextAll('form').first().fadeIn();
});
You can use the echo php statement. Example below:
echo '
$(document).ready(function () {
$("#' . $phpvariable . '").hide();
$("#' . $phpvariable . '").click(function () {
$("#' . $phpvariable . '").fadeIn(1200);
});
});';
I found a much easier method of doing this, thought I should I go back and put this in for reference
//Javascript
$(".testLink").click(function() {
var linkId = $(this).attr('id');
$("#testDiv"+linkId).fadeIn(400)
});
//PHP
for ($i = 0;$i < /*whatever*/; $i++){
?>
Click Here
<div style="display:none;" id="<?php echo 'testDiv'.$i ?>" >
Unique Data
</div>
<?php
}
In this method, a unique id is created between the link clicked, and the element to be manipulated in the javascript. This way each link can be of the same class, but each will have a unique id associated with its corresponding element, i.e div, form, span etc.

JavaScript element style change with dynamic id

I am trying to put a line through a list item when the check box next to it is checked. I have managed to do it but I can't check if the the box is checked.
JS File
if(document.getElementById(theID).checked){
document.getElementById(theID).setAttribute("style", "text-decoration:line-through");
}
HTML/PHP
echo'<ol>';
foreach($to_do_XML->task as $item)
{
$theID = $item['id'];
echo '<li id="'.$theID.'">'.$item.'</li>' ;?><form ><input onclick="return cross('<?=$theID?>');" type="checkbox" name="done<?php $li_id_num_done ?>"/></form>
<?php
}
echo '</ol>';
i should also add that the list item is being added within a foreach loop looping trough xml elements
The above code does nothing any help would be appreciated
If $theID is a string, you need quotes around it:
<input onclick="return cross('<?php echo $theID; ?>');" type="checkbox" name="done<?php $li_id_num_done ?>"/>
Also remove this from your function:
got_elements_id
It will cause a reference error.
This would be better I believe:
echo '<li id="'.$theID.'">'.$item.'</li>' ;?>
<form >
<input onclick="return cross('<? echo $theID; ?>');" type="checkbox" name="done<?php $li_id_num_done ?>"/>
</form>
And
function cross( id ){
var element = document.getElementById( id );
if( element.checked){
element.style.textDecoration = "line-through";
}
}
Or even:
function cross( id ){
var element = document.getElementById( id );
element.style.textDecoration = element.checked ? "line-through" : "";
}
Which also enables unchecking and removing the linethrough.

How to add a very dynamic inputs in the dynamic divs by jQuery

I have php code similar to this below:
foreach ($questions as $q){
foreach ($answers as $a)
{
echo '<input type="text" id="'.$a['question_id'].'_'.$a['id_answer'].'" value="'.$a['answer'].'" />';
echo '<div id="newAnswerTextBox'.$a['question_id'].'">';
}
echo '<button id="addNewAnswer'.$q['id_question'].'">Add new answer</button>';
}
exemplary output:
<input type="text" id="1_1" value="question1 answer1">
<input type="text" id="1_2" value="question1 answer2">
<input type="text" id="1_3" value="question1 answer3">
<div id="newAnswerTextBox1">
<button id="addNewAnswer1">Add new answer</button>
<input type="text" id="2_4" value="question2 answer4">
<input type="text" id="2_5" value="question2 answer5">
<input type="text" id="2_6" value="question2 answer6">
<div id="newAnswerTextBox2">
<button id="addNewAnswer2">Add new answer</button>
desired extra input after clicking first button "Add new answer":
<input type="text" id="1_4" value=" ">
The main question is how to add by jquery new inputbox.
I can't find similar solution I'm learning yet jquery.
I found this below but I need to add dynamic input in right div.
var num = 0;
$("#addNewAnswer").click(function() {
num++;
$("#newAnswerTextBox").html("<input type=\"text\" id=\"" + num + "\" />");
});
First give all button a common class say add_answer
Second on click of the button add textbox to its parent div like this
var num = 0;
$(".add_answer").click(function() {
num++;
$(this).parent().append("<input type=\"text\" id=\"" + num + "\" />");
});
$("button[id^='addNewAnswer']").click(function(){
var p = new RegExp(".*?(\\d+)",["i"]);
var questionID = parseInt(p.exec(this.id)[1]);
var answerID = parseInt($("input[id^='"+questionID+"_']:last").attr("id").split("_")[1]);
answerID++;
var newTextBoxID = questionID +"_"+answerID;
$("<input/>").attr({"type":"text","id":newTextBoxID}).insertBefore("#newAnswerTextBox"+questionID);
});
DEMO
Simply add tell javascript what was the last number that entered, using PHP:
foreach ($questions as $q){
foreach ($answers as $a)
{
echo '<input type="text" id="'.$a['question_id'].'_'.$a['id_answer'].'" value="'.$a['answer'].'" />';
echo '<div id="newAnswerTextBox'.$a['question_id'].'">';
}
echo '<script type="text/javascript">var num'.$q['id_question'].' = '.count($answers).';';
echo '<button id="addNewAnswer'.$q['id_question'].'">Add new answer</button>';
}
Or something similar...
Good luck :)
First of all you have to close the "newAnswerTextBox" divs. Replace the following line:
echo '<div id="newAnswerTextBox'.$a['question_id'].'" />';
And the solution of jimy is just fine.

Change a buttons value if parameters are met, jQuery, PHP, Sessions

I have the following button:
<input type="button" count='<?php echo count($_SESSION['children']);?>' name="children" class="add_child" value="Add Another Child"/>
On default when the form loads (with a clean session) there is no input for children, so the button should read "Add a Child".
If there is a text field present with the name children[] then it should just display: "Add another Child".
How would this be done ?
I am using php / jquery / sessions for the fields here is the code for it:
$('.add_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.children_form').append($('<li />').append(input));
$('#content li:odd').addClass('alt');
})
<?php
if(isset($_SESSION['children'])) {
foreach($_SESSION['children'] as $index=>$child){ ?>
<li>
<?php echo "<input type='text' name='children[{$index}]' value='{$child}'/>";?>
</li>
<?php } }?>
Try this out with the code you have already:
$('.add_child').click(function(){
//code...
$(this).val('Add Another Child');
})
and the php for the input:
<input type="button" count='<?php echo count($_SESSION['children']);?>'
name="children" class="add_child"
value="<?php echo (isset($_SESSION['children'])?
'Add Another Child':'Add a Child');?>"
/>

Categories