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.
Related
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}
I am using this code
$('.calc').blur(function () {
var sum = 0;
$('.calc').each(function() {
if($(this).val()!="")
{
sum += parseFloat($(this).val());
}
});
$('.full_calc').val(sum);
});
to fill dynamically input and I want to get its data dynamically (changed in every new input filled) in php variable and use it for other calculations without a submit button. Can I do this?
try this, change jquery file name like you have there :
<html>
<head>
<title>On Change</title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script>
function sum(){
$("#n3").val(eval($("#n1").val())+eval($("#n2").val()));
}
$(document).ready(function(e) {
$("#n1").change(function(){
sum();
});
$("#n2").change(function(){
sum();
});
});
</script>
</head>
<body>
N1 :<input type="text" name="n1" id="n1" value="0" /><br>
N2 :<input type="text" name="n2" id="n2" value="0" /><br>
N3 :<input type="text" name="n3" id="n3" value="0" />
</body>
</html>
I'm using jquery to sum values of input checkbox and i need to save the sum into DB MySQL but how can i put the value in a php var? I don't know how can i do this.
Can someone help me out? I'm newbie in jquery :/
Here's the code i'm using:
<script type="text/javascript">
$(document).ready(function () {
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
var val = $(this).attr("preco").replace(',', '.');
sum += parseFloat(val);
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
</script>
<?php
if (isset($_POST['submit'])){
$transporte = $_POST['metodoenvio'];
(... save into DB)
}
?>
<span id="output"></span> // the sum in html shows up here
<form class="cmxform" id="pedidoForm" method="post" action="">
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
Take a hidden type variable with some id in form tag and put value in hidden variable by jquery like:
$("#hidden_var").val(sum);
Then at the end submit the form
add new hidden input field to the form to hold the sum
<form class="cmxform" id="pedidoForm" method="post" action="">
//add new hidden input field to have the sum
<input id="sum_input" name="sum" type="hidden"/>
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
//Then use the jquery to put the sum to input id sum
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
var val = $(this).attr("preco").replace(',', '.');
sum += parseFloat(val);
});
$("#output").html(sum);
//jquery to put sum into form
$("#sum_input").val(sum);
}
You should split your php server side scripts out of your html/js client side pages. create a separate php page so process the data and call it through an ajax call.
change your submit button to just be a button and attach an onclick event to call a function that will sum the checkboxes and then initiate the and ajax request.
<script>
function sumChecked(){
i = 0;
$.each($('#pedidoForm:ckecked), function({
i++;
});
$.ajax({
url:"yourPHPpage.php",
type:"POST",
data:{"sumVar":i},
success: function(data){
alert ("Process Complete");
}
})
}
...
</script>
...
<form class="cmxform" id="pedidoForm">
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="button" name="submit" id="submit" value="submit" onClick="sumChecked()"/>
</form>
then on your php page catch the $_POST['sumVar'] variable sent through from the form and do whatever you want to server-side with that info.
I have a PHP form with different types of input fields (textbox, radio, checkbox,..) for which I used jQuery. It works fine for all input types except one of the question in my form for which the selected items(movies) by user are stored in an array. I think the image can explain better than me:
As can be seen in the image, selected movies by user are moved to the selected list(an array), while in jQuery validation, input names are "required" and therefore in this case only the value inserted in the textbox (in this case:"frozen") will be stored in database.
This is the code:
<form id="form2" action="page3.php" method="post">
<fieldset id = "q27"> <legend class="Q27"></legend>
<label class="question"> What are your favourite movies?<span>*</span></label>
<div class="fieldset content">
<p>
<div class="movienames">
<div class="field">
<Input type = 'radio' id="selectType" Name ='source' value= 'byTitle'>By title
<Input type = 'radio' id="selectType" Name ='source' value= 'byActor'>By actor
<Input type = 'radio' id="selectType" Name ='source' value= 'byDirector'>By director
</div>
<div id="m_scents" class="field">
<label style="margin-bottom:10px;" for="m_scnts"></label>
<p>
<input class="autofill4" type="textbox" name= "q27[]" id="q" placeholder="Enter movie, actor or director name here" />
<input type="button" value="search" id="btnSearch" />
</p>
<div>
</div>
<div id="basket">
<div id="basket_left">
<h4>Selected Movies</h4>
<img id="basket_img" src="http://brettrutecky.com/wp-content/uploads/2014/08/11.png" />
</div>
<div id="basket_right">
<div id="basket_content">
<span style="font-style:italic">Your list is empty</span>
</div>
</div>
</div>
</p>
</div>
</fieldset>
<script type="text/javascript">
var master_basket = new Array();
selectedMovies = {};
var selected;
var selectedVal;
var selectedDir;
$(document).ready(function () {
$("input[id='selectType']").change(function(){
$("#q").val('');
if ($(this).val() == "byTitle") {
//SOME LINES OF CODE....
.....
} else
if ($(this).val() == "byActor"){
// SOME LINES OF CODE
} else
if ($(this).val() == "byDirector"){
//SOME LINES OF CODE
}
});
$('#btnSearch').on('click', function (e) {
window.textbox = $('#q').val();
window.searchType = $('input:radio[name=source]:checked').val();
popupCenter("movielist.php","_blank","400","400");
});
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k,v) {
var name_and_year = v.movie_name;
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + name_and_year + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
});
}
</script>
// CODE RELATED TO OTHER QUESTIONS IN THE FORM....
//.........
<input class="mainForm" type="submit" name="continue" value="Save and Continue" />
</form>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$('#form2').validate({
rules: {
"q27[]": {
required: true,
},
//OTHER REQUIRED QUESTIONS....
},
errorPlacement: function(error, element) {
if (element.attr("type") == "radio" || element.attr("type") == "checkbox" || element.attr("name") == "q12[]") {
error.insertAfter($(element).parents('div').prev($('question')));
} else {
error.insertAfter(element);
}
}
});
});
</script>
QUESTION:
I have two problems with my code:
When I click on "Save and continue" button to submit this page of
the form, for the mentioned question (the one you could see in the
image), only the value inserted in the textbox will be stored in
database while I need all selected movies in the list will be stored
in separate rows in DB.
The textbox for this question is a hidden field that will be
appeared only if user select one of the radio button values. So, if
user just ignore this question and doesn't select one of radio
button values, then he can simply submit this page and continue
without any error message.
I would like to know if there is a way to customize jQuery validation so that I don't let users to submit this page until they didn't answer the mentioned question?? and then, how could I store the selected items by user in Database instead of textbox value?
All ideas would be highly appreciated,
To submit the basket movie items you can add a hidden input field. You would get something like this:
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + name_and_year + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
$("#basket_content").append("<div type='hidden' name='basket_movie[]' value='"+v.movie_name+"' />");
Using this, there will be an array like $_POST['basket_movie'] which contains the movie names of the movies in the basket.
If you want to prevent submitting, when the input box isn't filled you just add an action listener on form submit and count the item_list items. If it's 0 then don't submit. Add something like this to prevent form submitting when there are no items added to the basket:
$(document).on('submit', '#form2',function(e)
{
if($('.item_list').length == 0)
{
e.preventDefault();
}
});
I am using Json to retrieve elements from mysql and insert them into form boxes. Displaying in form boxes(text type) was not a problem but in my html one of my form structure is dropbox ... How should i display info that is in the database to the one that is in dropbox??
Here is the code that i used for displaying elements in form type (text). One of them is dropbox in the html.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='rno']").val(json.rno);
$("input[name='url']").val(json.url);
}, "json");
});
</script>
</head>
<body>
<form id="myForm" method="post">
id: <input type="text" name="id"/>
<input type="button" id="button1" value ="Get"/>
<input type="button" id="button2" value="Submit to script 2" />
<p>title:<input type="text" name="title"/></p>
<p>Report No:<input type="text" name="rno"/></p>
<p>URL:<input type="text" name="url"/></p>
Institution: <select name="institution">
<option value="abc">abc</option>
<option value="cdf">cdf</option>
</select>
</form>
<div id="age"></div>
</body>
</html>
PHP part or script_1.php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
//connect to DB part
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
**//i am not using $row['institution'] (no institution or dropbox part)**
$abc_output = array('title' => $row['title'],'rno' => $row['reportno'],'url' => $row['calc_url']);
}
}
echo json_encode($abc_output);
}
}
?>
Help appreciated.John.
var option1 = new Option("InstitutionName1","InsitutionValue1");
var option2 = new Option("InstitutionName2","InsitutionValue2");
document.myForm.institution.options.length = 0;
document.myForm.institution.options[0] = option0;
document.myForm.institution.options[1] = option1;
This is the way its done normally. In this particular case, you may want to have a for loop or something or jQuery's each(..).
#John
You can put the following snnipet of code at the end of the script tag:
for (item in json.institution) {
$('select[name="institution"]').html('').append('<option value="' + json.institution[item].value + '">' + json.institution[item].text + '</option>');
}
where:
json.institution is a named array that will be returned along with the other form fields by your .php script.
json.institution[item].value is the value of each option.
json.institution[item].text is the text of each option.
The .html('') code is for clear the previous loaded select options.