I have a couple of checkboxes and I want to execute a function for each of the elements marked as checked. How can I do this?
In my particular case, I think this might be a little bit easier, because the checkboxes are constructed like this:
$get_json_values=json_decode($json_string,true);
foreach ($get_json_values as $key=>$getlikes) {
if($getlikes['type']=='like') {
?>
<div>
<input type="checkbox" name="<?php echo $getlikes['name'] ?>" value="<?php echo $getlikes['id'] ?>" checked>
<a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
<?php echo $getlikes['name'] ?> </a>
</div>
<?php
}}
?>
So I think it should look like this:
function doIfChecked()
{
foreach ($get_json_values as $key=>$getlikes) {
if($getlikes['type']=='like'&&<sequence that checks if checkbox is checked>)
{//do stuff}
}
}
Can anyone please help?
Thanks to Julian H. Lam, I found a good answer, but my problem is that for each of the elements , I need to do a request to the server (like a page on facebook), but I can't put any php inside javascript.
So, how could I do that since php is not allowed inside js?
Using javascript:
var checkboxes = document.querySelectorAll('input[type="checkbox"]'),
numCheckboxes = checkboxes.length,
x;
for(x=0;x<numCheckboxes;x++) {
if (checkboxes[x].checked === true) {
// add code here to be done for each checked element
// you can refer to the checked element by calling "checkboxes[x]"
}
}
Related
I have a form like so:
<?php if (isset($_POST['artist'])) {
// do something
} ?>
<form name="admin_on_artist_<?php echo $artist->ID; ?>" action="" method="POST">
<p class="artist-negative">
<label for="artist"><input type="checkbox" name="artist_<?php echo $artist->ID; ?>" id="artist_<?php echo $artist->ID; ?>"> Check this?</label>
</p>
<button type="submit">Update</button>
</form>
On the page in question, this form is shown many times in a foreach loop. However, when I submit any given form, it updates all of the forms, which is not what I want.
How can I append the $artist->ID to $_POST['artist'] so that I get something like:
$_POST['artist_1'] to match the checkbox attributes?
You could pair your foreach that generates the frontend form markup with a foreach that processes the form submission. Something like:
<?php
$regex = '/^artist_([0-9]+)$/'
foreach (array_keys($_POST) as $key) {
if (preg_match($regex,$key,$matches)) {
$artistId = (int)$matches[1];
// do something with $_POST[$key] according to $artistId
}
}
This works for a single field submission or a multiple field submission.
Alternatively, you could do something on the frontend in JS (as #smith suggests in the comments) to ensure the form submission always has the same, well-known keys, populating a hidden form with the current submission. With this approach you would have to add another field to the form that contains the ID.
The solution for this was much simpler than I was able to grasp at first, but basically I just had to do this, the key difference between this and my original question being the first two lines:
<?php $artist_form_id = 'artist_'.$artist->ID;
if (isset($_POST[$artist_form_id])) {
// do something
} ?>
<form name="admin_on_artist_<?php echo $artist->ID; ?>" action="" method="POST">
<p class="artist-negative">
<label for="artist"><input type="checkbox" name="artist_<?php echo $artist->ID; ?>" id="artist_<?php echo $artist->ID; ?>"> Check this?</label>
</p>
<button type="submit">Update</button>
</form>
How do I check another checkbox when I toggled an other checkbox?
My code looks like this:
<form method="post"><input type="checkbox" name="checkall" value = "POST" />
</form>
<?php
foreach($records as $r){
if(isset($_POST["checkall"]) == 'POST'){
$chc = "checked = 'checked'";
}
else{
$chc = "";
}
}
?>
<form method="POST">
<input type="checkbox" name="<?php echo escape($r->id); ?>" class="check" value="POST" <?php echo $chc ;?> />
</form>
The code doesn't work can anybody help me please.
Thanks a lot!
Job
...
foreach($records as $r){
if($_POST["checkall"] == 'POST')
{
...
isset() function will tell you $_POST['checkall'] is there or not and also checks it has a value in it or not.
if you want to comapare $_POST['checkall'] with some value, you have to just compare like example above. If you want both, then use two if conditions like below
...
foreach($records as $r)
{
if(isset($_POST['checkall'])
{
if($_POST["checkall"] == 'POST')
{
...
...
}
}
That would help you. First of all, before putting up the codes, plan a structure of your page, what you have to do and what visitors have to do. WIthout plan, you will end up reaching nowhere and stuck. The code you have presented is not recommended.
If you put some more codes in your questions, we could help you to some extent.
Below is a script to upload images and save them to the DB.
On one page of the website, there's a table and inside each <li></li>, there is an upload icon where users can add one image.
The issue is the image upload only works for the "highest" empty <li> on the table.
Here, "highest" means the latest <li> saved in the DB (table is sorted by TIME DESC).
For instance, if I want to upload an image to a random <li></li> on the page, once I select an image, nothing happens. But if I select the "highest" empty (empty = no image saved in DB) <li></li>, it works like a charm.
HTML:
<li id="entry<?php echo $recipe_id ?>">
<div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
<form id="upload_icon" action="upload_extra.php" method="POST"
enctype="multipart/form-data">
<input class="upload" id="file" type="file" style="display:none" />
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
<img class="upload_icon" src="/upload_icon.png">
</form>
</div>
</li>
JAVASCRIPT (upload gets triggered as soon as one image is chosen):
<script>
$('.upload_icon').click(function(){
$(this).parent().find('.upload').click();
});
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
</script>
PHP:
<?php
include "includes/connnect.php";
$id = $_SESSION['id'];
$recipe_id = mysql_real_escape_string($_POST['recipe_id']);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$recipe_id= $_POST['recipe_id'];
//get image attributes
$add = query("UPDATE cookbook SET recipe_pic = '".$location."' WHERE recipe_id =
'$recipe_id'");
header(Location:"home.php");
}
?>
What's going here ?
There are many, many problems with your question. First of all the HTML you've posted is invalid. I suspect that your Javascript code has a problem with such invalid HTML. However, the following code has not (for your HTML code duplicated once for demonstration purposes):
NodeList.prototype.forEach = Array.prototype.forEach;
document.querySelectorAll('input[type="file"]').forEach(function (file) {
var click = function() {
file.click();
};
var change = function() {
console.log('change:', file.value);
};
file.form.querySelector('img').addEventListener('click', click);
file.addEventListener('change', change);
});
http://jsfiddle.net/eBLL5/
All you need is to assign the correct listeners to the correct elements, as you can see, I do not use any ID values because they are duplicated.
I can use as well duplicate IDs in case you think this is not an argument, this is demonstrated in a related answer:
remove text from multiple spans having same id
I hope this helps you to get the feets again on the ground so that you can continue to validate the HTML and clean up a little bit.
It appears that your html form has
<input type="hidden" value="<?php echo $recipe_id; ?>"/>
However, the input field name attribute is not present so the post data stream will not have a definition for $_POST["recipe_id"] field. The undefined value is likely being interpreted by your script as 0 and so only the top or "highest" li image is updated.
If you alter the input field thus:
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
You may have better results...
Just change this part :
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
With :
$("#file").change(function(){$(this).parents("form").get(0).submit();})
In your HTML, you have:
<form id="upload_icon" action="upload_extra.php" method="POST"
enctype="multipart/form-data">
Then your Javascript mentions:
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
According to some specifications (HTML4, HTML5), there shouldn't be same IDs on multiple elements. So, when you use an iteration, avoid printing ids without appending something unique on them, like:
<form id="upload_icon<?php print $recipe_id; ?>"
action="upload_extra.php" method="POST" enctype="multipart/form-data">
Your Javascript can be turned into something like the following. (please mind that you need to call this function after the page is loaded)
function afterPageLoad() {
var buttons = document.getElementsByClassName("upload");
for (i = 0; i < buttons.length; i++) {
buttons[i].onchange = function() {
this.form.submit();
}
}
}
Now, if your PHP code has stopped working, we would need to see that, too, at the part you omitted by writing
//get image attributes
where the $location variable is initiated.
In JavaScript provided its submitting the form by finding the element by ID, As in the HTML code the IDs are repeating (not a standard method, IDS can't repeat but class can) so the browser will always submit the last (highest) form only, that's why when adding image to highest row its working and in between its not.
Please check this code out
<script>
$(document).ready(function()
{
id = '';
$('.upload_icon').click(function(){
id = $(this).attr('id');
$(this).parent().find('#file'+id).click();
});
$(".upload").change(function () {
$('#upload_icon'+id).submit();
});
});
</script>
<style>
.upload_icon {
cursor:pointer;
}
</style>
<ul>
<?php for($recipe_id=1;$recipe_id<10;$recipe_id++): ?>
<li id="entry<?php echo $recipe_id ?>">
<div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
<form action="upload.php" method="POST" enctype="multipart/form-data" id="upload_icon<?php echo $recipe_id; ?>">
<input class="upload" id="file<?php echo $recipe_id; ?>" type="file" name="image" style="display:none"/>
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>" />
<img class="upload_icon" src="https://cdn2.iconfinder.com/data/icons/picons-basic-2/57/basic2-036_cloud_upload-128.png" id="<?php echo $recipe_id; ?>">
</form>
</div>
</li>
<?php endfor; ?>
</li>
In the HTMl code I have provided have different IDs for each forms (used the $recipe_id as suffix), when ever click event on the upload icon is fired it will check which upload icon is clicked by its attribute Id and then the respective input type file value is changed by finding the element by Id (used the same $recipe_id as suffix here also). On input type change event also same logic is used to fire the respective form.
I'm creating a test system that is driven by Wordpress where each answer is input with a true/false text box to say whether it's the correct answer of not.
I've created a loop that outputs the answers with a checkbox next to it:
<?php if(get_sub_field('answer_options')): ?>
<?php while(has_sub_field('answer_options')): ?>
<p class="contact-form">
<input style="width: 20px;" type="checkbox" name="CheckboxGroup<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
<?php echo the_sub_field('answer'); ?>
</p>
<?php endwhile; ?>
<?php endif; ?>
How can I add code to that to include whether the answer is the correct one? I can do a conditional statement like the following to check which answer is correct but how can I incorporate that with the code above?
It needs to check which is the correct answer and also whether the user has ticked the correct/incorrect checkbox.
if( get_sub_field('correct') )
{
echo "do something";
}
else
{
echo "do something else";
}
You can't check a user's input directly with php like this.
If you're outputting a form generated by html, it will need to be completed, and then submitted back to the web server.
You can check the answers when they submit the form. It sounds like you want to keep the same form and just mark questions as correct/incorrect.
Solved with the following:
<?php
if( is_array( $_POST['CheckboxGroup'.$counter] ) ) {
foreach($_POST['CheckboxGroup'.$counter] as $value[$counter]) {
if ($answer == $value[$counter]) { ?>
<p><?php $score++;echo $value[$counter]; ?></p><br />
<?php }
}}
?>
Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.