I'm doing this one using PHP.
I'm doing some basic quiz application and it has a backend. On my backend, I am setting up a quiz for students to answer. One of my interface is like this.
If the user checked the box, it means 1950 is the answer. How would I process that one in my database to determine that 1950 has been the answer of the question.
My Database is like this.
tbl_choices
Id,Choice,isAnswer
so ideally, it would be stored like this.
tbl_choices
ID CHOICE isAnswer
001 1900 0
002 1800 0
003 1950 1
004 1850 0
My question here is how would I code it in a sense when a user will check the checkbox and the textinput right beside it will have a value of isAnswer as 1.
Just an additional info: When a user will click that + button it will add a new textinput and if user will click - button it will delete a textinput, but I got that all covered.
The choices are dynamic, it will changed, that above that I've shown you is just an example.
P.S: Sorry for the title, I don't know what's the title of this kind of question :-)
Your help would be greatly appreciated and rewarded!
you can try html like this :
<input type="checkbox" value="1900" name="answer1[]">
<input type="text" value="1900" name="answer2[]" />
<input type="checkbox" value="1800" name="answer1[]">
<input type="text" value="1800" name="answer2[]" />
<input type="checkbox" value="1950" name="answer1[]">
<input type="text" value="1950" name="answer2[]" />
<input type="checkbox" value="1850" name="answer1[]">
<input type="text" value="1850" name="answer2[]" />
and then use php code:
foreach($_POST['answer2'] as $v){
if(in_array($v, $_POST['answer1'])) {
$s = 1;
}else
$s = 0;
$sql = "INSERT INTO table VALUES(null, $v, $s)";
}
also on click plus update values of both check box and text field
in general you can use checkboxes as an array when submiting information, just name the checkboxes as an array like
<input type="checkbox" value="1900" name="answer1[]">
<input type="checkbox" value="1800" name="answer1[]">
<input type="checkbox" value="1950" name="answer1[]">
<input type="checkbox" value="1850" name="answer1[]">
then on the server side you handle $_POST["answer1"] as an array and cycle through the possible answers, something like this
if (is_array($_POST["answer1"]))
{
foreach($_POST["answer1"] as $answer)
{
// insert into database here
}
}
important: this will only show what a user actualy selected, if an option is not clicked then it will not be part of the array
I think it would make sense to have more than one table, one for the questions with their options and then one for the answers with the fields id, choice_id. Otherwise it is going to make generating the questions a lot more difficult especially when a number of students answer the same question?
One more thing, you could add up in the answers of your question, add row and delete row based on + and - button.
The code for that:
<script type="text/javascript">
$(document).ready(function() {
$("#plus").click(function() {
$('#mytable2 tbody>tr:last').clone(true).
insertAfter('#mytable2 tbody>tr:last');
$('#mytable2 tbody>tr:last #st').val('');
$('#mytable2 tbody>tr:last #newst').val('');
$('#mytable2 tbody>tr:last #plus').val('+');
return false;
});
});
for more detail, you may refer following link:
Add Row on Button click
Related
Good day!
Im currently having problems with inserting values with checkbox and hidden field. Any tips or solutions are greatly appreciated.
So my problem is this: I have a form with only checkboxes in it and a submit button and If I check one of the values in a checkbox a hidden upload field will be displayed the hidden value must be connected to the chosen value in the checkbox. How can I insert the hidden value to the corresponding checkbox value in a database. For example
HTML:
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue">
Value 1
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue">
Value 2
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
PHP:(Updated) This is what I have now. when I dont check the 1st checkbox. the hidden_one in the 2nd checkbox isnt inserting
foreach($_POST['value'] as $key=>$value ){
$hidden_one = $_POST["hidden_one"][$key];
$sql = "INSERT INTO sample (value, hidden_one) VALUES ('$value','$hidden_one')";
$result = mysqli_query($connection, $sql);
}
If I check value 1 and entered a sample1 in the hidden form and I check value 2 and entered a sample2 in the hidden form. sample 1 must be in the same column as value 1 and sample 2 must be in the same column as value 2. its not inserting properly
UPDATE:
So I changed the code into this
foreach($_POST['value'] as $key=>$value ){
$hidden_one = $_POST["hidden_one"][$key];
but the problem is sometimes its not inserting correctly. Sometimes hidden_one is empty in the database. I'm really lost at the moment. Can't find a solution elsewhere.
This is my updated form
Im seeing a pattern, when I skipped a checkbox like I check value1 then skip value2 then check value3. value3 hidden isn't inserted. Still not solved :( lol this is driving me crazy. at the verge of quitting. lol
One way you could insert the value of your checkbox into your hidden input fields, is by making a click function that takes $(this).val(), which is your clicked elements value. You can then put that value into a variable. You then go to target the parent element/container for the targeted checkbox and find the corresponding input field. You then simply set the value of that input field with the declared value of the checkbox.
Note that the notation for this JavaScript is in jQuery, and you will need to include a jQuery library in order for this solution to work.
$(document).ready(function () {
$('[name="value[]"]').click(function(){
var mySelect=$(this).val();
if( $(this).prop('checked') ) {
$(this).parent().find('input[name="hidden_one[]"]').val(mySelect);
}
else {
$(this).parent().find('input[name="hidden_one[]"]').val("");
}
})
});
Example:
$(document).ready(function () {
$('[name="value[]"]').click(function(){
var mySelect=$(this).val();
if( $(this).prop('checked') ) {
$(this).parent().find('input[name="hidden_one[]"]').val(mySelect);
}
else {
$(this).parent().find('input[name="hidden_one[]"]').val("");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue 1">
Value 1
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
<label class="form-check-label">
<input class="form-check-input" name="value[]" type="checkbox" value="Venue 2">
Value 2
<div id="hidden_fields">
This is hidden: <input type="text" id="hidden_one" name="hidden_one[]">
</div>
</label>
<br>
Direct JS Fiddle link
When it comes to inserting the value(s) into the database, it's hard for me to give a concise answer, because I don't have any debugging information on your application, so I don't know if you have structered it properly. I would assume you have either an AJAX function or a form action to post your values. As you noted in your own attempt, is that the values come up as an array that you will have to loop through. However, I am uncertain of the nested foreach loops.
Let me know if you need any further assistance, and in that case, update your question with potential error messages, corresponding form/ajax code, and if your PHP file holds any other relevant information, add that too.
A rough example could be:
<?php
$hidden_one_array=array_values($_POST['hidden_one']); //our posted array
$i=0; // iterator
$length=count($hidden_one_array); //length of the array
while($i < $length) {
$sql="INSERT INTO sample (value, hidden_one) VALUES ('$value','$hidden_one_array[$i]')";
$result=mysqli_query($connection, $sql);
$i++;
}
?>
What we're doing here is basically looping through the array, using the iterator value as our index pointer to each respective array index to insert into the database.
Also note that you should probably look into prepared statements to prevent sql injection. You are already using mysqli_ so might as well take advantage of it.
I am trying to edit my form. Currently, i am able to retrieve data into my input textbox but not the checkbox. Now when, i am inserting data, i check the items that i want to insert, get the ids and save into my database.
Now when i want to edit, i want to retrieve the items that i previously selected (the checkbox of which i selected should be checked ).
In my Json below, i am able to display the id of the food that i selected when i was storing. How can i fetch that into my checkbox back
Desired output
I want to have the selected items checked. As in my JSON, i have stored chicken wings. If i click on edit, chicken wings should be checked already.
PS: I am a beginner and my english is not really good.
Controller
$item = Item::findOrFail($id);
return view('edit',compact('item'));
HTML
<div class="panel label_container">
<input onclick="return items(this)" type="checkbox" id="" name="" value="" />
</div>
JSON
If I understood the question correctly, you want to see if chicken wings (or any other food) is set and if it is, output a checked check box.
What you can do is use an if(strlen($json_file['name']) > 0) to see if chicken wings has text or not and then do /> Chicken wings.
Example:
<?php
if(strlen($json_file['name']) > 0) {
?>
<input type="checkbox" <? echo 'checked="checked"'; ?> />
}
?>
I realized that the name could be set but have another name such as chicken breasts instead of wings, you can do an if($json_file['name'] == 'Chicken wings') {}.
Good luck!
this is one of my issue back then in checkbox, you can use tenary to check the checkbox if there is a value for that attribute. Try this one,
<div class="panel label_container">
<input onclick="return items(this)" type="checkbox" id="" name="item_checked" value="1" {{ $item->item_checked ? 'checked' : '' }} />
</div>
Hope this helps :)
I'm working on a PHP self-evaluation form that has 5 question categories with 10 questions each. In the beginning of the application, I have 5 checkboxes to represent these categories, and they are automatically checked. The idea is that whenever user unchecks a category, the questions of that category instantly disappear from the form, and when they check it again, they come back. Something that should be achievable with the help of jQuery and AJAX.
I made the checkboxes with CodeIgniter's form_helper:
for($i = 1; $i<=5; $i++) {
$this->formapp_model->printCatName($i);
$data = array('name'=>'category$i', 'id'=>'category$i', 'value'=>'$i', 'checked'=>TRUE);
echo form_checkbox($data);
}
And I have a function to printing all 10 questions of the category from database after their category id, which works fine when I just post them as they are:
$this->formapp_model->printCategory(1);
$this->formapp_model->printCategory(2);
$this->formapp_model->printCategory(3);
$this->formapp_model->printCategory(4);
$this->formapp_model->printCategory(5);
Using the help of this:
Passing whether a checkbox is checked, via jQuery, to PHP
I was able to gather that for the jQuery, I need something like
var category1 = $('#category1:checked').val();
in order to check if the checkbox has been selected. I also tried
var category1 = $('#category1:checked').post();
as it seemed logical to use post in order to PHP to recognize it.
And for the print selection something like
if (isset($_POST['category 1'])) { $this->formapp_model->printCategory(1); } else { echo "This category is not selected."; }
I tried this, but PHP doesn't recognize the message that jQuery is giving it, meaning the category's questions disappeared permanently, whether the checkbox was checked or not. I checked with echo var_export($_POST); and noticed that all the jQuery is printing out is: array ( ). The question mentioned above was very informative, but missed some info that I would have needed to get it to work. The asker was also using an array instead of separate variables so I don't know how to edit it properly.
I'm a complete newbie with jQuery and AJAX so I have a hard time grasping what I need in order to get jQuery and PHP communicate dynamically the way I described. I have run around stackoverflow to find similar cases, but none of them have quite had what I need. However, I deeply apologize in case this is a repeativive question. Thank you to anyone who helps!
PHP is server side, you need the questions to appear/disappear client side meaning you want to make that happen using jQuery itself (or regular js but since you're already loading jQuery it's quicker just to use the library itself).
To be honest I'm not really following how your view is working so I'll just give some basic code to give you the idea. You create the checkboxes and the questions giving each a unique ID. Then in the on click method for the check boxes you determine which questions to show.
HTML:
<div id="checkboxes">
<input type="checkbox" id="box1" class="check" checked="checked"/>
<input type="checkbox" id="box2" class="check" checked="checked" />
<input type="checkbox" id="box3" class="check" checked="checked" />
<input type="checkbox" id="box4" class="check" checked="checked" />
<input type="checkbox" id="box5" class="check" checked="checked" />
</div>
<div id="question1" class="question">
<p>Question 1</p>
</div>
<div id="question2" class="question">
<p>Question 2</p>
</div>
<div id="question3" class="question">
<p>Question 3</p>
</div>
<div id="question4" class="question">
<p>Question 4</p>
</div>
<div id="question5" class="question">
<p>Question 5</p>
</div>
jQuery:
$(".check").on("click",function(){
var id = $(this).attr("id");
var id2 = id.substr(id.length -1);
var question = "question"+id2;
if($(this).is(":checked"))
{
$("#"+question).css("display","block");
} else {
$("#"+question).css("display","none");
}
});
Demo: http://jsfiddle.net/calder12/taSPX/1
hope everyone is enjoying their day coding so far :D. i'm relatively new to JQUERY and AJAX been trying to find my way around, i'm getting there though. I have one minor problem however. I have HTML content that was generated from a MYSQL database using PHP (so the values for the checkboxes vary); it's a simple internal messaging program that i am working on for my website. I have a single check box that i can click that will select all the other checkboxes on the page. However what i hope to achieve is when ever the user selects a specific amount of check boxes or even a few, then presses a picture it with then call on my php file which will be responsible for deleting the message which the user checked. This previous question helped alot: How to pass jQuery variables to PHP variable? but i have numerous check boxes
HTML/JS:
<body>
Check Box: <input type="checkbox" name="check" value="1">
Check Box: <input type="checkbox" name="check" value="4">
Check Box: <input type="checkbox" name="check" value="3">
Check Box: <input type="checkbox" name="check" value="4">
<img id = "delete" src="http://icons.iconarchive.com/icons/visualpharm/must-have/256/Delete-icon.png">
<script>
$("#delete").click(function () {
$.post('sql_delete.php', 'num=' + $(this).val(), function (response) {
alert(response);
});
});
</script>
</body>
PHP
<?php
require 'functions/init.php';
$messageid = "_$POST[num]";
$sql_statement = "DELETE FROM chj_messages WHERE message_ID = $messageid";
mysql_query($sql_statement);
?>
I suspect that i might need loops in both the JS and PHP not entirely sure though. All your beautiful suggestions are welcomed :D
$messageid = "_$POST[num]"; should be $messageid = $_POST['num'];
Your code will delete one by one checkbox, as the user clicks them. If you want to let users check as many as they want, and then click some button to delete them, you need to remove that click listener from the checkboxes and bind it to a submit button or the image you mentioned. You'll also need to change the way you make your ajax call - you'll have to serialize all the checked ids and send that. Also, the PHP code needs to unserialize that data and make a DELETE query for each received ID.
Also, probably the most important, read about SQL Injection before going live with any site that uses MySQL. And mysql_* functions are deprecated, like it says on php.net, so you better switch to mysqli_* or PDO.
jquery:
$('#your_form').submit(function() {
$.post('sql_delete.php', $("#your_form").serialize(), function (response) {
alert(response);
});
return false;
});
html:
<form id="your_form">
Check Box: <input type="checkbox" name="check[]" value="1">
Check Box: <input type="checkbox" name="check[]" value="6">
Check Box: <input type="checkbox" name="check[]" value="8">
Check Box: <input type="checkbox" name="check[]" value="4">
<input type="image" src="path/to/your/image">
</form>
php:
$messageid = $_POST['check'];
foreach($messageid as $id) {
$sql_statement = "DELETE FROM chj_messages WHERE message_ID = $id";
mysql_query($sql_statement);
}
the edited code above has been tested.
also, the php should probably be done without a loop
$messageid = $_POST['check']; // sql injection already discussed.
$in = implode(", ", $messageid);
$sql_statement = "DELETE FROM chj_messages WHERE message_ID IN ($in)";
mysql_query($sql_statement);
I've this simple form, when the price is set to 120 $:
<input type="checkbox" name="addon[book]" value="120" /> book
<input type="checkbox" name="addon[plane]" value="420" /> Plane
Could I send two values (USD & €) with thr form?
EDIT:
I added name="addon[book]" because I'll display the name too
EDIT 2:
PHP:
foreach($addon as $name => $value) {
echo 'your addons: '.$name;
}
$total = array_sum(array_map("intval", $_POST["addon"]));
echo 'the total '.$total.' $';
<input type="hidden" name="addon[book_USD]" value="250" />
<input type="checkbox" name="addon[book_EUR]" value="120" /> book
However NEVER trust the input from the form. Check the price in the backend code or users can change the price!
EDIT
What about json encoding?
<input type="checkbox" name="addon[book]" value="{"USD":250,"EUR":120}" /> book
EDIT2
To explode the values you'll have to use json_decode()
EDIT3
As others (and myself) already stated what you are trying to do (at least from the looks of it) is that you use the price from the input field as the price the user is going to pay.
That is not the best thing you can do, cause users can easily change the price of the input field.
I don't know your code but somehting like the following would be much better:
<input type="checkbox" name="addon[book]" value="book1">
And in your PHP code:
$prices = array('book1'=>array('USD'=>250, 'EUR'=>120),
'book2'=>array('USD'=>120, 'EUR'=>60),
);