As I am currently working with my project for addcart. I have written the javascript query for radio button can any one check this either my query is wrong or right?
JavaScript:
function get_radio_value()
{
for (var i=0; i < document."make_payment_frm".rmr.length; i++)
{
if (document."make_payment_frm".rmr[i].checked)
{
var rad_val = document."make_payment_frm".rmr[i].value;
}
}
}
HTML:
<input name="rmr" id="rmr" type="radio" value="3" onclick="get_radio_value()">
<input name="rmr" id="rmr" type="radio" value="5" onclick="get_radio_value()">
<input name="rmr" id="rmr" type="radio" value="10" onclick="get_radio_value()">
Can any one give me the correct code? If I click those buttons that amount should be added with addcart amount. For example: if my addcart amount is 27£ then I choose 2nd radio button finaly it should be display like a 32£.
Thanks in advance.
Your syntax is off, it should be document.make_payment_frm, not quotes in there (that's for bracket notation, e.g. document["make_payment_frm"]). Also, IDs shouldn't be repeated, your inputs should just be:
<input name="rmr" type="radio" value="3" onclick="get_radio_value()" />
<input name="rmr" type="radio" value="5" onclick="get_radio_value()" />
<input name="rmr" type="radio" value="10" onclick="get_radio_value()" />
Then matching script to get the value:
function get_radio_value() {
var rad_val = 0;
for (var i=0; i < document.make_payment_frm.rmr.length; i++) {
if (document.make_payment_frm.rmr[i].checked) {
rad_val = document.make_payment_frm.rmr[i].value;
break;
}
}
//use rad_val here to add to whatever
}
You can test it out here.
But since you tagged this jQuery, why not take full advantage of it? Remove those onclick handlers and add a click or change handler, like this:
$(function() {
$("input[name='rmr']").change(function() {
var val = +$(this).val();
//use val, it's a number ready to add to
});
});
You can test that version here.
Related
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>
I have a web app (PHP) and I have to make this change. I am more of a database, scripting guy, please bear with me on this one!
I have 8 check boxes (think numbered 1~8) in a form. I have to implement a condition where in :
If one of the first 4 checkboxes are checked (only one checkbox can be checked in the first 4),
Then the next 4 checkboxes should be disabled
Else the next 4 checkboxes should be enabled.
My solution :
Make the first 4 checkboxes radiobuttons to confirm to the only one
checkbox can be selected condition.
Disable/Enable the next 4 checkboxes based on the above action. So,
if the radiobutton is not selected, then the next 4 checkboxes should
be available for selection.
I have to actually disable the checkboxes rather than hide using jQuery, so the checkboxes should be solidgray (uncheckable) when disabled.
Sample code (stripped off some formatting mess for others looking for a similar solution) :
<div>
<input type="checkbox" name="check1" value="1" id="check1" <?php if (!empty($rows['check1'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check2" value="1" id="check2" <?php if (!empty($rows['check2'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check3" value="1" id="check3" <?php if (!empty($rows['check3'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check4" value="1" id="check4" <?php if (!empty($rows['check4'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check5" value="1" id="check5" <?php if (!empty($rows['check5'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check6" value="1" id="check6" <?php if (!empty($rows['check6'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check7" value="1" id="check7" <?php if (!empty($rows['check7'])) { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="check8" value="1" id="check8" <?php if (!empty($rows['check8'])) { echo 'checked="checked"'; } ?> />
</div>
My requests :
What is the most efficient way of doing this? (simple without complicating the problem)
Any sample code is greatly appreciated.
I think this is what you're looking for. You can achieve it using .index() to get current clicked checkbox. .slice() is used to get all elements at index 4 and after.
$('input[type=checkbox]').change(function(){
var $linputs = $('input[type=checkbox]').slice(4);
var $this = $(this);
$linputs.prop('disabled',($this.index() < 4 && this.checked));
if($this.index() < 4 && this.checked){
$linputs.prop('checked',false);
}
});
FIDDDLE
Or is it something like this that you want? Where only one of the first four checkboxes can be checked. If one is checked then all the others will be disabled.
$('input[type=checkbox]').change(function(){
var $this = $(this);
$(linputs).prop('disabled',($this.index() < 4 && this.checked));
if($this.index() < 4 && this.checked){
$(linputs).prop('checked',false);
}
});
http://jsfiddle.net/h5wDr/
EDIT:
if you have other checkboxes in the page and want to be able to separate them from this logic, you can add context in the selector so it keeps this code isolated to only those within this div like so
<div id='test'>
<input type="checkbox" name="check1" value="1" id="check1" >first
<input type="checkbox" name="check2" value="1" id="check2" >second
<input type="checkbox" name="check3" value="1" id="check3" >third
<input type="checkbox" name="check4" value="1" id="check4" >fourth
<input type="checkbox" name="check5" value="1" id="check5" >fifth
<input type="checkbox" name="check6" value="1" id="check6" >sixth
<input type="checkbox" name="check7" value="1" id="check7" >seventh
<input type="checkbox" name="check8" value="1" id="check8" >eight
</div>
Then just add the context
var $inputs = $('input[type=checkbox]', $('#test'));
// this will only select checkboxes within the element with id=test
http://jsfiddle.net/h5wDr/2/
<div>
<input type="checkbox" name="check1" value="1" id="check1" />
<input type="checkbox" name="check2" value="1" id="check2" />
<input type="checkbox" name="check3" value="1" id="check3" />
<input type="checkbox" name="check4" value="1" id="check4" />
<input type="checkbox" name="check5" value="1" id="check5" />
<input type="checkbox" name="check6" value="1" id="check6" />
<input type="checkbox" name="check7" value="1" id="check7" />
<input type="checkbox" name="check8" value="1" id="check8" />
</div>
<script>
$(document).ready(function () {
var $firstFourChecks = $("#check1,#check2,#check3,#check4");
var $lastFourChecks = $("#check5,#check6,#check7,#check8");
$firstFourChecks.on('click', function (e) {
var isCheck = $(this).is(':checked');
$firstFourChecks.not($(this)).prop('checked', false);
$(this).prop('checked', isCheck);
if (isCheck) {
$lastFourChecks.prop("disabled", true).prop('checked', false);
} else {
$lastFourChecks.prop("disabled", false);
}
});
});
</script>
This is entirely done in javascript, and is agnostic to the fact you are using php. Essentially, we make sure in the first four for you have not selected, they are set to false. Then we toggle the state of the one clicked.
If you clicked something on in your first four the last four are turned off and disabled, otherwise they are renabled. This matches the posted pseudocode.
You should be able to paste this directly in. The selectors are cached for speed reasons.
http://jsfiddle.net/L4qeN/ see it here.
Edit: wow looks like someone beat me to the punchline by only a few minutes. We did use very different methods; however.
You would have to try it yourself, but I would do something like (using javascript):
Add a class to every checkbox of the first group and another class to every checkbox of the second group;
Check for change events for the first class, turn off all of the first group but the clicked one;
Check if any of the first group is selected and activate / deactivate the second class group accordingly.
Give your first four checkboxes one class and then your second four a second class and then add onclick handlers to all the first checkboxes:
$('.firstfour_class').click(
if $('input:checkbox:checked.firstfour_class').length > 1){
//code to turn OFF the second four and make them unchecked
} else {
//code to turn ON the second four
}
})
Check out the jQuery :checked selector.
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.
I have number of check boxes that gets generated dynamically. So i do not know how many check boxes gets generated each time. I need to have some JavaScript ways to count the total numbers of check boxes in a form.
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
I can not change the name of the check boxes as i need to send the values to serverside PHP script as an array.
Since all other answers are jquery based, I'll offer a pure javascript solution. Assuming the following form:
<form id="myform">
<input type="checkbox" value="username1" name="check[0]" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" /><br/>
</form>
You could compute the number of checkbox elements with the following logic:
<script type="text/javascript">
var myform = document.getElementById('myform');
var inputTags = myform.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
BTW: As others have noted, the id attribute in any HTML tag should be unique within the document. I've omitted your id="1" attributes in my sample HTML above.
Update:
If you simply want to count all checkbox elements on the entire page without using a containing form element, this should work:
<script type="text/javascript">
var inputTags = document.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
In Plain JavaScript:
var myForm = document.forms[nameOrIndex];
var inputs = myForm.getElementsByTagName('input');
var checkboxes = [];
for(var i=0;i<inputs.length;i++){
if(inputs[i].getAttribute('type').toLowerCase() == 'checkbox'){
checkboxes.push(inputs[i]);
}
}
alert(checkboxes.length);
I would go with:
alert(document.querySelectorAll("input[type=checkbox]").length);
If you wanted a particular form you would need to select the form and use that as a base for your call to querySelectorAll instead of document or change the selector to include the form.
<form id="aForm">
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
<form id="bForm">
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
Then use:
alert(document.querySelectorAll("#aForm > input[type=checkbox]").length); //shows 2
alert(document.querySelectorAll("#bForm > input[type=checkbox]").length); //shows 3
Note: The Selectors API is only available in newer browsers starting with: Internet Explorer 8, Firefox 3.5, Safari 3.1, Chrome 1, and Opera 10.
alert( $("form input[type='checkbox']").length );
Will give you all the checkboxes in a form, using jQuery.
As you tagged your question with php and you seem to use some sort of numbering already for the form fields, you can also just echo that php counter to a javascript variable:
<?php
//
?>
<script language="javascript" type="text/javascript">
var checkbox_counter = <?php echo $your_counter_in_php; ?>
</script>
<?php
//
?>
By the way, in html you can only have one id on a page and it can´t start with a number.
you could use jquery
var len = $('input:checkbox').length;
alert(len);
WORKING DEMO
if you have jQuery you could do something like
alert ($(':checkbox').length ());
If not then you'll have to document.getElementsByTagName ('input'), iterate over the collection you get back and increment a counter every time you encounter one with its type attribute set to checkbox.
I have a checkbox group in my html form.The check box group contains array.
My question is how validate the checkbox array using jquery and get the array value in php
The code given below
<input type="checkbox" name="go[]" value="1" /><label>Married</label><br>
<input type="checkbox" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" name="go[]" value="4"/><label>Minor</label>
Thanks in advance.
I think you're trying to use the jQuery Validation plugin to make sure that at least one checkbox from your group is checked.
The Validation plugin doesn't like input names with brackets in them. Try this in your form's validate method:
rules: {
'go[]': { //since it has brackets, the name must be in quotes to work
required: true,
minlength: 1
}
If you mean how to validate check boxes because they contain [], here is one solution using ids instead:
<script type="text/javascript">
function validate()
{
var proceed = true;
for(var i = 1; i <= 4; i++)
{
if (!$("#" + i).is(':checked'))
{
proceed = false;
break;
}
}
if (proceed == true)
{
return true;
}
else
{
alert('All Fields Are Required !!');
return false;
}
}
</script>
And the html form might look like this:
<form action="frm" method="post" onsubmit="return validate();">
<input type="checkbox" id="1" name="go[]" value="1" /><label>Married</label><br>
<input type="checkbox" id="2" name="go[]" value="2" /><label>Widowed</label><br>
<input type="checkbox" id="3" name="go[]" value="3" /><label>Single</label><br>
<input type="checkbox" id="4" name="go[]" value="4"/><label>Minor</label>
<br />
<input type="submit">
</form>
For PHP:
// get checkboxes array
$chk_array = $_POST['go'];
Now you can manipulate $chk_array array in any way you want:
Note:
$chk_array[0] // contains your 1st checkbox value
$chk_array[1] // contains your 2nd checkbox value
$chk_array[2] // contains your 3rd checkbox value
$chk_array[3] // contains your 4th checkbox value
In php, arrays start from 0 index.
Thanks