Getting values from radio button in php - javascript

I am trying to get the values from (male or female) each pair of radio buttons which are displayed in a for-loop.
<?php
echo '<form method="post" action="index.php">';
for($i=0;$i<4;$i++){
echo 'Male <input type="radio" name="gender[]" value="Male">Female <input type="radio" name="gender[]" value="Female"><br>';
}
echo '<input type="submit" value="submit" name="test"></form>
?>
Also i am placing a button in which user can add more fields according to his needs
<input type="button" value="add" name="">
When click on this button pair of "Male" and "female" radio-button is added to current form its already implemented .
But how can I get the values with checked radio buttons?

If you want to collect the Gender of 4 different people you will have to name the radio buttons differently for each person
Using the loop counter would allow you to do this quite simply like this, using the $i added to the name=gender to get name=gender0 name=gender1 etc
<?php
echo '<form method="post" action="index.php">';
for($i=0;$i<4;$i++){
echo 'Male <input type="radio" name="gender' . $i . '" value="Male">Female
<input type="radio" name="gender' . $i . '" value="Female"><br>';
}
echo '<input type="submit" value="submit" name="test"></form>
?>

Your input name is same for all the radio's thats why only one is option selected, try with different name for each radio or use checkboxes
<?php
echo '<form method="post" action="index.php">';
for($i=0;$i<4;$i++){
echo 'Male <input type="radio" name="gender_'.$i.'[]" value="Male">Female <input type="radio" name="gender_'.$i.'[]" value="Female"><br>';
}
echo '<input type="submit" value="submit" name="test"></form>';
?>

Related

Form is auto submitting but the data is not getting passed/received

I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}

Keep the selected radio button checked and clicked upon page refresh?

i have a radio input whose values are coming dynamically and creating multiple radio fields. Long list of radio fields are displayed.
<?php
for ($i = 0; $i < $total_trades; $i++) {
$array_trade_data = $data_trade_data[$i];
$Trade_name = $array_trade_data['name'];
$Trade_id = $array_trade_data['id'];
?>
<input type="radio" class="trade" id="<?php echo $Trade_id; ?>" name="trade" value="<?php echo $Trade_id; ?>" ><?php echo $Trade_name; ?><br>
<?php } ?>
I want to Keep the selected radio button checked and clicked upon page refresh.
you cold use checked attribute
<input type="radio" name="trade">1<br>
<input type="radio" name="trade" checked>2<br>
<input type="radio" name="trade">3
to click something like
<script>document.getelementbyid("<?php echo $Trade_id; ?>").click();</script>

How to calculate a total by taking the radio button values using PHP and Javascript?

I represent the questions from the database using php. Using an array I display them in a table. The radio buttons are grouped by giving a variable "i" in php as the name. Because of that I cannot get the values of those radio buttons to a javascript function to calculate the total.
This is how the table is represented:
I want to calculate the total from the selected radio button values and send the value to another page. How do I do that? Thanks a lot in advance!
Below is my code.
<html>
<body>
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'psych';
$connect = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
$res = mysqli_query($connect, "SELECT questions FROM questions");
$quests = mysqli_fetch_array($res);
?>
<form name="form1" id="form1" method="post" action="../../Algorithms/score.php">
<table>
<th>
<td width=100>Strongly agree </td>
<td width=100>Agree </td>
<td width=100>Neutral </td>
<td width=100>Disagree </td>
<td width=100>Strongly disagree </td>
</th>
<?php
$score=0;
$i=1;
while($row = mysqli_fetch_array($res))
{
echo "<tr> <td width=500>".$i.". ".$row['questions']."</td>";
echo '<td width=100> <input type="radio" name="'.$i.'" value="1" > </td>';
echo '<td width=100> <input type="radio" name="'.$i.'" value="2" > </td>';
echo '<td width=100> <input type="radio" name="'.$i.'" value="3" > </td>';
echo '<td width=100> <input type="radio" name="'.$i.'" value="4" > </td>';
echo '<td width=100> <input type="radio" name="'.$i.'" value="5" > </td>';
// if (score."$i") {echo "score$i";}
echo "</tr>";
// echo $scores[$i];
//$scores[$i]=$_POST['score'.$i];
$i++;
}
echo "</table>";
echo "<br>";
?>
<input type='submit' name='submit' value='Submit'/>
First of all , it will better to name your inputs with a meaningful names.
For example
echo '<td width=100> <input type="radio" name="score['.$i.']" value="1" > </td>'
this will help you to distinguish between other fields - if you need to add another fields -
in server side , you are now have a array of inputs called score , you can sum/calculate the total with array_sum just like :
if (isset($_POST['score'])) {
$total = array_sum($_POST['score']);
}
to save this value , you can use session with this
You can use same radio button but different values <input type="radio" name="score" value="1" >,<input type="radio" name="score" value="2" >.
In radio buttons pass the custom class like this <input type="radio" class="cstm-radio" name="score" value="1" >;
use on-click java-script or jquery event to get the value of clicked radio button and perform the ajax request, pass the url of file or file name in which you have to perform back-end operation.
You can use this code to perform ajax request!
$('.cstm-radio').click(function () {
var radio_val = $(this).val();
$.ajax({
//url of your php file
url: "post.php",
type: "POST",
data: {score: radio_val},
success: function (data) {
// alert radio value here
alert(data);
}
});
});

Get the values of while loop using button with js

How can I get the values in the while loop using button with js?
<?php
while ($row = mysqli_fetch_array($query))
{
echo '<input type="text" name="sample" value="'.$row['sample'].'">';
}
?>
Thanks
You can get the value of textbox when you click on a button.
<input type="text" name="sample[]" value="abc" class="valueInput">
<input type="text" name="sample[]" value="xyz" class="valueInput">
<input type="text" name="sample[]" value="pqr" class="valueInput">
<input type="button" class="getValue" value="Get Value">
Note: I have set the static input box you can make it dynamic but make sure please add the class as valueInput.
Jquery Code.
$(document).on('click','.getValue',function(){
var valArr = [];
$(".valueInput").each(function(){
valArr.push($(this).val());
});
console.log(valArr);
})
The name of the input field should indicate an array with [].
<form action="action.php" method="POST">
<?php
while ($row = mysqli_fetch_array($query)){
echo '<input type="text" name="sample[]" value="'.$row['sample'].'">';
}
?><input type="submit">
</form>
action.php: (Processes the data on submit)
<?php
echo "<pre>";
print_r($_POST['sample']);
echo "</pre>";

How to keep php $_GET value from a submit button after form submit from javascript?

I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name

Categories