Passing checkbox checked from jQuery to PHP in CodeIgniter - php

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

Related

how to uncheck checkboxes when another is checked?

im kinda trying to get into programming in general and was wondering how to uncheck / check with updating the array-
like as soon as someone checks a 2nd checkbox it should uncheck the first option and update the search (w the new data)- im a mere beginner and kinda lost rn so would appreciate any form of help
<form action="index.php" id="form1" name="form1" method="get">
<?php $i = 0; foreach ($row_page_nav_kategorie as $row_page_nav_kategorie) { ?>
<label class="checkbox-container">
<input <?php if (strpos($url,$row_page_nav_kategorie['typ']) == true) {echo 'checked="checked"';}?>
type="checkbox"
class="checkmark"
name="hotelKategorie[]"
id="ckb5"
value="<?php echo $row_page_nav_kategorie['typ']; ?>"
onclick="kategorie(<?php echo $i ?>);"
onchange="submit()"/>
<?php echo $row_page_nav_kategorie['typ']; $i++;?>
</label>
<?php } ?>
</form>
You should use radio buttons, but if you want to overwrite checkbox functionality below code will take care of it, I have added a common class on your inputs:
function checkboxClick(obj) {
var cbs = document.getElementsByClassName("checkkbox-option");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo
First of all welcome to the community!
As for your question, there is multiple ways to handle this, one of wich is as followed:
In HTML there's an attribute called radio wich you can add to your input by using type='radio'. In a set of radio buttons, only one can be checked at any time. If you then want to immedietely submit your form, you can use something like onChange='this.form.submit()'. This will submit your form when the value is changed, such as pressing on a different radio button.
Something to keep note of is that the attribute onChange is case sensitive as far as i'm aware. You were heading in the right direction with onchange="submit(), but your code doesn't know what to submit. this.form.submit() will submit the form that the element is in.
Use Radio Buttons or use JavaScript on your page to dynamically uncheck other checkboxes when you click on one.
If you want to dynamically update the page content with the new search results you should also look into AJAX which basically means you will call PHP functions from JavaScript code and those will return JSON arrays that you can exploit to modify your page's DOM.
Try THIS
HTML:
<label><input type="checkbox" name="check1" class="checkbox" /> CheckBox1</label>
<label><input type="checkbox" name="check2" class="checkbox" /> CheckBox2</label>
<label><input type="checkbox" name="check3" class="checkbox" /> CheckBox3</label>
<label><input type="checkbox" name="check4" class="checkbox" /> CheckBox4</label>
jQuery:
$(".checkbox").change(function() {
$(".checkbox").prop('checked', false);
$(this).prop('checked', true);
});
if you want to uncheck the selected checkbox
$(".checkbox").change(function() {
$(".checkbox").not(this).prop('checked', false);
});
hope this helps, thanks !!!

Fetching data from database into checkbox

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 :)

Have an issue with javascript Jquery and php buttons for checkbox

I have a problem with this code :
jQuery(".cb-disable").click(function(){
var parent = jQuery(this).parents('.switch');
var vid =this.id;
jQuery('#'+vid).attr('id','');
jQuery('#'+vid).attr('id','');
jQuery('.cb-enable',parent).removeClass('selected');
jQuery(this).addClass('selected');
jQuery('input[name='+vid+'-off]').attr('checked', true)
jQuery('input[name='+vid+'-on]').removeAttr('checked');
jQuery('input[name='+vid+']').attr('name', vid+"-on");
jQuery('input[name='+vid+'-off]').attr('name', vid);
});
});
because this code is correct for the example code below.
<p class="wpptabs_hoverable-286 switch">
<input type="radio" id="ON" class="on286" name="wpptabs_hoverable-286" value="on" checked="checked">
<input type="radio" id="OFF" class="off286" name="wpptabs_hoverable-286-off" value="off">
<label for="ON" id="" class="cb-enable"><span>ON</span></label>
<label for="OFF" id="" class="cb-disable selected"><span>OFF</span></label>
</p>
But it isn't correct. Can you help me?
This code is based on http://devgrow.com/iphone-style-switches/
for php generating a checkbox in table column.
I have question: "What is wrong in this javascript code?".
Sorry for my english, but I rarely write in this language
Your names have to be the same for each radio input, otherwise they act independently (meaning they can show both on and off state) — in the code below I have deleted the -off part in the name for the off radio:
<p class="wpptabs_hoverable-286 switch">
<input type="radio" id="ON" class="on286" name="wpptabs_hoverable-286" value="on" checked="checked">
<input type="radio" id="OFF" class="off286" name="wpptabs_hoverable-286" value="off">
<label for="ON" id="" class="cb-enable"><span>ON</span></label>
<label for="OFF" id="" class="cb-disable selected"><span>OFF</span></label>
</p>
You can see that the on and off buttons now work as expected here:
http://jsfiddle.net/S8qFT/
update
It seems that getting the radios to work wasn't your only issue. I've simplified the javascript so it only does what it needs to, it should work as you required now.
http://jsfiddle.net/65JRx/
javscript
/// make sure we apply the click handling to both on and off labels
$(".cb-enable,.cb-disable").click(function(){
/// find the elements we need
var self = $(this);
var parent = self.parents('.switch');
/// handle the selected highlight, first remove all selected
parent.find('.selected').removeClass('selected');
/// then select the right one again
self.addClass('selected');
/// most modern browsers should handle transfering the label click
/// to the actual radio (via `for` and `id`), but just in case.
if ( self.is('.cb-enable') ) {
parent.find('input[value=on]').prop('checked', true);
}
else {
parent.find('input[value=off]').prop('checked', true);
}
});
markup
<div class="wpptabs_hoverable-286 switch">
<!-- I've laid these inputs out just to make them
easier to read, I wouldn't normally lay markup out
this way //-->
<input
type="radio"
class="on286"
name="wpptabs_hoverable-286"
id="wpptabs_hoverable-286-on"
value="on"
checked="checked"
/>
<!-- I've renamed your IDs to have more specific names
this will mean you can use this method on more than
one set of inputs -- as long as you keep the IDs inline
with your id convention. //-->
<input
type="radio"
class="off286"
name="wpptabs_hoverable-286"
id="wpptabs_hoverable-286-off"
value="off"
/>
<label
for="wpptabs_hoverable-286-on"
class="cb-enable selected">
<span>ON</span>
</label>
<label
for="wpptabs_hoverable-286-off"
class="cb-disable">
<span>OFF</span>
</label>
</div>
css
/**
* Added a highlight so you can see selected working
*/
label.selected { color: blue; }
/**
* I've removed the display none so you can still see the inputs
* working as they should. Obviously you can put the display none
* back to get your working version.
*/
.switch input{/*display: none;*/ opacity: 0.5; position: relative;}

How to store data if checkbox is selected

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

How to change and add new HTML objects with Javascript?

I know a bit of PHP and so also HTML/CSS, and I have made a simple quiz program allowing users to create and do quizzes that are stored in a MySQL database. Now what I am trying to do is improve the usability and efficiency of the program.
On the createQuestions form, there are eight textboxes, users can fill in between 2 or 8 of these boxes with answers. Although I think this looks messy with all eight, and what I would like is to have 2 textboxes, and when there is text in the second one, the third one appears and so on.. up to eight
I spent a few hours learning a bit of basic JS, and managed to get it, so that there was a button that changed the visibility propities of the input box, label and radio button of each row. Although I wrote it really inefficiently lots of lines of code to do not much :p - giving each object a separate ID, and it still didn't work that well.
Below is an example of how my HTML is laid out, I have eight of these, though I could replace this with one, and a PHP for loop with a limit of 8.
<div id="c">
<p class="subFont" id="cT" style="display:none;">Answer 3</p>
<input type="text" name="optionC" class="textbox" style="display:none;" id="cI">
<input type="radio" name="correctAns" value="c" id="cR" style="display:none;">
<input type ="button" name="add" value="d" style="background-color:green;" onclick="addBox('d', 'inline')" id="cB" style="display:none;">
</div>
Any suggestions on how to write the script descried above? Please could you comment or briefly explain your workings, so I can learn from it :)
Thank you loads in advance, I'm so grateful to all you guys on stackoverflow ;)
ps, any suggestions for learning js resources?
Pure Javascript
to hide/show object id="cR"
// hide
document.getElementById('cR').style.display = 'none';
// show
document.getElementById('cR').style.display = 'block';
to append textarea to
document.getElementById('c').innerHTML += '<textarea name=".." id=".."></textarea>';
events:
<input type="text" id="xxx" onchange="your action here" />
jQuery
to hide/show object id="cR"
// hide
$('#cR').hide();
$('#cR').fadeIn(); // with fade in effect
// show
$('#cR').show();
$('#cR').fadeOut(); // width fade out effect
to append textarea to
$('#c').append('<textarea name=".." id=".."></textarea>');
events:
$('#xxx').change(function() {
your action here
});
another way to add element dynamically in page..
<html>
<head>
<script>
function addElement(obj) {
text_limit = 5; // limit text then add text after that.
var text_lenght = obj.value.length;
if(text_lenght >= text_limit){
var mainElement = document.getElementById('myDiv');
var counter= mainElement.getElementsByTagName('textarea').length;
var newTextArea = document.createElement('textarea');
var textareaname = 'txt_area'+counter;
newTextArea.setAttribute('id',textareaname );
newTextArea.onkeydown= function() {
addElement(this);
}
mainElement.appendChild(newTextArea);
}
}
</script>
</head>
<body>
<div id="myDiv">
<textarea id="txt_area2" onkeyup="addElement(this);"></textarea></div>
</body>
</html>

Categories