Validate dynamically named radio buttons using javascript - javascript

I have been trawling through various examples of radio buttons validation and grasp the concept but no examples seem to fit my situation. I have queried my database which has 4 options and for each option I have generated an associated radio button as below:
<?php foreach($options as $option){ ?>
<p><input type="radio" name="ID<?php echo $row['id']; ?>" value="<?php echo $option; ?>"><?php echo $option; ?></p>
<?php } ?>
So this basically generates 4 radio buttons per row called from the database. This appears in the source as:
<form method="POST" action="Result.php">
<p>1. Question </p>
<p><input type="radio" name="ID1" value="answer1">answer1</p>
<p><input type="radio" name="ID1" value="answer2">answer2</p>
<p><input type="radio" name="ID1" value="answer3">answer3</p>
<p><input type="radio" name="ID1" value="answer4">answer4</p>
<p>2. Question 2</p>
<p><input type="radio" name="ID2" value="answer1">answer1</p>
<p><input type="radio" name="ID2" value="answer2">answer2</p>
<p><input type="radio" name="ID2" value="answer3">answer3</p>
<p><input type="radio" name="ID2" value="answer4">answer4</p>
<input type="submit" name="submit" value="Submit!">
</form>
etc etc.
The names of these radio buttons are partially generated by php, how can I use javascript with an associated alert to check 1 of the radio buttons from each question has been checked prior to submitting the form the questions are populated within?
Or maybe even just how can I achieve this with php ISSET?

Using just JavaScript to verify whether a radio button within a radio group is checked:
function radiogroupSelected(name){
var inputArr = document.getElementsByName(name);
for(var i = 0; i < inputArr.length; i++){
if(inputArr[0].checked){
return true;
}
}
return false;
}
Now you can call this function like radiogroupSelected('ID1') to determine if one of the inputs was selected.

Related

How to put in checkboxes values into a session variable without any button clicks?

lets say i have a code pretty similar like this
<form>
<input type="checkbox" name="account1" value="1">
<input type="checkbox" name="account2" value="2">
<input type="checkbox" name="account3" value="3">
<input type="checkbox" name="account4" value="4">
<button type="submit">Delete</button>
</form>
Now i want to store the value of the checkbox in a php session once the user checked the boxes without clicking the submit/delete button. I plan to use jquery/ajax for this but i still cant quite wrap my head around it since im very new to ajax or jquery.
To add more detail, the process is like this..
the user can select any account he wants he checked. lets say he checked an account on page 1. he then went to another page(pagination) and then went back to page 1, the checked boxes would still be checked.
You can use onchange event listener for this.
Live example here.
index.php
<form>
<input type="checkbox" name="account1" value="1">
<input type="checkbox" name="account2" value="2">
<input type="checkbox" name="account3" value="3">
<input type="checkbox" name="account4" value="4">
<button type="submit">Delete</button>
</form>
<br/><strong>You can see the checkbox values in session below...</strong>
<div id="newDiv">
</div>
<script>
$('*[type="checkbox"]').on("change", function(){
var check = 0;
if(this.checked == true) check = 1;
var value = this.value;
$.post("session.php", { box : value, check : check }, function(data, status){
if(status == "success"){
$('#newDiv').load("values.php");
}
})
})
</script>
session.php
<?
session_start();
if(isset($_POST['box'])){
//Separate session variable for each checkbox.
$checkbox = "checkBox".$_POST['box'];
$_SESSION[$checkbox] = $_POST['check'];
}
?>
values.php
<?
session_start();
print_r($_SESSION);
?>

Get RadioButton value with php

I can get the value of text input from a form.
Like this:
<label for="lblName">Name (*):</label>
<input type="text" name="txtBoxName" id="txtBoxName">
I submit the form with a validation check first:
<form name="contactDataForm" action="sendMail.php" onsubmit="return ValidationCheck()" method="post">
This is sendMail.php:
$Name = $_POST['txtBoxName'];
This works, but how you do it for a RadioButton value? The selected radio button value.
<input type="radio" name="test1" id="test1" value="test1" required> TEST 1<br>
<input type="radio" name="test2" id="test2" value="test2"> TEST 2<br>
A radio button is used for selecting a single value from multiple values. So, there will be only one single name for all the radio buttons and the values for each of them may vary. You can get the value using the usual $_POST['name'] in PHP.
<form action="" method="post">
<input type="radio" name="radio" value="1">Radio 1
<input type="radio" name="radio" value="2">Radio 2
<input type="radio" name="radio" value"3">Radio 3
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['radio']))
{
echo "You have selected :".$_POST['radio']; // Displaying Selected Value
}
}
?>
Make the 2 radio buttons with the same name attribute test1 example
you will find the radio button value at your PHP server with
$radioValue = $_POST['test1'];
This is a standard HTML Form. A HTML form always gives the value of the selected radio button. If you have a 2 radio buttons with the same name value this will work. The selected radio button will then post your answer to the server. You can then get the value the same way.
I hope this helps.

Using javascript to prevent duplicate values of dynamically generated input text boxes

I have a 3 step (3 page) form. The first page that asks the user to check up to 5 of there favorite music genres. The second page dynamically displays the checked genres and then asks to rank them and the third page displays their music genre preference in order.
My question is how can I use javascript to prevent duplicate values of dynamically generated input text boxes on the second page?
I found this code (http://jsfiddle.net/zHJSF/) that would work if my text box fields were set but the text box fields are being generated dynamically. It might be easier to tweak that code or do something different that involves a loop. I'm not sure.
below is the code for the three pages:
Page 1
<form id="genre" name="genre" method="post" action="musicsell.php">
<input type="checkbox" name="genre[]" id="Rap" value="Rap"/>Rap<br />
<input type="checkbox" name="genre[]" id="HipHop" value="HipHop"/>HipHop<br />
<input type="checkbox" name="genre[]" id="RnB" value="RnB"/>RnB<br />
<input type="checkbox" name="genre[]" id="Rock" value="Rock"/>Rock<br />
<input type="checkbox" name="genre[]" id="Jazz"value="Jazz"/>Jazz<br />
<p>
<input type="submit" value="Next">
<br />
</p>
</form>
Page 2
<form id="form1" name="form1" method="post" action="musicresults.php">
<?php
$name = $_POST['genre'];
if(isset($_POST['genre'])) {
foreach ($name as $genre){
?>
<input type="number" required="required" id="<?php echo $genre ?>" name="music[<?php echo $genre ?>]" max="3" min="1" /><?php echo $genre ?><br />
<?php
}
}
?>
<input type="submit" name="button" id="button" value="Submit" /></form>
page 3
<?php
//Get the form results (which has been converted to an associative array) from the $_POST super global
$musicgenres = $_POST['music'];
//Sort the values by rank and keep the key associations.
asort($musicgenres, SORT_NUMERIC );
/*
//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
echo "$music is your $rank choice";
echo "<br>";
}*/
foreach($musicgenres as $music => $rank)
{
array_push($musicstring, $music);
echo "$music is your $rank choice";
echo "<br>";
}
$musicstring = implode(", ", $musicgenres);
echo $musicstring;
?>
add a class to the inputs i will use the class test
and i'm using jquery so add the jquery library before add the code
$(document).ready(function(){
$('.test').change(function(){
var theinput=$(this);
var value=theinput.val();
$('.test').each(function(){
if($(this).val()==value){
theinput.val('');//to remove the value
alert('you choose a duplicate');//notify the user why the value removed
}
});
});
});

Single radio select on two forms

I have two radio buttons which correspond to two different forms.
Depending on the selected radio, I want to accomplish two different actions, thus the reason why I have two forms.
The problem I'm having is that single-radio select works when the two radios are on a single form. If, by any chance they are in two different forms, the single selection doesn't work.
Both radios have the same name, but I don't know how to force single select based on two different forms.
I'm using jQuery (not for radios selection, but the jQuery is there) so although I would prefer not to use jQuery for this action, if it comes down to it, I'm ok with that.
Could anyone provide a solution or a pointer in the solution direction for this?
Best Regards,
EDIT
I'm placing some code at request
<div class="payment-details-account-top">
<form id="payment-details-form-card" action="<?php echo Mage::getUrl('orderform/index/changedpayment'); ?>" method="POST">
<div class="row all-steps">
<div class="col-md-12">
<input type="radio" name="payment-type" value="<?php echo $this->__('Betale med kort') ?>" id="payment-with-card" class="css-checkbox" <?php if ($ba->getMethodCode() == 'payex2'): ?> checked <?php endif; ?> onclick="this.form.submit();">
<label for="payment-with-card" class="css-radio-label"></label>
<input type="submit" name="payment-with-card" id="payment-with-card" value="<?php echo $this->__('Betale med kort') ?>" class="top-payment-buttons" />
<div class="creditcards"></div>
<!-- <span class="payment-method-message"><?php if ($ba->getMethodCode() == 'payex2') echo $message; ?></span> -->
</div>
</div>
</form> <!-- Close "payment-details-form-card" form -->
</div>
<div class="payment-details-account-bottom">
<form id="payment-details-form" action="<?php echo Mage::getUrl('orderform/index/changedpayment'); ?>" method="POST">
<div class="col-md-12">
<input type="radio" name="payment-type" value="<?php echo $this->__('Betale med faktura') ?>" id="payment-with-faktura" class="css-checkbox" <?php if ($ba->getMethodCode() != 'payex2'): ?> checked <?php endif; ?> >
<label for="payment-with-faktura" class="css-radio-label"></label>
<input type="button" name="payment-with-faktura" id="payment-with-faktura" value="<?php echo $this->__('Betale med faktura') ?>" class="bottom-payment-buttons" />
<div class="row">
<ul>
<li class="row">
<div id="billing-submit" style="display: none;">
<input type="reset" name="submit-cancel" id="billing-cancel" value="AVBRYT" class="btn-grey" />
<input type="submit" name="submit-payment" id="submit-payment" value="<?php echo $this->__('Bekreft') ?>" class="btn-green" />
</div>
</li>
</ul>
</div>
</div>
</form>
</div>
Without seeing all of your code, it is hard to tell if you would be better off handling this in a different manner, such as:
Use a tab set with each form on a different tab.
Use a single form, but change the form's action based on the radio buttons.
If you really want to use two forms with radio buttons like that, you either have to place the radio buttons outside the forms or handle the selecting/unselecting yourself.
(1) Placing the radio buttons outside the forms.
HTML:
<label><input type="radio" name="formSelect" value="#form1" checked="checked"/>Form 1</label>
<form id="form1" class="form">
<input type="text"/>
</form>
<label><input type="radio" name="formSelect" value="#form2"/>Form 2</label>
<form id="form2" class="form">
<input type="text"/>
</form>
<button type="button" id="submitBtn">Submit</button>
JQuery:
$('#submitBtn').click(function() {
var $form = $($('input[name=formSelect]:checked').val());
alert('submitting form: ' + $form.attr('id'));
//$form.submit();
});
jsfiddle
(2) Handling the selecting/unselecting yourself/.
HTML:
<form id="form1" class="form">
<label><input type="radio" class="formSelect" checked="checked"/>Form 1</label>
<input type="text"/>
</form>
<form id="form2" class="form">
<label><input type="radio" class="formSelect"/>Form 2</label>
<input type="text"/>
</form>
<button type="button" id="submitBtn">Submit</button>
JQuery:
$('.formSelect').change(function() {
$('.form').not($(this).closest('form')).find('.formSelect').prop('checked', false);
});
$('#submitBtn').click(function() {
var $form = $('.formSelect:checked').closest('form');
alert('submitting form: ' + $form.attr('id'));
//$form.submit();
});
jsfiddle
Really, no vanilla JS answer even though OP explicitly mentioned a preference?
Simple as this:
var options = document.getElementsByName('mygroup');
document.body.addEventListener('click', function(e) {
if (e.target.name === 'mygroup') {
for (var i = 0; i < options.length; i++)
options[i].checked = false;
e.target.checked = true;
}
}, false);
See it here: http://jsbin.com/mefibi/1/edit?html,js,output
Most of these answers are almost there and actually provide a path in the right direction..
Since the forms code is a lot more complex than the sample I posted, here's the actual implementation:
$('#payment-with-faktura').on('click', function(){
$('#payment-with-card').removeAttr("checked");
$('.billing-address-list input').each(function() {
$(this).attr({
'disabled': 'disabled'
});
});
$(".col-order-12").slideDown(300);
$(".prepaid-extra-method2").slideDown(300);
if (validateBillingAddress()) {
$(".payment-button-submit").removeAttr("disabled");
} else {
$(".payment-button-submit").attr("disabled", "disabled");
}
});
$('#payment-with-card').on('click', function(){
$('#payment-with-faktura').removeAttr("checked");
$("#payment-details-form").find('input[type="text"]').val("");
$(".prepaid-extra-method2").slideUp(300);
$(".col-order-12").slideUp(300);
if (validateBillingAddress()) {
$(".payment-button-submit").removeAttr("disabled");
} else {
$(".payment-button-submit").attr("disabled", "disabled");
}
});
If I understood correctly, there will be 2 same named radio boxes inside 2 different forms and only one of radio box could be selected at a time. A possible way to achieve this could be like this:
var options = $('form input:radio');
options.click(function() {
options.prop('checked', false);
$(this).prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form><input type="radio" name="opt"/></form>
<form><input type="radio" name="opt" /></form>
It is basically clean all 'selected' state and re-check the clicked one

Nested Form to disable text field with selection box HTML

I have code form.html and entry.php
First I want to disable textfield with selection box using javascript, then submit it to give an output.
If i not using this code <form name="form1" method="post" action="entry.php"> form.html is success to display in web browser, but how i can submit it with one submit button?
form.html
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('.group').hide();
$('#option1').show();
$('#chooseForm').change(function() {
$('.group').hide();
$('#'+$(this).val()).show();
})
});
</script>
</head>
<body>
<form name="form1" method="post" action="entry.php">
<select id="chooseForm" name="select">
<option value="option1">Form1</option>
<option value="option2">Form2</option>
<option value="option3">Form3</option>
</select>
<form id="option1" class="group">
<input name="a" value="form A"><br>
</form>
<form id="option2" class="group">
<input name="a" value="form A"><br>
<input name="b" value="form B"><br>
</form>
<form id="option3" class="group">
<input name="a" value="form A"><br>
<input name="b" value="form B"><br>
<input name="c" value="form C"><br>
</form>
<input value="Save" name="submit" type="submit"><br>
</form>
</body>
</html>
entry.php
<?php
$select = $_POST['select'];
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
echo $select;
echo "<br>";
echo $a;
echo "<br>";
echo $b;
echo "<br>";
echo $c;
?>
Can anyone solve this code without nested form? thanks :)
First of all, you can't nest forms.
As I understand the idea is to group some elements. If so, then replace the interior <form>tags with <div>s.
The other problem is that you want to use the same input elements names through different sections. Basically, if name is not unique, it will get updated with the last occurrence's value. For example:
<input type="text" name="a" value="val 1" />
<input type="text" name="a" value="val 2" />
When the above is posted, $_POST['a'] will contain val 2 value. Even, if the second text-box is hidden. So either you make text-boxes names unique or you disable the ones, which are hidden. disabled attribute will make the control disabled for user input and also not present in $_POST array. So, in this case:
<input type="text" name="a" value="val 1" />
<input type="text" name="a" value="val 2" disabled />
$_POST['a'] will contain val 1 value, because the second text-box is disabled.
In your case, every time you hide a section you should disable all controls within the group. Here's how to do it: disable all form elements inside div.

Categories

Resources