JQuery get attributes of radio input inside a group - php

Here is my PHP code to generate dynamic form inputs
echo '<div class="radio" id="'.$questionID.'">';
foreach ($options as $key => $opt_value) {
$option_text = $opt_value->option_text;
$question_id = $opt_value->question_id;
$is_correct = $opt_value->is_correct;
$option_id = $opt_value->id;
echo '<label>
<input type="radio" class="optionChecked" name="optionCheck'.$questionID.'" id="'.$option_id.'" value="'.$option_id.'" data-id="'.$option_id.'" data-title="optionCheck'.$questionID.'"><p>
'.$option_text.'</p>
</label>';
}
echo '</div>';
I am generating radio buttons inside div. Each div for a question and the radio inputs are its variable options.
JQuery to get data for each question:
function fetchAttempt(){
var jsonArr = [];
$('.radio').each(function() {
var selected_option = -1;
var is_skipped = 1;
var correct_option = 0;
var quesId = $(this).attr('id');
var quesOptns = "optionCheck"+quesId;
$('.'+questOptns).each(function() {
if(($(this).val()) == 1){
correct_option = $(this).attr("id");
}else{
correct_option = -1;
}
});
jsonArr.push({
correct_option: correct_option,
is_skipped: is_skipped,
correct_option: is_right,
selected_option: selected_option,
temp_id: temp_id,
question_id: quesId
});
});
return JSON.stringify(jsonArr);
}
I struggled for more than 5 hours ... still unable to get the access the checked radio value inside a group.
I tried all possible ways... to get the value of checked radio inside a div by a name ... but it never worked.

I don't have your $options variable, so I created my own questions
form to simulate your situation.
To select a radio button we have only to use this jQuery $("input[type=radio]:checked") then we must check everyone of these checked radio buttons using the function .each().
Here is a full example of what you should do:
$("#submit").on("click",function(){
$("input[type=radio]:checked").each(function(){
console.log($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio" id="form1">
<label>Question 1
<input type="radio" class="optionChecked" name="name1" id="'id1" value="value1" data-id="option1" data-title="question1"></label><br>
<label>Question 2
<input type="radio" class="optionChecked" name="name2" id="'id2" value="value2" data-id="option2" data-title="question2"></label><br>
<label>Question 3
<input type="radio" class="optionChecked" name="name3" id="'id3" value="value3" data-id="option3" data-title="question3"></label><br>
<label>Question 4
<input type="radio" class="optionChecked" name="name4" id="'id4" value="value4" data-id="option4" data-title="question4"></label><br>
<label>Question 5
<input type="radio" class="optionChecked" name="name5" id="'id5" value="value5" data-id="option5" data-title="question5"></label><br>
<button type="button" id="submit"> Submit</button>
</div>

Related

How to display the value of hidden when checkbox is checked in PHP

Im having problem on how to get the value of the hidden input box once the checkbox is checked. here are my code.
<label class="control control--checkbox"><span>Additional</span>
<input type="checkbox" name="apply[]" value=""/>
<input type="hidden" name="option[]" value="1 bottle"/>
<input type="hidden" name="cost[]" value="$20"/>
</label>
<label class="control control--checkbox"><span>Additional</span>
<input type="checkbox" name="apply[]" value=""/>
<input type="hidden" name="option[]" value="3 bottle"/>
<input type="hidden" name="cost[]" value="$50"/>
</label>
My Php code:
<?php
$options = $_POST['option'];
$costs = $_POST['cost'];
$apply = $_POST['apply'];
if (isset($apply)) {
foreach ($options as $option) {
echo '<tr>';
echo '<td>'.$option.'</td>';
echo '</tr>';
}
}
?>
It seems that the option of my php code is always two, i want only to display that was checked and dont display that are not.
can someone advise me on how can i solve this problem or any work around to get the same result?
Using PHP you need to set the CheckBox value and then are able to find the other values.
<input type="checkbox" name="apply[]" value="y"/>
PHP
$options = $_POST['option'];
$costs = $_POST['cost'];
$apply = $_POST['apply'];
if(isset($apply)) {
foreach ($options as $key => $option) {
if($option == 'y'){
echo $costs[$key];
echo $apply[$key];
}
}
}
Using jQuery you can get the Hidden values like-
$(function(){
$('.input_check').on("change", function(){
var chk = $(this).prop('checked');
if(chk == true){
var val = $(this).closest('label').find('.option').val();
console.log(val);
}
})
})

PHP getting value immediately after clicking on checkbox

How to get value from checkbox or radio button immediately after clicking on it and write it in textfield without using reset or submit button?
<input type="checkbox" name="age" value="21-29">21-29 <input type="text" name="yourAge" value="">
You can do like this with jQuery click function More Detail Here
<input type="checkbox" name="age" value="21-29" id="age">21-29
<input type="text" name="yourAge" value="" id="yourAge">
JQuery
$("#age").click(function () {
$("#yourAge").val($("#age").val());
});
Fiddle
#Shehary is on point but there is always room for more.
JS
<script>
var changeInput = function (val){
var input = document.getElementById("age");
input.value = val;
}
</script>
HTML
<input type="checkbox" name="age" value="21-29" onclick='changeInput(this.value);' >21-29
<input type="text" name="yourAge" value="" id="age">
Pen
I know this is old, and my code may not be great, but I like to use this.
<?php
$get= "?checked";
$checked= "";
if(isset($_GET['checked'])){
$get= "";
$checked= "checked";
}
?>
<a href="waiting_in_db.php<?=$get?>">
<input type="checkbox" <?=$checked?> >
</a>
But I prefer using CSS and links without the checkbox.

get check box value with javascript and add those values in a div as i select more than one value

get check box value with javascript and add those values in a div as i select more than one value.
i want something like this: http://img515.imageshack.us/img515/4503/w3i.jpg
when items are slected: http://img59.imageshack.us/img59/8761/fizo.jpg
and than onclick compare btn send all item selected to compare.php page
<SCRIPT LANGUAGE="JavaScript">
//do not getting what to do?
</SCRIPT>
<FORM>
<INPUT TYPE=CHECKBOX NAME="road" VALUE="Car">car
<INPUT TYPE=CHECKBOX NAME="road" VALUE="bike" CHECKED>bike
<INPUT TYPE=CHECKBOX NAME="road" VALUE="truck">truck
<INPUT TYPE=CHECKBOX NAME="road" VALUE="bus" CHECKED>bus
<div id="compare" style="border:2px solid red;"></div>
</FORM>
Here's an example to get you started:
HTML
<form id='compareForm' action='#'>
<input type='checkbox' name="road" value="car">car
<input type='checkbox' name="road" value="bike" checked>bike
<input type='checkbox' name="road" value="truck">truck
<input type='checkbox' name="road" value="bus" checked>bus
<button type='submit'>Compare</button>
</form>
<div id="compare"></div>
Note that for accessibility and usability, you may want to wrap those words in label elements.
JavaScript
document.getElementById('compareForm').addEventListener('submit', function (e) {
var items = document.getElementsByName('road'),
i;
// Prevent default form submission functionality
e.preventDefault();
// Clears the results box
document.getElementById('compare').innerHTML = '';
// Loop through all the checkboxes
for (i = 0; i < items.length; i += 1) {
if (items[i].checked) {
// Do something if the box is checked.
document.getElementById('compare').innerHTML += '<p>' + items[i].value + '</p>';
}
}
});
See the jsFiddle.

Count checked checkboxes

I am new to HTML, I have a list of checkboxes on a form in an HTML page.
Each checkbox on each line represents a different category "I" "D" "C" and "S".
Part of my code is as follows:
<form>
1.<input type="checkbox" name="Personality_1.1" value="I"/>Animated &nbsp
<input type="checkbox" name="Personality_1.2" value="D" />Adventurous &nbsp
<input type="checkbox" name="Personality_1.3" value="C" />Analytical &nbsp
<input type="checkbox" name="Personality_1.4" value="S" />Adaptable<br /><br />
2.<input type="checkbox" name="Personality_2.1" value="I"/>Playful &nbsp
<input type="checkbox" name="Personality_2.2" value="D" />Persuasive &nbsp
<input type="checkbox" name="Personality_2.3" value="C" />Persistent &nbsp
<input type="checkbox" name="Personality_2.4" value="S" />Peaceful<br /><br />
3.<input type="checkbox" name="Personality_3.1" value="I"/>Sociable &nbsp
<input type="checkbox" name="Personality_3.2" value="D" />Strong Willed &nbsp
<input type="checkbox" name="Personality_3.3" value="C" />Self-sacraficing &nbsp
<input type="checkbox" name="Personality_3.4" value="S" />Submissive<br /><br />
I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then display the total of each category when the form is submitted.
Such a: "Five D's have been checked" "Three C's have been checked"
Is there a way I can do this with Javascript or PHP? If so can anyone help direct me to figure out how to do so?
Well, with PHP, assuming your submitting the form with POST:
$counts = array_count_values($_POST);
And you'll get an associative array with the values as keys and counts as values. So if for example 3 D's have been checked, $counts['D'] will hold "3".
As an example, you can use something like this:
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var allChk = document.getElementsByTagName("input"),
counts = {},
i, j, cur, val;
for (i = 0, j = allChk.length; i < j; i++) {
cur = allChk[i];
if (cur.type === "checkbox") {
if (!(cur.value in counts)) {
counts[cur.value] = 0;
}
if (cur.checked) {
counts[cur.value]++;
}
}
}
for (val in counts) {
console.log("There are " + counts[val] + " " + val + "'s checked");
}
};
};
DEMO: http://jsfiddle.net/Dwjez/1/
Click the button, after checking some checkboxes, and look at your console to see the results. It just finds all checkboxes, and stores the number of checked ones, per value, in an object literal...then the final loop is there just to print the results in the console.
This was just a simple example with event handling, but I'd suggest looking at addEventListener vs onclick to see another way to handle events (with addEventListener).
jquery-:
var numberOfCheckboxesSelected = $('input[type=checkbox]:checked').length;
javascript--:
var checkboxLength = document.forms["formName"].elements["checkbox[]"].length;
var checkboxes = document.forms["formName"].elements["checkbox[]"];
for(var i = 0; i < checkboxLength; ++i) {
if(checkboxes[i].checked) {
// do stuff
}
}
how about...
var getCount = function(type) {
return document.querySelectorAll('input[value='+type+']:checked').length;
}
alert(getCount('A') + "As have been selected");
and it looks like you would be better off using a radio group instead of checkboxes. From looking at your html, do you want the user to be able to select more than one item in each section?
Here is the code you want. Try it and let me know.
<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" action="next_page.php" method="post">
<input type="checkbox" name="chkGuar[]" value="mike"> Mike<br />
<input type="checkbox" name="chkGuar[]" value="joy"> Joy<br />
<input type="checkbox" name="chkGuar[]" value="harry"> harry<br />
<input type="checkbox" name="chkGuar[]" value="watson"> watson<br />
<input type="checkbox" name="chkGuar[]" value="george"> george<br />
<input type="checkbox" name="chkGuar[]" value="peter"> Peter<br />
<input type="submit" name="chksbmt" value="Send" />
<!-- <div id="myrow" style="visibility:hidden">
<input type = text name ='txtGRTNo' tabindex = 19 size="20">
</div>
<div width="338" align="left" colspan="3" height="12"></div> !-->
</FORM>
</BODY>
</HTML>
next_page.php
<?php
if(isset($_POST['chksbmt'])){
$counts = count($_POST['chkGuar']);
echo "this is the next page. you checked $counts checkbox <br /><br />";
for($i=1;$i<=$counts;$i++){
echo "<input type='text' style='border:1px solid #000;' value='your text box here' /><br/><br/>";
}
}
You should write your form code like this:
<form>
1.<input type="checkbox" name="chkI[]" value="I1"/>Animated
<input type="checkbox" name="chkD[]" value="D1" />Adventurous
<input type="checkbox" name="chkC[]" value="C1" />Analytical
<input type="checkbox" name="chkS[]" value="S1" />Adaptable
2.<input type="checkbox" name="chkI[]" value="I2"/>Playful
<input type="checkbox" name="chkD[]" value="D2" />Persuasive
<input type="checkbox" name="chkC[]" value="C2" />Persistent
<input type="checkbox" name="chkS[]" value="S2" />Peaceful
3.<input type="checkbox" name="chkI[]" value="I3"/>Sociable
<input type="checkbox" name="chkD[]" value="D3" />Strong Willed
<input type="checkbox" name="chkC[]" value="C3" />Self-sacraficing
<input type="checkbox" name="chkS[]" value="S3" />Submissive
</form>
Look at the "name" and "value" attributes. I made I change to the values of them.
You say:
I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then
display the total of each category when the form is submitted.
If you make a submit...
<?php
if(!empty($_GET['chkD'])) {
$counterChkD = 0;
foreach ($_GET['chkD'] as $chkD){
echo $chkD."\n";
//echoes the value set in the HTML form for each checked checkbox associated with the "D" value
//so, if I were to check "Adventurous", "Persuasive", and "Strong Willed" it would echo value D1, value D2, value D3.
$counterChkD++;
}
echo "# of 'D-CheckBoxes' checked: ".$counterChkD."\n";
}
?>

Calling JavaScript function from PHP echo within a radio button

I have a series of radio buttons, which onClick will either reveal or hide a Div:
Reveal the Div:
<input type="radio" name="con[4]" value="1" onclick="toggleLayer4(this.checked);" id="con4" />
Hide the Div:
<input type="radio" name="con[4]" value="0" onclick="toggleLayer4(!this.checked);" checked="checked" id="con4" />
JavaScript:
function toggleLayer4(val)
{
if(val == '1' || val === true)
{
document.getElementById('con4').checked = true;
document.getElementById('con4PSTN').style.display = 'block';
}
else if(val == '0' || val === false)
{
document.getElementById('con4').checked = false;
document.getElementById('con4PSTN').style.display = 'none';
}
}
Now the problem, when the pag is recalled, I can get the radio button checked like this:
<input type="radio" name="con[4]" value="1" onclick="toggleLayer4(this.checked);" <? if ($conn_count[3] == 1){echo "checked=\"checked\"";}?> id="con4" />
But I need a away of calling the JavaScript function to reveal the div if the radio button is checked, I have tried to echo toggleLayer4(this.checked); within the PHP if statement inside tags, however this just seems to reurn the text in the html??
There must be a way, not really versed in JS.
Cheers,
B.
Here is a plain unobtrusive javascript for you which will save you some work - please notice there are no event handlers on the radios anymore.
I gave them unique IDs which is mandatory.
If you ever need to use jQuery for other stuff, this script can be a little more elegant.
I assume
<input type="radio" name="con[1]" value="1" id="con1_1" />
<input type="radio" name="con[1]" value="0" id="con1_0" />
<input type="radio" name="con[2]" value="1" id="con2_1" />
<input type="radio" name="con[2]" value="0" id="con2_0" />
<input type="radio" name="con[3]" value="1" id="con3_1" />
<input type="radio" name="con[3]" value="0" id="con3_0" />
<input type="radio" name="con[4]" value="1" id="con4_1" />
<input type="radio" name="con[4]" value="0" id="con4_0" />
and matching object to have conxPSTN where x is the number in the con[x]
window.onload=function() {
var conLength = <?php echo count($con); ?>;
for (var i=1;i<=conLength;i++) {
var cons = document.getElementsByName("con["+i+"]");
for (var j=0;j<cons.length;j++) {
cons[j].onclick=function() {
var id = this.id.split("_")[0];
document.getElementById(id+"PSTN").style.display = (this.value==1)?"block":"none"
}
if (cons[j].checked) cons[j].click();
}
}
}
<input type="radio" name="con[4]" value="0" onclick="toggleLayer4(0);" checked="checked" id="con4" />
<input type="radio" name="con[4]" value="1" onclick="toggleLayer4(1);" checked="checked" id="con4" />
function toggleLayer4(val)
{
if(val){
document.getElementById('con4PSTN').style.display = 'block';}
else{
document.getElementById('con4PSTN').style.display = 'none';
}
}
If you are echoing from php then you should do like
echo "<script type='text/javascript'>toggleLayer4(this.checked);</script>";
But you cant use this in there. You need to get the value of the radio button manually n pass it
EDIT
This is the case when you want to call the function explicitly in some part of the code and when the php code is not with the <script> tags.

Categories