displaying radio button values on different textbox - php

<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.0");
</script>
<script type="text/javascript">
$(function()
{
$('input[type=button]').click(function ()
{
var txtbox = $('#buttoncheck1').attr('name');
var var_name = $("input[name='radio1']:checked").val();
$('#btn_get').val(var_name);
});
});
</script>
<html>
<body>
<?php
for($i = 0; $i < 2; $i++)
{
echo "
<div id = 'div1' name = 'div1'>
<input type='radio' value='Blue' name='radio1'>Blue</input>
<input type='radio' value='White' name='radio1'>White</input>
<input type='radio' value='Red' name='radio1'>Red</input>
<input id='buttoncheck1' type='button' name='btn' value='Click'></input>
<br />
<input type='text' id='btn_get' name='get_btn_value'></input>
</div>
";
}
?>
</body>
</html>
I can clearly get all the values of the radio buttons in this code but the only problem I've been solving for almost 3 days is that I cant display the value on other textbox. all the values from all the radio button groups are only displayed on the first textbox produced by the loop. please help me . thanks!

id values should always be unique. You can change your duplicated ids to class values and do the following:
$('input[type=button]').click(function ()
{
var $parent = $(this).parent();
var var_name = $parent.find("input[name='radio1']:checked").val();
$parent.find('.btn_get').val(var_name);
});

Related

How to disable selected list values in subsequent lists?

I have a table with one column which has the list of values .The list is same in all the rows.
Now when user selects the value for first row, I want to disable it for all the rows, and when user select second value in second row, that value should be disabled in all upcoming rows and so on.So that user don't have the option to choose one value for more than one column.
I could disable the first selected value in all the columns but dont know how to do it for all the rows.
DB Table
sqlite> select * from outdoor_games;
games
----------
Badminton
Football
Basketball
Golf
Code
<?php
$db = new PDO("sqlite:c:/sqlite/games.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query_game = $db->prepare("select distinct games as di from outdoor_games;");
$query_game->execute();
$data = $query_game->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<TABLE id="STable" width="350px" border="1">
<tr> <th bgcolor="WHITESMOKE">Game Id </th> </tr>
<TR> <td><select name= "Game_id[]" class='Game'/> <option value="">Games</option>
<?php foreach ($data as $row){echo '<option value="' . $row['di'] . '">' . $row ['di'] . '</option>';} ?>
</select></td>
</TR>
</TABLE></br>
<label>No. of games <input type= "text" id="s_cnt" name= "d_Count"></label>
<button type="button" class='loadgames' >Load Games</button>
<input type="submit" name ="add_SP" value ="Add Student Info" style="float: right;" /> </br> </br>
<input type="submit" name ="exit" value ="EXIT" />
</form>
<script>
$('.Game').on('click', function()
{
var selected = $(this).val();
$('.Game').not(this).find('option[value="'+selected+'"]').prop('disabled', true);
});
$(".loadgames").on('click',function()
{
var num = $("#s_cnt").val();
$("#STable tr").slice(2).remove();
for (var i = 2; i <= num; i++)
{
var data = "<tr><td><select name='Game_id[]' class='Game'><option value='null'>Games</option><?php foreach ($data as $row){echo "<option value=".$row['di'] . ">" .$row['di']. "</option>";}?></select></td></tr>";
$("#STable").append(data);
}
});
</script>
</body>
</html>
try this:
$('select').on('change',function(){
var val = $(this).val();
var selected = $(this);
$('select').nextAll('select').find('option').each(function(){
if($(this).attr('value')==val) {
$(this).attr('disabled','disabled');
}
})
});
see the demo.
You can try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('change', '.Game', function() {
$('.Game option').removeClass("active");
$(this).addClass("active");
});
});
<script>
// For class
.Game option.active {opacity: 0.3;cursor: pointer}

PHP getting form data using id attribute

I'm making a form with checkboxes and radiobuttons
I use the value as price, which I calculate with a script so I get the total price of the selected checkboxes and radiobuttons.
<script>
function calcscore() {
score = 0;
$(".calc:checked").each(function () {
score += Number($(this).val());
});
$("#price").text(score.toFixed(2));
$("#sum").val(score)
}
$().ready(function () {
$(".calc").change(function () {
calcscore()
});
});
</script>
<input type="radio" id="1" value="40" class= "calc" name = "780143050"> Gezichtsbehandeling (incl.)<br>
<input type="radio" id="2" value="40" class = "calc" name = "780143050"> Massage<br>
<input type="radio" id="3" value="75" class = "calc" name = "780143050"> beide
<span id="output"></span><input type="hidden" name="sum" id="sum" value="0">
<p>Totaal extra's : € <span id="price">0</span>
I have the following PHP
test.php
<?php
echo("keuze : " . $_POST['780143050'] . "<br />\n");
?>
I in my php script the value and the ID. How can I echo the ID of the selected radiobutton?
There are 2 ways to do this:
change the value of value to the value of the id
add the value of the id to the value
html:
<input type="radio" id="2" value="40|2" class = "calc" name = "780143050"> Massage<br>
js:
<script>
function calcscore() {
score = 0;
$(".calc:checked").each(function () {
score += Number($(this).val().split('|')[0]);
});
$("#price").text(score.toFixed(2));
$("#sum").val(score)
}
$().ready(function () {
$(".calc").change(function () {
calcscore()
});
});
php
<?php
echo("keuze : " . split('|',$_POST['780143050'])[1] . "<br />\n");
?>
See below code. Selected radio button ID will be received as $_POST['selID']:
$('form').submit(function(){
var selID = $('form input[type=radio]:selected').attr('id');
$(this).append('<input type="hidden" name="selID" value="'+selID+'" />');
});

How to save the value of the checked checkbox to the database

I have here checkboxes that have a different prices and each have a different titles. When the user clicks the checkbox, it will view the price in the total field. When the user now clicks the save button, I want now to save the total to the database and save the titles of the checked checkbox to categories. The titles that will be save to the one row of the database must be separated by comma (,).
This is my HTML codes:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<link rel="stylesheet" type="text/css" media="screen" href="css/master.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<!--<script type="text/javascript" src="js/jquery.min.js"></script>-->
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<form action="" method="post">
<input type="checkbox" name="checkbox1" value="₱20"> Red </br>
<input type="checkbox" name="checkbox1" value="₱30"> Blue </br>
<input type="checkbox" name="checkbox1" value="₱40"> Green </br>
</br></br>
Total: <input type="text" name="total" readonly>
<input type="submit" name="save" value="SAVE">
</form>
<script type="text/javascript">
$(function(){
//bind the change event to the checkboxes
$('input[name="checkbox1"]').change(function(){
var total = 0;
//get value from each selected ckeck box
$('input[name="checkbox1"]:checked').each(function(){
var tval = $(this).val();
//remove ₱ sign from value
//convert it to a flot
//plus it to the total
total += parseFloat(tval.replace("₱",""));
});
//finally display the total with a ₱ sign
$('input[name="total"]').val("₱ " + total);
});
});
</script>
</body>
</html>
I don't have any idea in how to save the titles of the checkboxes to one row (CATEGORY) of the database. The total price must be save too in the TOTAL field in the database.
Table name: PRODUCTS
Columns: CATEGORY, TOTAL
Example data saved in the database:
CATEGORY:[Red, Blue]
TOTAL: [50]
If you need to colors, you need to get the next sibling from the binded checkbox, then you could create another hidden form for colors since you set the checkbox values as prices. Rough example:
<form action="" method="post">
<input type="checkbox" name="checkbox1" value="20"> Red </br>
<input type="checkbox" name="checkbox1" value="30"> Blue </br>
<input type="checkbox" name="checkbox1" value="40"> Green </br>
</br></br>
<!-- hidden input colors -->
<input type="hidden" name="colors" value="" />
Total: <input type="text" name="total" readonly>
<input type="submit" name="save" value="SAVE">
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var colors = [];
//bind the change event to the checkboxes
$('input[name="checkbox1"]').change(function(){
var total = 0;
//get value from each selected ckeck box
$('input[name="checkbox1"]:checked').each(function(){
var tval = $(this).val();
total += parseFloat(tval);
});
//finally display the total with a ₱ sign
$('input[name="total"]').val("₱ " + total);
// handle colors
var color = $.trim($(this)[0].nextSibling.nodeValue); // get the name
var i = colors.indexOf(color);
if(i != -1) {
colors.splice(i, 1); // remove if unchecked
} else {
colors.push(color); // push if checked
}
var temp = colors.join(', ');
$('input[name="colors"]').val(temp);
});
});
</script>
The PHP:
<?php
$db = new mysqli('localhost', 'username', 'password', 'database');
$stmt = $db->prepare('INSERT INTO `PRODUCTS` (`CATEGORY`, `TOTAL`) VALUES (?, ?)');
if(isset($_POST['save'])) {
$total = (int) str_replace('₱ ', '', $_POST['total']); // remove peso sign
$colors = $_POST['colors'];
$stmt->bind_param('si', $colors, $total);
$stmt->execute();
}
?>
Give them different names
<input type="checkbox" name="Red" value="₱20"> Red </br>
<input type="checkbox" name="Blue" value="₱30"> Blue </br>
<input type="checkbox" name="Green" value="₱40"> Green </br>
and change your jquery a little bit:
//bind the change event to the checkboxes
$('input[name="checkbox"]').change(function(){..}
then access the attribute name:
var name = $(this).attr("name");
DEMO
$(function(){
var total = 0;
var colors = "";
$("input[type=checkbox]").change(function(e) {
var selected_color = $('input[type=checkbox]:checked');
colors = selected_color.map(function() {
return $(this).attr("name");
}).get().join(', ');
//alert(colors);
selected_color.each(function(){
var tval = $(this).val();
total += parseFloat(tval.replace("₱",""));
});
//alert(total);
});
$( "form" ).submit(function( event ) {
$.ajax({
type: "POST",
url: "your_script.php",
data: { category:colors, total: total},
success: function(data) {
alert('success');
}
});
});
});
PHP
echo $_POST['categor'];
echo $_POST['total'];
As for the insert provide this is straight for forward, you did not specify which driver you use, but you can consult #Ghost answer for mysqli
DEMO
well this seems to be a problem to the super extraordinary label element!!! (i'm so stupid, i can't beat my impetus -.-)
you can put it in a label like this:
Red
so each label identify each checkbox
so you can (if it is PHP):
$labels = $_POST['labels'];
and supposing that you have a normalized DB like this(everything else is only play with strings):
| ID | CATEGORY |
for($i=0; $i < count($labels); $i++){
mysqli_query($con,"Insert into CATEGORY(categoryname) values(' "+$labels[$i]" '); ");
}
PD: this code wasn't tested.
You need to write some server side code that will take the form data and write it to the database - this would be usually written in PHP or ASP with the bit writeing data to the database in SQL.

How do I get all radio buttons and their textbox values?

Description: On the form appears radio buttons with textboxes. Their count = count that you entered in textbox. In test.php file I need get all radio buttons and their textbox values, it does not matter - checked, unchecked radio buttons state.
Error is that I get only the most recent values of radiobutton and textbox. I do not see values of previous radiobuttons and textboxes.
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function getnewElementID()
{
var elementID = 0;
if($(".form-element").length > 0)
elementID = $(".form-element").length;
return elementID;
}
$(document).ready(function() {
$('#ok1').click(function () {
var n = $('#box1').val();
var index = 0;
var newElementID = getnewElementID();
if($(".RadioDiv").length > 0)
index = $(".RadioDiv").length;
var newElement = "<div class='RadioDiv form-element'><input type='hidden' name='RadioElements["+newElementID+"]' value='radiogroup'/>\n<input type='text' size='50' name='RadioElementsQueations["+newElementID+"]' placeholder='question...' >";
for (var i=1;i<=n;i++)
{
newElement+="<ol><input type='radio' name='RadioElementsValues["+newElementID+"]' value='radio_"+index+"' for='RadioElementsValuesText["+newElementID+"]'>\n\<input type='text' id='radtext' name='RadioElementsValuesText["+newElementID+"]' size='30' value='choice.."+index+"' ></ol>";
index++;
}
newElement+="</div>";
$("#myForm").append(newElement);
});});
$(document).ready(function() {
$('#submit').click(function () {
var data = $("#myForm").serialize();
if($('input[type="radio"]:checked').length == "0") {
alert("Select any value");
} else {
$.post (
"test.php",
data,
function (response) {
$('#message').html(response);
}
);
}
return false;
});
});
</script>
</head>
<body>
<form id ="myForm" action="test.php">
<label>Select your favourite Activities:</label><br/>
<input type="button" name="ok" value="ok" id="ok1">
<input type="text" value="" id="box1" name="count" size="1"><br/>
<input type="submit" id="submit"/> <br/>
</form>
<div id="message"></div>
</body>
</html>
test.php
<?php
var_dump($_POST);
$elements = $_POST['RadioElementsValuesText'];
if(is_array($elements));
for ($index = 0; $index<sizeof($elements);$index++)
{
$astring = implode("<br/>", $elements);
echo "Choices: ". $astring."<br/>";
}
?>
You should use checkboxes instead of radio button.
In a post request, only one radio button value will be send for the group name (here 'RadioElementsValuesText').
Use javascript to reproduce the radio button behavior on your checkboxes (only one checked at a time).

Changing from PHP to JS

My problem maybe is basic, i just lack the skills.
How can i turn the following code into javascript? :
<?php
for($i=1; $i<10; $i++){
echo "<input type='text' placeholder='Word' name='word$i' /><br />";
}
?>
I want to add an input everytime the user presses a button (already built) but i need every new input to have the following number than the one before. For instance:
input 1 (... name='word1')
press again the button
input 2 (... name='word2')
press again the button
input 3 (... name='word3')
Thanks! Happy 2013!
Ok you have one button created please write a onclick event on it whick fires a function
like this and also create one main div in which your elements can be added
<input type="button" onclick="getElement();"/>
<di id="main"></div>
In the function getElement please write this code:
var i=1;
function getElement(){
var str = "<input type='text' placeholder='Word' name='word"+i+"' />";
i++;
document.getElementById('main').innerHTML = str;
}
for (var i = 0; i < 10; i++) {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Word');
input.setAttribute('name', 'word' + i);
}
Something like this?
Tested in Chrome
<input type="button" value="Magical pony time!" onclick="clickhandler()" />
<div id="container"></div>
<script type="text/javascript">
// contains the counter for elements added
window.__buttonClickCounter = 0;
// Keep reference to container
var c = document.getElementById('container');
// Click handler that appends to the contents of the container
var clickhandler = function() {
c.innerHTML = c.innerHTML + "<input type='text' placeholder='Word' name='word"+window.__buttonClickCounter+"' value="+window.__buttonClickCounter+" /><br />";
window.__buttonClickCounter++;
}
</script>
Try
<?php
for($i=1; $i<10; $i++){
?>
<input type='text' placeholder='Word' name='word'<?php echo $i;?>/>
<?php
}
?>

Categories