Ok, this situation is a little weird but anyway. This PHP code generates several radiobuttons:
for($i = 0; $i<count($questionList); $i++)
{
echo $questionList[$i]->__get(QuestionId).'-'.$questionList[$i]->__get(QuestionText).'<br />';
$answerList = $questionList[$i]->GetAnswers();
for($j = 0; $j<count($answerList); $j++)
{
echo '<br /><input type=\'radio\' name=\'group'.$i.'\' id=\'radioButtonAnswer'.$answerList[$j]->__get(AnswerId).'\' value=\''.$answerList[$j]->__get(AnswerId).'\' >'.
$answerList[$j]->__get(AnswerText).'</input>';
}
echo '<br /><br />';
}
Ok, that works fine, after the checkboxes are created, I'm trying to run some code to get all the radio buttons and it didn't work, so I tried just getting one radio button several times, and it only gets it the first time.
function Validate()
{
var i = 1;
do
{
document.writeln(document.getElementById('radioButtonAnswer2') == null);
i ++;
}while(i < 10);
document.writeln('out of loop');
return false;
}
So I know FOR SURE that 'radioButtonAnswer2' exists and it shouldn't be null. But this is what I get when I click the submit button:
false true true true true true true true true out of loop
The first time is not null, but after that, it is. Any thoughts?
Thanks!
You can use document.getElementsByName("group") to get all the radio buttons.
This loop works fine. The problems is with document.writeln(), it replaces the html in the page and therefore the DOM elements are gone. Here's an updated version using an Alert instead.
function Validate(){
var radioGroup = document.getElementsByName("group");
var results = "";
for(i = 0, len = radioGroup.length; i < len; i++){
currentRadio = radioGroup[i];
results += "\n" + currentRadio.id + " is ";
results += (currentRadio.checked ? "checked" : "not checked");
}
results += "\n..out of loop...";
alert(results);
return false;
}
It may be because your HTML you are generating is invalid. You also shouldn't be explicitly calling the __get() function, but that's an unrelated issue most likely.
Something like:
<input type="radio" ...>Label Text</input>
is not the correct way to define a radio button.
Try this code:
for($j = 0; $j<count($answerList); $j++)
{
echo '<br /><input type="radio" name="group'.$i.'" id="radioButtonAnswer'.$answerList[$j]->AnswerId.'" value="'.$answerList[$j]->AnswerId.'" />';
echo '<label for="radioButtonAnswer'.$answerList[$j]->AnswerId.'">'.$answerList[$j]->AnswerText.'</label>';
}
Edited to add: Ah, now I see. You're using document.writeln(). That function overwrites the content of the page.
So the first time into the loop, the element does exist, and it does a document.writeln() call, which writes "true" to the page. This overwrites everything that was on the page before (didn't you notice how when the page loads, it only has the output of the javascript?). The next time through the loop, it tries to look for the radio button again, but it's been erased and replaced with the javascript output. Now it no longer exists.
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.
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 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
}
Hello i want any checkbox i am gonna check, to stay checked after pagination.
here is the code:
foreach($test as $string){
$queryForArray = "SELECT p_fname,p_id FROM personnel WHERE p_id = " .$string["p_id"]. " ;" ;
$resultForArray = mysql_query($queryForArray, $con);
$rowfForArray = mysql_fetch_array($resultForArray);
?>
<td id="<?php echo $rowfForArray["p_id"]?>" onclick="setStyles(this.id)" ><?php echo $rowfForArray["p_fname"]?></td>
<td><input id="<?php echo $rowfForArray["p_id"]?>" class="remember_cb" type="checkbox" name="how_hear[]" value="<?php echo $rowfForArray["p_fname"]?>"
<?php foreach($_POST['how_hear'] as $_SESSION){echo (( $rowfForArray["p_fname"] == $_SESSION) ? ('checked="checked"') : ('')); } ?>/></td>
</tr>
<tr>
I am geting the data from a search result i have in the same page , and then i have each result with a checkbox , so that i can check the "persons" i need for $_Session use.
The only think i want is the checkbox's to stay checked after pagination and before i submit the form!(if needed i can post the pagination code, but he is 100% correct)
In the checkbox tag use the ternary operation, without that foreach inside him:
<input [...] value="<?php echo $rowfForArray["p_fname"]?>" <?php $rowfForArray["valueToCompareIfTrue"] ? "checked='checked'" : ''; ?> />
because the input already is inside of 'for' loop, then each time of the loop will create a new checkbox wich will verify if need to being check or not.
I hope I have helped you.
A few ways to tackle this:
(Straight up PHP): Each page needs to be a seperate form then, and your "next" button/link needs to submit the form everytime they click next. The submit data should then get pushed to your $_SESSION var. The data can then be extracted and used to repopulate the form if they navigate backwards as well. Just takes some clever usage of setting the URL with the proper $_GET variables for the form.
(HTML5): This will rely more on JavaScript, but basically you get rid of pagination and then just break the entire data set into div chunks which you can hide/reveal with JavaScript+CSS or use a library like JQuery.
(AJAX): Add event listeners to the checkboxes so that when a button is checked an asynchronous call is made back to a PHP script and the $_SESSION variable is updated accordingly. Again, this one depends on how comfortable you are with JavaScript.
Just keep in mind that PHP = ServerSide & JavaScript = ClientSide. While you can hack some PHP together to handle "clientside" stuff, its usually ugly and convoluted...
I did it without touching the database...
The checkbox fields are a php collection "cbgroup[]".
I then made a hidden text box with all the values which equal the primary keys of the selectable items mirroring the checkboxes. This way, I can iterate through the fake checkboxes on the current page and uncheck the checkboxes by ID that exist on the current page only. If the user does a search of items and the table changes, the selectable items remain! (until they destroy the session)
I POST the pagination instead of GET.
After the user selects their items, the page is POSTED and I read in the hidden text field for all the checkbox IDs that exist on that current page. Because PhP only tells you which ones are checked from the actual checkboxes, I clear only the ones from the session array that exist on the POSTED page from this text box value. So, if the user selected items ID 2, 4, 5 previously, but the current page has IDs 7,19, and 22, only 7, 19, and 22 are cleared from the SESSION array.
I then repopulate the array with any previously checked items 7, 19, or 22 (if checked) and append it to the SESSION array along with 2, 4, and 5 (if checked)
After they page through all the items and made their final selection, I then post their final selections to the database. This way, they can venture off to other pages, perhaps even adding an item to the dB, return to the item selection page and all their selections are still intact! Without writing to the database in some temp table every page iteration!
First, go through all the checkboxes and clear the array of these values
This will only clear the checkboxes from the current page, not any previously checked items from any other page.
if (array_key_exists('currentids', $_POST)) {
$currentids = $_POST['currentids'];
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$removeItems = explode($delimiter, $currentids);
foreach ($removeItems as $key => $del_val) {
//echo "<br>del_val: ".$del_val." - key: ".$key."<br>";
// Rip through all possibilities of Item IDs from the current page
if(($key = array_search($del_val, $itemList)) !== false) {
unset($itemList[$key]);
//echo "<br>removed ".$del_val;
}
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
// Leaves the previous paged screen's selections intact
$newSessionItems = implode(",", $itemList);
$_SESSION['materials'] = $newSessionItems;
}
}
}
Now that we have the previous screens' checked values and have cleared the current checkboxes from the SESSION array, let's now write in what the user selected, because they could have UNselected something, or all.
Check which checkboxes were checked
if (array_key_exists('cbgroup', $_POST)) {
if(sizeof($_POST['cbgroup'])) {
$materials = $_POST['cbgroup'];
$N = count($materials);
for($i=0; $i < $N; $i++)
{
$sessionval = ",".$materials[$i];
$_SESSION['materials'] = $_SESSION['materials'].$sessionval;
}
} //end size of
} // key exists
Now we have all the items that could possibly be checked, but there may be duplicates because the user may have paged back and forth
This reads the entire collection of IDs and removes duplicates, if there are any.
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$filtered = array();
foreach ($itemList as $key => $value){
if(in_array($value, $filtered)){
continue;
}
array_push($filtered, $value);
}
$uniqueitemschecked = count($filtered);
$_SESSION['materials'] = null;
for($i=0; $i < $uniqueitemschecked; $i++) {
$_SESSION['materials'] = $_SESSION['materials'].",".$filtered[$i];
}
}
}
$_SESSION['materials'] is a collection of all the checkboxes that the user selected (on every paged screen) and contains the primary_key values from the database table. Now all you need to do is rip through the SESSION collection and read\write to the materials table (or whatever) and select/update by primary_key
Typical form...
<form name="materials_form" method="post" action="thispage.php">
Need this somewhere: tracks the current page, and so when you post, it goes to the right page back or forth
<input id="_page" name="page" value="<?php echo $page ?> ">
if ($page < $counter - 1)
$pagination.= " next »";
else
$pagination.= "<span class=\"disabled\"> next »</span>";
$pagination.= "</div>\n";
Read from your database and populate your table
When you build the form, use something like this to apply the "checked" value of it equals one in the SESSION array
echo "<input type='checkbox' name='cbgroup[]' value='$row[0]'";
if (isset($filtered)) {
$uniqueitemschecked = count($filtered);
for($i=0; $i < $uniqueitemschecked; $i++) {
if ($row[0] == $filtered[$i]) {
echo " checked ";
}
}
}
While you're building the HTML table in the WHILE loop... use this. It will append all the select IDs to a comma separated text value after the loop
...
$allcheckboxids = "";
while ($row = $result->fetch_row()) {
$allcheckboxids = $allcheckboxids.$row[0].",";
...
}
After the loop, write out the hidden text field
echo "<input type='hidden' name='currentids' value='$allcheckboxids'>";
My php code:
for($i = 1; $i < 22; $i++) {
echo '<div id="number" style="display:none">'.$i.'</div>';
}
My jquery code:
$('#number').each(function() {
$(this).slideDown("slow");
})
What's wrong here? I want to achieve effect when all numbers, each after another would appear. I mean, first of all slides down number 1, after him number 2 and so on. And now only slides down number 1 and after him nothing happens although I use jquery each. Thank you.
There may only be one id="number" in your code. IDs are unique. Use class="number" instead.
That is:
Your PHP-Code:
for ($i = 1; $i < 22; $i++) {
echo '<div class="number" style="display:none">'.$i.'</div>';
}
Your JS-Code:
$('.number').each(function() {
$(this).slideDown("slow");
});
First, your PHP needs a change, it's rendering invalid HTML, so this:
for($i = 1; $i < 22; $i++) {
echo '<div id="number" style="display:none">'.$i.'</div>';
}
Need to be something like this (or remove the id completely if it's not needed):
for($i = 1; $i < 22; $i++) {
echo '<div id="number'.$i.'" class="number" style="display:none">'.$i.'</div>';
}
Then your jQuery should be something like this:
$('.number').each(function(i) {
$(this).delay(600*i).slideDown("slow");
});
You can view a demo here
This will show the first immediately, the second 600ms later (speed "slow" = 600ms), the third after 1200ms, etc, so they'll happen one after the other. All we're doing is using .delay() and passing the index of the element in the set times the animation duration, so they occur in order.
IDs are meant to be unique. Use a CSS class (and corresponding selector ".number") instead.
Once you have them all showing, i'm guessing they'll be showing up all at once. In order to fix that, you'll probably need to create a function that slides in the next number and sets a timeout to call itself again. Like,
function slideNext()
{
$(".number:first").each(function() {
$(this).slideDown("slow").removeClass("number");
window.setTimeout(slideNext, 1000);
});
}
$(document).ready(slideNext);
Note, this is not tested, and i am not by any means a jQuery guru.
You are creating multiple elements with the same id attribute. this is illegal according to the HTML spec and is preventing your jQuery selector from being able to determine which element you are trying to access. Try using a class attribute instead and using $('.number')
You can't have more than one element with the same ID. You need to use a class instead:
PHP
for($i = 1; $i < 22; $i++) {
echo '<div class="number" style="display:none">'.$i.'</div>';
}
Jquery:
$('.number').each(function() {
$(this).slideDown("slow");
})
Use a class instead of an id as id must be unique. I've tried it with class and it worked.
PHP:
for($i = 1; $i < 22; $i++) {
echo '<div class="number" style="display:none">'.$i.'</div>';
}
jQuery:
$('.number').each(function() {
$(this).slideDown("slow");
})
Cool effect! Good luck!
hey - this wouldn't work basically because the id has to be unique, thus the code isn't going to work. it might work if you were to use a class rather than an id (i.e. <div class="number").
haven't tried it - so just a thought really..
jim
It's true that according to spec there is should be only one element with given ID, but you can overcome it by doing:
$( "*[id='number']").each(function() {
$(this).slideDown("slow");
});
hey, for the delay, try this:
$('.number').each(function(i) {
setTimout($(this).slideDown("slow"), i*250);
});
you never know...