I'm trying to create a repeatable field (an upload image input with image preview) in PHP using jQuery.clone(). Everything works fine, except the return of the clone data.
In my PHP file, I have:
$i = 0;
$valid_input['image'] = $input['image'][$i];
then
return $valid_input;
used in an image upload input:
<input type="hidden" class="image" name="image[image]['.$i.']" value="'.$theme_options['image'].'" />
<input type="button" class="upload-button button" value="'. __( 'Upload Image', 'theme' ).'" />
the value of $i is set to 0 and counted with jQuery clone.
The problem is that the cloned fields disappear after submitting.
The original field "image['image'][0]" is saved and returns as valid, but the others (image['image'][1], [2], [3]...) don't validate!
If I change the value of $i like this:
$i = 1;
$valid_input['image'] = $input['image'][$i];
then the original input don't submit, only the clone, because the original is [0] and the clone is [1], but after submitting the clone returns as [0].
I tried things like:
$i = 0;
$valid_input['image'] = $input['image'][$i];
$i++; //-- I know, I'm stupid...this will not count the input!
Please, can somebody help me with this?
How can I be able to validate the cloned fields?
My Google searches are all marked as visited and I swear that I did not find anything that could solve this!
Any help would be greatly appreciated, thanks in advance!
Do you mean something like:
for($i = 0; $i < count( $input["image"] ); $i++) {
echo $input["image"][$i];
}
or did i get you wrong
please try with this
using the input name as image[] so you will get the value of image as an simple array by using the foreach you can do you validation.
i.e.,
$arrValue = $_POST['image'];
foreach ($arrValue as $key=>$value) {
//do the operations here
}
Related
How can I get the value of the amp selector and save it in a php variable
<amp-selector multiple layout="container" class="radio-selector"
on="select: AMP.setState({
selectedOption: event.targetOption,
allSelectedOptions: event.selectedOptions
})">
<div option="1">1</div>
<div option="1">1</div>
<div option="1">1</div>
</amp-selector>
<input type="text" name="" [value]="allSelectedOptions.join(' ')">
<?php
$category_id ='"selectedOption"';
// $category_id ='{{selectedOption}}';
// $category_id=remove_special_characters($category_id);
$int = (int) filter_var($category_id, FILTER_SANITIZE_NUMBER_INT);
echo $int;
$filter= get_filter_category($category_id);
?>
I tried multiple ways like domdocument but nothing seems to work.
Any help would be appreciated
$dom = new DOMDocument();
$dom->loadHTML($html);
//$num = "";
$optionTags = $dom->getElementsByTagName('div');
print_r($optionTags);
for ($i = 0; $i < $optionTags->length; $i++ ) {
if ($optionTags->item($i)->hasAttribute('selected')
) {
$num = $optionTags->item($i)->nodeValue;
}
}
echo "Num is " . $num;
Normally you would need this for a form.
Hence you will have a submit button or something similar.
Way to go here is to link your submit button to another file that reads the selection (possible via POST) and redirects you to the desired page.
If you just want to save your selection without doing anything, you could use amp-bind and a JSON Endpoint. The Endpoint gets called when changed, with the selection as parameter and saves it instead of delivering any files what so ever.
Not that sure if this question has been answered somewhere.. have searched for it and found some stuff about it.. but sincerelly don't really understand the answers ive seen and probably am making a major confusion since im not that experienced on working with these languages..
The thing is that i have a group of 5 checkbox's which i want to post in a binary output for example: [0,0,1,1,0].
So far i've managed this by applying the hidden input solution (which i described in a more static way.. since i have a lot of things coming from the db, and other things that dont make sence to explain for this problem.. i think)
$checkychecky = explode(",", [1,0,1,0,0] );
<input type="hidden" name="'.$row_perguntas[0].'[]" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value"'.$checked = ($checkychecky[0] == 1 ? "checked=\"checked\" " : "")/>'.$questionV[1].'
row_perguntas-> comes from the db which gives me the display name
checkychecky -> temp var which stores the values present in the values array [1,0,1,0,0]
questionV -> db label content
which is working just fine.. the problem is when i go forward to another form, and then come back to this form, i get the right arrray values, managed to place the visible checkbox checked, but aint sure on what to do with the hidden field.. since tecnically it isnt set, i dont press the checkbox.. so the onclick doesnt fire.. and when i advance to the next form again i end submiting [0,0,0,0,0]
How should i address this stituation? have tryed to use the.. checkychecky on the hidden input:
<input type="hidden" name="'.$row_perguntas[0].'[]" value="0"'.$value= ($checkychecky[0] == 1 ? "value=\"0\" " : "1")
but no success at all :(
Any ideas? Thanks
Solved..
var checkBQ = ["c0q402","c1q402","c2q402","c3q402","c4q402","c0q408","c1q408","c2q408","c3q408","c4q408"];
var checkBQLength = checkBQ.length;
for (var i = 0; i < checkBQLength; i++) {
if(document.getElementById(checkBQ[i]).checked){
document.getElementById(checkBQ[i]).previousSibling.value = 1;
}else{
document.getElementById(checkBQ[i]).previousSibling.value = 0;
}
}
I'm using a form with checkboxes. Here is part of the code:
if(isset($_POST['send'])){
$grandezas = array('tempCheckbox', "umiCheckbox", "uvCheckbox", "ventoCheckbox", "direcaoventoCheckbox", "precipitacaoCheckbox");
$grandezasCount = 0;
$tamanhoArray = count($grandezas);
for($i = 1; $i <= $tamanhoArray; $i++){
if($_POST[$grandezas[i]])
$grandezasCount++;
echo $grandezas[i]."."; // This gives me null values.
}
echo "<br>".count($grandezas)."<br>";
echo $grandezasCount;
printf("%s", $grandezas[1]);
I have the $grandezas array with the names (already checked and they are right) of the checkboxes i used in my form. They return value 1 when checked. All the rest of the form works perfectly fine with a similar logic.
When i use:
echo "<br>".count($grandezas)."<br>";
printf("%s", $grandezas[1]);
It works right, but the echo inside the for loop keeps giving me null values.
Am i using the $_POST[$grandezas[i]] in the wrong way?
You need to use $i rather than i:
if($_POST[$grandezas[$i]])
$grandezasCount++;
echo $grandezas[$i].".";
Additionally, checkboxes that are not ticked on the form will not show up in your POST results. This means that you merely need to check that the variable exists IF you know the key is going to be a checkbox:
if( isset($_POST[$grandezas[$i]]) ){
//checkbox was ticked
}
I'm trying to cycle through my photo gallery with next / previous buttons. When the user clicks on a photograph it enlarges it. When they click next it should go to the next photo. When the user clicks on the submit button immediately after selecting the photo it will enlarge the next photo. However when they click submit (next) again it doesn't update the $index variable. I know the reason is because once its set the first time the isset($_POST['myNext') evaluates to false. So how can I update $index each time they click on the button. I don't want to use javascript for this because it should be possible with PHP. I also don't want to just copy and paste some JS i don't understand. I've looked online for answers but have found nothing without JS. I've omitted the code to scan the directory with the images. Thank you.
<?php
for($i = 0; $i < count($thumbArray); $i++)
{
$currentIndex = $thumbArray[$i];
echo '<div class = "img"> <img src="'.$dir.$thumbArray[$i].'" alt="Picture" height = "100" width = "100" /> </div>';
}
if(isset($_GET['original_selection']))
{
$original_selection = $_GET['original_selection'];
}
for($i = 0; $i < count($thumbArray); $i++)
{
if($thumbArray[$i] == $original_selection)
$index = $i;
}
?>
<html>
<head><title>Single</title></head>
<body>
<?php
if(isset($_POST['myNext']))
{
echo 'index: '.$index;
$index++;
}
?>
<div class = "img"> <img src="<?= $dir.$thumbArray[$index] ?>" alt = "Picture" height = "500" width = "500" /></div>
<form name="NextForm" method="post">
<br />
<input type="submit" name="myNext" value="Next"/>
</form>
<h1>hi</h1>
</body>
</html>
Have you tried to output what $index is before the if(isset($_POST['myNext']))?
You miss the action parameter in the form tag:
<form name="NextForm" method="post" action="">
^ Doing that will send the form data to the same page.
This seems like very inefficient code I'm allowed to be brutally honest.
for($i = 0; $i < count($thumbArray); $i++)
{
if($thumbArray[$i] == $original_selection)
$index = $i;
}
Why are you searching like that? Not only will it continue to search after it finds it's value, but there are already a php function for this, namely array_search. Also you don't need to loop like that in php, just use the foreach loop. If you really had to do what you tried above, you should have used "break;" inside the if.
Instead of this:
echo 'index: '.$index;
$index++;
You could have just done this:
echo 'index: '.$index++;
EDIT:
Where do you store the thumbarray? This could all have been made much easier and more efficient if you used a database to store the name of the files and gave them for example a group id number, an id etc.
The title is so general mainly because I don't know what should be the appropriate title for it. Let me just explain the situation:
Say that I have two textboxes named LastName0 and FirstName0 and a button called addMore. When I click addMore, another two textboxes will be created through JavaScript. These textboxes will be named LastName1 and FirstName1. When I click the addMore button again, another two textboxes button will be created and named LastName2 and FirstName2 respectively. This will go on as long as the addMore button is clicked. Also, a button named deleteThis will be created alongside the textboxes. This simply deletes the created textboxes when clicked.
I also initialized a variable called counter. Every time the addMore button is clicked, the counter goes up by 1, and whenever the deleteThis button is clicked, the counter decreases by 1. The value of the counter is stored in a hidden input type.
When the user submits the form, I get the value of the counter and create a For loop to get all the values of the textboxes in the form. Here is the sample code:
//Suppose that the user decides to add 2 more textboxes. Now we have the following:
// LastName0 FirstName0
// LastName1 FirstName1
// LastName2 FirstName2
$ctr = $_POST['counter']; //the counter == 3
for ($x = 0; $x < $ctr; $ctr++)
{
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//This will get the values of LastName0,1,2 and FirstName0,1,2
//code to save to database…
}
On the code above, if the value of counter is equal to 3, then the values of textboxes LastName0,1,2 and FirstName0,1,2 will be saved. Now here is the problem: If the user decided to delete LastName1 and FirstName1, the For loop will not be able to iterate properly:
$ctr = $_POST['counter']; //the counter == 2
for ($x = 0; $x < $ctr; $ctr++)
{
//Only LastName0 and FirstName0 will be saved.
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
Someone told me to use the "push and pop" concept to solve this problem, but I am not really sure on how to apply it here. So if anyone can tell me how to apply it, it'll be grand.
Add your input text boxes with name as array ie, <input type="text" name="FirstName[]" />
In php you can fetch them as a array. ie,
foreach($_POST["FirstName"] as $k=>$val){
echo $val; // give you first name
echo $_POST["LastName"][$k]; // will give you last ame
}
In this case even if one set of field is removed in HTML will not affect the php code.
One solution would be to use the isset function like this:
$ctr = $_POST['counter'];
for ($x = 0; $x < $ctr; $ctr++)
{
isset($_POST["LastName$x"])?$lastname = $_POST["LastName$x"]:;
isset($_POST["FirstName$x"])?$firstname = $_POST["FirstName$x"]:;
}
If it is possible, instead of using LastNameN and FirstNameN names try using LastName[N] and FirstName[N], this way the result is an array and you can iterate through it with a foreach, meaning you will not need the counter and the index of the value will not be important:
foreach ($_POST["LastName"] as $i=>$lastname) {
if (!isset($_POST["FirstName"][$i])) {
// This should only happen if someone messes with the client side before posting
throw new Exception("Last name input does not have a related First name input");
}
$firstname = $_POST["FirstName"][$i];
}
If not, then you may have to use your $counter in a different way
$current = 0;
while ($counter) { // Stop only when i found all
if (isset($_POST["LastName$current"]) {
$counter--; // Found one
$lastname = $_POST["LastName$current"];
$firstname = $_POST["FirstName$current"];
}
$current++;
}
A better way to solve this would be to use arrays for Firstname and Lastname. Instead of calling them Lastname0 and Firstname0, then Lastname1 and Firstname1, call them all Lastname[] and Firstname[]. Give them ID's of Lastname0 and Firstname0 and so on for the delete function, but keep the names as arrays.
When the form is submitted use the following:
foreach($_POST['Lastname'] as $i => $lastname) {
$firstname = $_POST['Firstname'][$i]
//... code to save into the database here
}
Be warned though that in IE if you have an empty field it will not be submitted, so if Lastname0 has a value, but Firstname0 does not, then $_POST['Firstname'][0] will in fact contain the value of Firstname1 (assuming it has a value in it). To get around this you can use javascript to check if a field is empty when submitting the form, and if so put the word EMPTY in it.
Do not use counter if not required
A much easier way is to add array name when admore clicked.
Give a name like first_name[] in textbox
if you create form like that you can use foreach through $_POST['first_name']
try var_dump($_POST) in you php code to see how things goes on.
Inside your for loop, maybe you could try...
if ((isset($_POST["LastName$x"])) && (isset($_POST["FirstName$x"]))){
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
This will check if the variables exists before you try to do anything with them.