Select Field controlling Character Limit - php

Does anyone know how to allow this character countdown to be controlled by pre-determined variables that are linked to the select field options?
var large = 300
var medium = 200
var small = 100
I appreciate any input greatly.
Example Code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function updateCountdown() {
var remaining = 50 - jQuery('#post').val().length;
jQuery('#character_limit').text(remaining + ' characters remaining.');
}
jQuery(document).ready(function($) {
updateCountdown();
$('#post').change(updateCountdown);
$('#post').keyup(updateCountdown);
});
</script>
<textarea id="post" cols="40" rows="3" maxlength="500"></textarea>
<div id="character_limit"></div>
<select name="product" id="product">
<option value="large">Large Product</option>
<option value="medium">Medium Product</option>
<option value="small">Small Product</option>
</select>

You can achieve this by firstly changing the options of the select element to have a value equal to the length required by that type of product:
<select name="product" id="product">
<option value="300">Large Product</option>
<option value="200">Medium Product</option>
<option value="100">Small Product</option>
</select>
From there you can retrieve the selected value (converting it to a number) before subtracting the number of used characters. Also note that you would also now need to update the count on the change event of the #product field. Try this:
function updateCountdown() {
var charLimit = parseInt($product.val(), 10)
var remaining = charLimit - jQuery('#post').val().length;
jQuery('#character_limit').text(remaining + ' characters remaining.');
}
var $product = $('#product');
updateCountdown();
$('#post, #product').change(updateCountdown);
$('#post').keyup(updateCountdown);
Example fiddle

Related

How to add values of generated textbox in database using mysqli

This code somehow stores only the value of last textbox. When we generate 3 textboxes, only the value of 3rd is stored in database instead of all. I want to store all the generated textbox values in the database
<?php if(isset($_POST['submit'])){
$num_cat = $_POST['num_cat'];
$text = $_POST['category'];
foreach ($text as $key) {
// echo $key."\n";
}
$insertquery = mysqli_query($con, "INSERT INTO accounts (accountusername, accountemail) VALUES('".$num_cat."', '".$key."')");
if(!$insertquery){
echo "Error".mysqli_error($con);
}
} ?>
<script type="text/javascript">
//when the webpage has loaded do this
$(document).ready(function() {
//if the value within the dropdown box has changed then run this code
$('#num_cat').change(function(){
//get the number of fields required from the dropdown box
var num = $('#num_cat').val();
var i = 0; //integer variable for 'for' loop
var textboxes = ''; //string variable for html code for fields
//loop through to add the number of fields specified
for (i=1;i<=num;i++) {
//concatinate number of fields to a variable
textboxes += 'Category'+i+': <input type="text" name="category[]' + i + '" placeholder = "category_' + i + '" /><br/>';
}
//insert this html code into the div with id catList
$('#catList').html(textboxes);
});
});
</script>
<form method="post" action="">
Number of fields required:
<select id="num_cat" name="num_cat">
<option value="0">- SELECT -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="catList"></div>
<input type="submit" name="submit" value="Submit"/>
</form>
If you update your javascript to write this (remove ' + i + ' from the name):
textboxes += 'Category'+i+': <input type="text" name="category[]" placeholder = "category_' + i + '" /><br/>';
then $_POST['category'] will be an array. It then depends how you want to store the values, but assuming you'll want three rows, you'll need to do this:
foreach ($_POST['category'] as $key) {
$insertquery = mysqli_query($con, "INSERT INTO accounts (accountusername, accountemail) VALUES('".$num_cat."', '".$key."')");
if(!$insertquery){
echo "Error".mysqli_error($con);
}
}
This is explained in the PHP manual.
Please have a look at how can I prevent SQL-injection in PHP? as well, because your current code is vulnerable to simple exploits.

Dynamic Form Submission to database

I've got an HTML form that has some static fields and some fields that are dynamically added with javascript. It looks sort of like this
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
for(i=0; i < val; i++)
{
//texts.innerHTML += '<div><input type="text" name="t_' + i + '" value="select_' + i + '" /></div>';
texts.innerHTML += i + '<div><input type="text" name="t_' + i + '" /></div>';
}
}
}
</script>
<body>
<form method="POST" action="connection.php">
Question:<br>
<textarea name="question" cols="35" rows="5"></textarea><br>
<select id="select" size="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div id="texts"></div>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
when the user clicks it adds a text box field. How does the data stored into the database.Kindly suggest me an idea what are the resources used to do this .Thanks in advance
Good day Shashak
In order to submit the data of your form into the database, regardless of the javascript of the form the data should be passed using in your case the POST method to a script 'connection.php' in your case.
This script should contain a way to connect to your database followed by the logic that will validate your data and then at the end if the validation is successful a database query that will INSERT the data into your database.
Which is your level of understanding when it comes to PHP or any other server-side scripting language and databases? - I will be able to give you more information if I know what you know.
I think instead of giving the textbox the name format t_1 , t_2 you can give it as an array like below
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
for(i=0; i < val; i++)
{
//texts.innerHTML += '<div><input type="text" name="t_' + i + '" value="select_' + i + '" /></div>';
texts.innerHTML += i + '<div><input type="text" name="txt_name[]" /></div>';
}
}
}
</script>
<body>
<form method="POST" action="connection.php">
Question:<br>
<textarea name="question" cols="35" rows="5"></textarea><br>
<select id="select" size="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div id="texts"></div>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
PHP
It will post data like this:
Suppose you select option 2.
$inputs = $_REQUEST['t']; // change the name like this name[]
$textarea = $_REQUEST['textarea'];
$selectbox = $_REQUEST['select']; // you should define the name of the select box as i used 'select'
insert into mysql
$conn = mysql_connect('localhost', 'db user', 'db password');
mysql_select_db('database name');
for($i=0; i<count($inputs); $i++) {
$sql = "insert into <table name> (textarea, inputs) values ($inputs[$i], $textarea)";
mysql_query($sql);
}
it will store each row as per your selection of input text boxes.
Note: Modify the query as per your requirement.

jquery change form button value in php

I have a form with 2 dropdowns, 'Type' and 'Level', eg
Type
-----
Hotel
Restaurant
Casino
Level
-----
1
2
3
And a submit button which shows the price based on whichever options are selected in the dropdown. The price is calculated by some basic maths on the fly.
How can I do this using jquery?
Is it using onchange() or something?
$("#button_id_here").val("$your_amount_here");
If you want it to update automatically, bind it to the change event in the select/dropdowns
$("#select_id_here").change(function(){
//"basic maths"
$("#button_id_here").val("$your_amount_here");
});
You want more help, we would need to see code.
HTML:
<form>
<fieldset>
<p>
<label for="selectType">Type:</label>
<select id="selectType" name="type">
<option value="Hotel" data-cost="40">Hotel</option>
<option value="Restaurant" data-cost="80">Restaurant</option>
<option value="Casino" data-cost="35">Casino</option>
</select>
</p>
<p>
<label for="selectLevel">Level:</label>
<select id="selectLevel" name="level">
<option value="1" data-cost="0">1</option>
<option value="2" data-cost="15">2</option>
<option value="3" data-cost="30">3</option>
</select>
</p>
<p>
Total Cost: $<span id="cost">0</span>
</p>
<p><input type="submit" value="Go!"></p>
</fieldset>
</form>
jQuery:
$(function() {
$("#selectType, #selectLevel").change(function() {
var type = $("#selectType"),
level = $("#selectLevel"),
cost = $("#cost"),
typeCost = type.find(":selected").data('cost'),
levelCost = level.find(":selected").data('cost'),
total = typeCost + levelCost;
cost.html(total);
}).change(); // invoke the .change() trigger
});
See it in action here
You might want to also set something like "data-multiplier" for the level... whereas level 2 may have a 1.5x multiplier, and level 3 may have a 2x multiplier. You'd have to adjust the jQuery accordingly as well (total = typeCost * levelCostMultiplier, for example).
You can check if a select list has changed via jQuery's change() function.
Here's a way to do it:
HTML:
Type
<select name="type" id="type">
<option value="hotel" selected>Hotel</option>
<option value="restaurant">Restaurant</option>
<option value="casino">Casino</option>
</select>Level
<select name="level" id="level">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="result"></div>
jQuery:
var result = 1;
$("#type").change(function () {
var val = $(this).val();
$("#result").html("Type is " + val + ", level is " + $("#level").val());
});
$("#level").change(function () {
var val = $(this).val();
// Some basic math
result = parseInt(val) * 5;
$("#result").html("Type is " + $("#type").val() + ", level is " + val + ", result: " + result);
});
And the relevant jsfiddle:
http://jsfiddle.net/y2s4v/1/

dynamic selection option in JS

I have a date SELECT/OPTION create by JS.
The code works fine, but when this file post to different page. The SELECT didn't retain the value when I click back button from browser or when I post it back. The day and year become blank. Copy the code and try it in your browser you will understand what I mean.
Any suggestion?
<script>
function populate(s1, s2){
var s1=document.getElementById(s1);
var s2=document.getElementById(s2);
s2.innerHTML="";
if(s1.value==""){
var optionArray=['|Day'];
}
else if(s1.value=="01" || s1.value=="03" || s1.value=="05" || s1.value=="07" || s1.value=="08" || s1.value=="10" || s1.value=="12"){
var optionArray=['|Day'<?PHP for($d=1; $d<32; $d++){echo ", '$d|$d'";}?>];
}
else if(s1.value=="04" || s1.value=="06" || s1.value=="09" || s1.value=="11"){
var optionArray=['|Day'<?PHP for($d=1; $d<31; $d++){echo ", '$d|$d'";};?>];
}
else if(s1.value=="02"){
var optionArray=['|Day'<?PHP for($d=1; $d<30; $d++){echo ", '$d|$d'";};?>];
}
for(var option in optionArray){
var pair=optionArray[option].split("|");
var newOption=document.createElement("option");
newOption.value=pair[0];
newOption.innerHTML=pair[1];
s2.options.add(newOption);
}
}
function populate_year(s2, s3){
var s2=document.getElementById(s2);
var s3=document.getElementById(s3);
s3.innerHTML="";
if(s2.value==""){
var optionArray=['|Year'];
}
else if(s2.value=="29"){
var optionArray=['|Year'<?PHP for($y=1936; $y<2013; $y=$y+4){echo ", '$y|$y'";};?>];
}
else if(s2.value!=="29"){
var optionArray=['|Year'<?PHP for($y=1933; $y<2013; $y++){echo ", '$y|$y'";};?>];
}
for(var option in optionArray){
var pair=optionArray[option].split("|");
var newOption=document.createElement("option");
newOption.value=pair[0];
newOption.innerHTML=pair[1];
s3.options.add(newOption);
}
}
</script>
<select id="s1" onchange="populate(this.id, 's2')" name="month" style="width:80px; font-family:arial;">
<option value="">Month</option>
<option value="01">Jan</option>
<option value="02">Feb</option>
<option value="03">Mar</option>
<option value="04">Apr</option>
<option value="05">May</option>
<option value="06">Jun</option>
<option value="07">Jul</option>
<option value="08">Aug</option>
<option value="09">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select id="s2" onchange="populate_year(this.id, 's3')" name="day" style="width:65px; font-family:arial;">
<option value="">Day</option>
</select>
<select id="s3" name="Year" style="width:80px; font-family:arial;">
<option value="">Year</option>
</select>
The issue is the html for the day and year are dynamically generated, so the value of the last selected index can't be injected into the select boxes (because the select boxes haven't been made yet).
I have two suggestions:
1) I wouldn't populate each select option dynamically. Perhaps have 3 select boxes in the DOM for each of the three different types of day selections (30 days, 31 days, and for February). The JavaScript that executes when selecting a month doesn't populate the select box, but shows the appropriate select box for days and hides the other two. By default, they would all be hidden. You would then repeat something similar for the year select box.
2) If you must dynamically generate your content, I would attempt storing the selected index in Local Storage (or whatever other means tickles your fancy). For example, if someone selects January, 23, 2012.. store this in Local Storage. This could look something like this:
localStorage['dateSelect'] = '01|23|2012';
This is just an example of what you could do. Then, you could read from it upon page load.
var selectedMonth;
var selectedDay;
var selectedYear;
if (localStorage['dateSelect']) {
var storage = localStorage['dateSelect'].split('|');
selectedMonth = storage[0];
selectedDay = storage[1];
selectedYear = storage[2];
}
Let me know if you need any more help :)
Good luck!
-Graham

Update Price based on dropdown list selection

I have a dropdown list populated by mysql working perfectly, I also have it displaying the price set by mysql, so far i'm happy.
What the issue is as it's a multiple dropdown list, it will only display what is chosen first, if I pick 2 or more selections, only the first price is shown.
My second issue is I want the prices to add up i.e. 1st Selection's price is £1.99, 2nd Selection's price is £2.99 so the total should be £4.98
Finally once i have all this working, I want to continue this onto the 2nd / 3rd / 4th dropdown boxes so that all the boxes add up giving me a combined total.
Here's my html code to show you what i'm using:
<form method="post" action="" name="form1">
<?
include 'classes.php';
$query="SELECT * FROM Sex_Table";
$result=mysql_query($query);
?>
<select data-placeholder="Your Favorite Football Team" class="chzn-select" multiple tabindex="6" id="Sexdiv" name="Sexdiv" style="width: 300px;" onChange="getClothing(this.value),changePrice()">
<option>Select Colour Type</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['ID']?> sex_price="<?=$row['Price']?>"><?=$row['Sex_Name']?> (£<?=$row['Price']?>)</option>
<? } ?>
</select><br /><br />
<p id="Clothingdiv">
<select style="width: 300px;" name="Clothing" disabled='disabled'>
<option>Select Sex First</option>
</select>
</p><br />
<script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true}); </script>
</form>
and here's my js:
function changePrice() {
var sex_price = $("option:selected").attr("sex_price");
$("#price_div").html("Price = £" + sex_price);
}
Thanks
Below is an example of what you're trying to do, I've given each select element I want to calculate the total for a class so that they are not mixed up with other elements.
jQuery
<script>
$(document).ready(function() {
$('.calculate').change(function() {
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
$('#total').text('£' + total.toFixed(2));
});
});
</script>
HTML
<select class="calculate" name="select-1">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<select class="calculate" name="select-2">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<select class="calculate" name="select-3">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<span id="total">£0</span>
This will update the contents of total with the total price of each select element with class calculate when one of them is changed.
select with multiple should have the size attribute set as well, like this:
<select data-placeholder="Your Favorite Football Team" class="chzn-select" multiple="multiple" tabindex="6" id="Sexdiv" name="Sexdiv" style="width: 300px;" onChange="getClothing(this.value),changePrice()" size="10">
Your jQuery script:
$('select#Sexdiv').change(function() {
var value = 0;
$("select#Sexdiv option:selected").each(function(){
value += parseFloat($(this).val());
});
$("#price_div").html("Price = £" + value);
});
Hmm?

Categories