Dynamically increase and decrease numbers in JavaScript - php

I would like to know how to dynamically increase and decrease numbers in JavaScript.
The users buys an item and I have a input field "quantity" with a number and two buttons: One to add and another to remove.
My code is the following
<td class="quantity">
-
<input type="text" id="purchase_quantity" min="1" max="99" delta="0" cost="<?php echo$poupa ?>" name="purchase_quantity" value="1" />
<a href="#" class="addItem" >+</a>
</td>
How can I have it decrease the number of the input field when I click on the "-" and increase the number of the input field when clicking on the "+"?

var input = document.getElementById("YOUR_INPUT_ID");
function minus(){
var num = +input.value;//+ for convert from string to number
num--;
input.value = num;
}
function plus(){
var num = +input.value;//+ for convert from string to number
num++;
input.value = num;
}
http://jsfiddle.net/VY9tE/
One more example with your html form and with check count(0..99):
http://jsfiddle.net/VY9tE/2/

decrease:
-
increase
+
Assuming you can use jquery since you have it tagged.

Markup (changed the ID on the text input to a class):
<td class="quantity">
-
<input type="text" class="purchase_quantity" min="1" max="99" delta="0" cost="" name="purchase_quantity" value="1" />
+
</td>
JavaScript (uses jQuery):
$(function() {
$('.removeItem').click(function() {
// Find the appropriate quantity input
var target = $(this).siblings('.purchase_quantity');
// Get the current quantity
var currentQuantity = $(target).val();
// Not allowed to go below zero
if (currentQuantity > 0) {
// Update input with decreased quantity
$(target).val(--currentQuantity);
}
});
$('.addItem').click(function() {
// Find the appropriate quantity input
var target = $(this).siblings('.purchase_quantity');
// Get the current quantity
var currentQuantity = $(target).val();
// Update input with increased quantity
$(target).val(++currentQuantity);
});
});
See it in action.

Related

how to pass java script value to php in codeigniter

i have a form where two fields are dynamically generated through java script when a button is clicked.when the button is clicked each time,the two text field will generate again and again.now i have got the count of text field generated in a hidden field in JavaScript.How can i get the value of hiddenfield in controller and insert the values of text fields in database,by appending comma in data when the text box value is entered each time.please help me.
my javascript is
<script>
var countbox=0;
var textbox1=0;
var textbox2=0;
function getField()
{
var newtextbox1="name1"+countbox;
var newtextbox2="name2"+countbox;
document.getElementById('renderDiv').innerHTML+='<br/><input type="text" id="'+newtextbox1+'" name="'+newtextbox1+'" /><br/><input type="text" id="'+newtextbox2+'" name="'+newtextbox2+'" />';
document.getElementById('renderDiv').innerHTML+='<br/><input type="hidden" id="hiddentextField" name="hiddentextField" value="'+countbox+'" />';
countbox +=1;
}
</script>
my html code is
<input type="button" id="button1" onclick=getField();/>
<div id="renderDiv">
</div>
inside this div the two textfield is generated along with the hidden field
i am not getting the value of textfield in controller while submitting and i am not getting the count of textfield.i tried like $hiddenfield=$this->input->post('hiddentextField');
you will have to post the variable inorder to pass this to the server
<script>
var countbox=0;
var textbox1=0;
var textbox2=0;
function getField()
{
var newtextbox1="name1"+countbox;
var newtextbox2="name2"+countbox;
document.getElementById('renderDiv').innerHTML+='<br/><input type="text" id="'+newtextbox1+'" name="'+newtextbox1+'" /><br/><input type="text" id="'+newtextbox2+'" name="'+newtextbox2+'" />';
document.getElementById('renderDiv').innerHTML+='<br/><input type="hidden" id="hiddentextField" name="hiddentextField" value="'+countbox+'" />';
countbox +=1;
window.location.href = "index.php?name=" + countbox-1;
//change index.php to your page name
}
</script>
then in the same page
<?php
$hiddenfield=$_GET["name"];
?>
I had the same problem before, what I did is I insert those text box inside a table, lets say, tableSample
then I use jQuery find
var _content = '';
var _findcontent = $("#tableSample");
_findcontent.find("tr").each(function(){
$(this).find("td").each(function(){
$(this).find("input").each(function(){
_content += $(this).val+'~'+$(this).attr("id")+'|';
});
});
});
Then use ajax to pass it to your PHP
$.post("<?php echo site_url('controller_name/method_name'); ?>",
{
content : _content
}
,function( _data){
jAlert("alert",_data,"alert");
});
In your PHP, you can use explode to get the desired values,
$content_from_page = $this->input->post("content");
$explode_string = array();
$explode_string = explode("|",$content_from_page );
$explode_arr = array()
for($x=0;$x<count($explode_string)-1;$x++)
{
$explode_arr[] = explode("~",$explode_string[$x];
}
then print_r($explode_arr); to check
*Note: The only problem with this approach is that, if the character that is inserted into the textbox is ~ or |, coz that is the delimiter used.

add values of multiple input boxes in Jquery

i am working in a code igniter. i have a form which contain three input boxes in a row . ..i put them in a for loop which is less then five ..so now my form has five rows with three input boxes in a row .. now what i am doing write now i am adding the values of two input boxes and displaying in 3rd input box .. now what i want to do is when every "total"(3rd input box) is filled .. then i am gonna add all the totals and then display all the totals in last box which i display at the bottom ..
here is my view
<td><input type="text" id = "price_<?php echo $i ?>"
onkeyup='addition(<?php echo "$i"?>)'>
</td>
<td> <input type="text" id = "quantity_<?php echo $i ?>" onkeyup='addition(<?php echo "$i"?>)'>
</td>
<td><input type="text" id = "total_<?php echo $i ?>">
</td>
<?php echo form_input($subtotal)?></td> // here i want to display sum of all the totals
here is my javascript..this function is multiplying the price and quantity ..i mean first and 2nd input box and then displaying in the 3rd box ..
function addition (obj)
{
var subtotal = 0;
var num1=parseInt($('#price_'+obj).val());
var num2=parseInt($('#quantity_'+obj).val());
var num4=parseInt($('#total_'+obj).val());
if ($('#price_'+obj).val() !='' && $('#quantity_'+obj).val() !='')
{
var num3=num1*num2;
$('#total_'+obj).val(num3);
}
else
{
$('#total_'+obj).val('');
}
}
i have uploaded the image also ..
I see that you use jQuery, I have modified your code a bit to use jQuery better. You can see the demo at JsBIN
The idea is lock all "total" cell, when you update one "total" cell by calculating the result. Sum all "total" cell to the "grand-total" cell. I listen on the "keyup" event.
Here is jsFiddle example: http://jsfiddle.net/Ner7M/2/
Code of interest:
var table = $('table');
// nth-child is 1-based, not 0
function totalColumn(table, idx) {
var total = 0;
var tds = $('table')
.find('tr td:nth-child(' + idx + ') input')
.each(function() {
total += parseInt($(this).val());
});
return total;
}
totalColumn(table, 3);

Change text input values dynamically

My question might be quite easy for you guys, but it's hard for me...
I have a text field and I want to change its value between once <label id="some_id"> is clicked. Until what I've described now, I can do it myself with jQuery, but here comes the complex part (for me, obviously):
I have two values I want for that text field, and once that <label> is clicked, it switches to the value that isn't shown, but once we click it again, it goes back to the original text the text field contained.
I have to keep my jQuery/JS internal because I get the desired values from the database and I don't want to make my .js files .php.
This is what I got:
<label for="html" onclick="$('#html').val('<?php echo $image->convert('html_b', $image_data['image_link']); ?>')">HTML:</label>
<input type="text" id="html" value="<?php echo $image->convert('html_a', $image_data['image_link']); ?>" readonly />
It does the first part I need, changing the value of the field to the new value, but once that button gets clicked again, I want the original text.
Thank you.
You can compare its current value to the available possibilities.
<label id="toggle" for="stuff">I'm a label</label>
<input type="text" val="" name="stuff" id="stuff">​
var possibilities = ["foo", "bar"];
$('#toggle').click(function(){
var old_val = $("#stuff").val(), new_val;
if (old_val == possibilities[0])
new_val = possibilities[1];
else
new_val = possibilities[0];
$("#stuff").val(new_val);
});​
demo
First, don't use inline JavaScript.
You can use a combination of .toggle() and data-* attributes for this. For example, using a data-toggle attribute for the value you want to toggle with.
<label for="html" data-toggle="This is a placeholder">HTML:</label>
<input type="text" id="html" value="This is my real value" readonly>​
$("label[for][data-toggle]").each(function() {
var $this = $(this);
var $for = $("#" + $this.attr("for"));
var originalValue;
$this.toggle(function() {
originalValue = $for.val();
$for.val($this.data("toggle"));
}, function() {
$for.val(originalValue);
});
});​
See it here.
UPDATE #1
I added usage of for attribute of <label>.
UPDATE #2
If you don't want to use .toggle() due to the deprecation notice.
$("label[for][data-toggle]").each(function() {
/* cache */
var $this = $(this);
var $for = $("#" + $this.attr("for"));
var originalValue = $for.val();
/* state variable */
var which = 0;
$this.click(function() {
$for.val(which ? originalValue : $this.data("toggle"));
which = 1 - which;
});
});​
See the non-.toggle() alternative here.
For doing this, on the first button click you need to store the current value of input in some variable and then on 2nd click you can assign that variable to input value. If you donot want to have js file, you can simply use <script></script> tags to write the jquery.
`<label id="label" onclick="replaceText('newvalue')">Click Mee</label>
<input id="html" type="text" value="some value">
<script>
var currentValue="";
function replaceText(newval){
currentValue= $("#html").val();
if(currentValue!=newval)
$("#html").val(newval);
$("#label").attr("onclick","replaceText('"+currentValue+"')");// Here we assigned the other value to label onclick function so that it will keep on toggling the content.
}
</script>`
DEMO HERE
You can store the values into JavaScript variables and use jQuery click method instead of onclick attribute.
var def = "<?php echo $image->convert('html_a', $image_data['image_link']); ?>",
up = "<?php echo $image->convert('html_b', $image_data['image_link']); ?>";
$('label[for=html]').click(function() {
$('#html').val(function(i, currentValue) {
return currentValue === def ? up : def;
});
});

How to pass a javascript variable to PHP

Im creating a dynamic form with a button called "Add more rows" when this is clicked a JavaScript function creates a new row of textboxes with the appropriate id.
The problem is, how do I pass a counter variable from my JavaScript function to my next php page so it nows how many rows of textboxes to receive $_POST.
Ive got my JavaScript function however I'm missing data from the rows it creates itself.
any ideas?
Thanks
This is my js function
window.onload=function()
{
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++)
{
if(inp[c].value=='add')
{
inp[c].onclick=function()
{
n=15;
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='time'+n;
document.getElementById('txtara').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='event'+n;
document.getElementById('txtara').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='supplies'+n;
document.getElementById('txtara').appendChild(x)
var sel = document.createElement('select');
y = document.createElement('option');
y.value = 'Yes';
y.name = 'success' + n;
y.innerHTML = y.value;
x = document.createElement('option');
x.value = 'No';
x.name = 'success' + n;
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
document.getElementById('txtara').appendChild(sel);
document.getElementById('txtara').appendChild(sel);
document.getElementById('txtara').appendChild(sel);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='comment'+n;
document.getElementById('txtara').appendChild(x)
document.getElementById ('txtara').innerHTML += '<br>';
n++;
}
}
}
//-->
}
You should add an <input type="hidden" name="num_rows" value="0"> to your form and update its value to be the row count when the form is submitted.
Assuming you want the number for easing the way you fetch the data on the server side.
There is a very simple way of doing this.
Let's say you have many input's of the same logical data type you want to handle, like:
<input type="text" name="names" value=""> And you create more of it dynamically.
Of course, you want them individual names to fetch the data, so you do like:
<input type="text" name="names[]" value=""> OR if you have more input for one entity, to make it consistent: <input type="text" name="names[1]" value=""><input type="text" name="eye_colours[1]" value=""> , so you can add a number in the brackets.
What do you do on the PHP side?
if( isset($_POST['names']))
foreach($_POST['names'] as $key => $val){ ... }
PHP parses it as an array, hurray! :)
You can add a name attribute to your form elements. As your form contains multiples elements (and you don't know how much elements), this name attribute must be in the form "my_name[]". The [] chars indicates a collection of elements. So your HTML code could look like this:
<form method="POST" action="mypage.php">
<input type="text" name="whatever[]" value="first" />
<input type="text" name="whatever[]" value="second" />
<input type="text" name="whatever[]" value="third" />
<input type="submit" />
</form>
Then, when the form will be submitted, you can get the values using the PHP variable $_POST['whatever']. This variable is an array and contains all the values of the "whatever" inputs like this:
$myValues = $_POST['whatever'];
// $myValues = array( 0 => "first", 1 => "second", 2 => "third" );
Then, if you want to do some actions with each rows, do a for each loop. If you want to know how many lines were submitted, you can simply do a count.
Since javascript is a client-side language, this is not possible :(
but, you can use AJAX to send a local javascript var to the server by GET, or POST
You can use PHP to output javascript code. If you have a value you can output it directly in javascript, or if you have a more complex value, you can encode it using json_encode.
You don't need to. POST will carry the number of rows for you without a problem. Simply do count($_POST) to get the number of values posted. Or, if you use my suggested version below, use count($_POST['time']) to get the number of time values.
var types = ['time', 'event', 'supplies'];
function createInput( i, n )
{
var base = isNaN( i )? i: types[ i ];
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name= base + "[" + n + "]"; // this will make $_POST[<base>] an array with n as the index.
document.getElementById('txtara').appendChild(x)
}
window.onload=function()
{
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++)
{
if(inp[c].value=='add')
{
var n = 15; // move n out here. Otherwise n will always = 15.
inp[c].onclick=function()
{
for( var i = 0; i < types.length; i++ )
{
// passing both variables in will avoid any possible collisions.
createInput( i, n );
}
var sel = document.createElement('select');
sel.name = 'success[' + n + ']';
y = document.createElement('option');
// option has no name attribute (http://www.w3schools.com/tags/tag_option.asp)
y.value = 'Yes';
y.innerHTML = y.value;
x = document.createElement('option');
x.value = 'No';
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
// you had this three times... why?
document.getElementById('txtara').appendChild(sel);
createInput( 'comment', n );
document.getElementById ('txtara').innerHTML += '<br>';
n++;
}
}
}
}

Adding a value to a dynamic form

I need to pull the contents of some input text boxes into a database. The first box is displayed but I'm using this Javascript to create some of them dynamically:
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter !== limit) {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <input type='text' name='myInputs[]' size=40>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
How can I add a value to the form which will be different for each box created so I can reference them in PHP?
Thanks!
Edit: scratch that, I've never tried using an array to group inputs, but it works so use that instead. Keep the name of your inputs as myInputs[] but reference in php like this:
$_POST[myInputs][0]
for your first field and
$_POST[myInputs][1]
for the second etc..
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>//use jQuery. it makes life easy.
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.2.js"%3E%3C/script%3E'))</script>
<script>
$(document).ready(function(){//fire when the page is ready
$('.addFields').click(function(){//any time someone clicks on a element with the class addFields
if( $('.myInputs').length < 10 ){ // if there are less than 10 input fields...
$($(this).attr('rel')).append("<br/><input type='text' name='myInputs[]' class='myInputs' size='40' id='myInputs"+($('.myInputs').length)+"'>");
// add another input field with an ID equal to it's place in line.
}
});
});
</script>
</head>
<body >
<a rel="#addToMe" class="addFields" href="#">Add a field</a><!-- the triggering element this can be anything that can be clicked on-->
<div id="addToMe"><!-- the element holding our input fields, new ones get added to the back of here, note that the trigger's rel attribute is the ID of this attribute and started with a "#' ID identifier-->
<input type='text' name='myInputs[]' class='myInputs' size='40' id='myInputs0'>
</div>
</body>

Categories