How to add another field dynamically - php

How to add the elemen statically, but invisible at design time, and then show it dynamically when some event come.
at this case i use code HTML like these
<input type="text" name="field_1"/>
<input type="text" name="field_2"/>
<input type="text" name="field_3"/>
<input type="text" name="field_4" style="display:none"/>
<input type="text" name="field_5" style="display:none"/>
add another field
at first time, field_4 and field_5 is invisible right? but when i click "add another field" then field_4 and field_5 should be visible.
is there any tips?
i dont mind if someone could solve this case with PHP, maybe this case is like FB, when u input ur contact info (ur number phone) if u have just 1 number it means u dont need to click "Add another phone", but if u have 2 or more number u could click it and field text would appear as many as u had clicked.

document.getElementById('field_4').display = 'inline'
That should work for your purposes.
You could just add a new element when you click the button instead of showing old invisible elements though.
var index = 2;
document.getElementById('addBtn').addEventListener('click', function() {
var inp = document.createElement('input')
inp.setAttribute('type', 'text')
inp.setAttribute('name', 'field_' + index)
document.insertBefore(inp, document.getElementById('addBtn'))
index ++;
})

First of all, you don't need to have those hidden fields. That's not "adding them dynamically".
<input type="text" name="field_1"/>
<input type="text" name="field_2"/>
<input type="text" name="field_3"/>
add another field
Next, tell the link to perform a JavaScript function when clicked:
add another field
Write your javascript:
;(function) {
var counter = 3; //This is set to the number of initial fields.
function addField(e) {
e = e || window.event; //Normalize the event.
counter++; //Increment the counter.
//Create the new element.
var element = document.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("name", "field_" + counter);
//Insert it before your link.
e.target.parentNode.insertBefore(element, e.target);
}
})();

Related

Multiply two input field and result in the third field which changes when either of the input field changed with jQuery

I need to Multiply two user Input Fields and show the results in the third field. The Result field must change when either of the User Input fields are changed.
<input type="number" name="rate" id="rate" />
<input type="number" name="box" id="box" />
The result should be in a third field which changes when either of the two above fields is changed. This totally depends on the user input
<input type="number" name="amount" id="amount" readonly />
I need to do this Multiplication with Jquery.
Thanks in advance
Try this : bind change event listener for rate and box input box and inside it multiply the values to put it in amount input.
$('#rate, #box').change(function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
DEMO
You can use keyup event to calculate amount as soon as you enter other fields
$('#rate, #box').keyup(function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
DEMO
Try this : bind input event listener on rate and box input box and inside it multiply the values to put it in amount input.
The input event only fires when the value of the input has changed whereas change only fires once the field has lost focus. input fires immediately
$('#rate, #box').on('input',function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="number" name="rate" id="rate" value=""/>
<input type="number" name="box" id="box" value=""/>
<input type="number" name="amount" id="amount" readonly />
Here is my 2 cents on the above scenario -
http://jsfiddle.net/ak9ejpne/3/
My aim was to keep the code thin & clean and with some MVC flavor.
function Operand(a,b){
this.a = parseInt(a);
this.b = b;
this.c = (this.a)*(this.b);
this.set = function(key,edit){
this[key] = edit;
this.c = (this.a)*(this.b);
};
return this;
}
Do let me know if it is a useful approach for you :)
You can Try It.
<script type="text/javascript">
$("#txtOne,#txtTwo").on("change keyup", function(e){
var txtOne = parseFloat($("#txtOne").val());
var txtTwo = parseFloat($("#txtTwo").val());
var result = txtOne * txtTwo ;
if (!isNaN(result)) {
$("#txtAmount").val(result);
}
});
</script>

PHP POST values from selected textboxes

I'm trying to create a comparison page/form using a combination of PHP, HTML and jQuery. The ideal effect I like to create as below
<form>
left | right
[text1.l] | [text1.r]
[text2.l] | [text2.r]
submit
</form>
Where [] denotes an input text box. For a particular use case, the user select would select either the left or right textbox for each row and post the form. Essentially I am only interested in the value of the text box selected when I process the form.
I was thinking of perhaps using a radio button as I only allow selection of one box per row, but I am unsure how set this up to retrieve the text box value.
Any helps would be appreciated, cheers.
JSFIDDLE http://jsfiddle.net/Bq8AF/
Form
<form method="post" action="process.php" class="form">
<fieldset id="left">Left
<input type="text" name="foo-left-1" size="50" />
<input type="text" name="foo-left-2" size="50" />
</fieldset>
<fieldset id="right">Right
<input type="text" name="foo-right-1" size="50" />
<input type="text" name="foo-right-2" size="50" />
</fieldset>
<input type="submit" value="Submit">
</form>
JS + jQuery
$("input[type=text], textarea").focus(function(){
// Check for the change from default value
if(this.value == this.defaultValue){
this.select();
}
// get the name of the field, e.g. foo-left-1
//alert(this.name);
var fieldNameSplitted = this.name.split("-");
// recombine + switch "left" to "right" and vice versa
var fieldNameOtherSide = '';
// the ident remains the same (e.g. foo-)
var fieldNameOtherSide = fieldNameSplitted[0] + "-";
// left/right switch (e.g. foo-left, gets foo-right and vv)
if(fieldNameSplitted[1] == 'left') { fieldNameOtherSide += 'right-'; }
if(fieldNameSplitted[1] == 'right') { fieldNameOtherSide += 'left-'; }
// row number (e.g. foo-right-2)
fieldNameOtherSide += fieldNameSplitted[2];
// now we have the name of the field on the other side of the row, right?
//alert(fieldNameOtherSide);
// use that as jQuery selector and disable the element
// because the user has selected the other one
// and when the form is send disabled fields will not be send
// http://www.w3.org/TR/html401/interact/forms.html#disabled
$('input[name=' + fieldNameOtherSide + ']').prop("disabled", true);
});
The user selects the textbox by click.
When "submit" is clicked, a browser will only send the not-disabled fields.
The $_POST array will only contain the values from all not-disabled fields.
When a user enters this:
you would get $_POST['foo-right-1'] = 'car' and $_POST['foo-left-2'] = 'dog'.

dynamically generate text areas w/ unique id's based on checkbox inputs

I am working on a program for my company to process different product types and create files.
I have a form that will eventually grow to close to 150 checkbox options over the course of a few months. I'm trying to get input on the best way to do this and save me time in the long run.
So for example I have this:
<input type="checkbox" value="NOT" name="size">NOT<br />
<input type="checkbox" value="THA" name="size">THA<br />
<input type="checkbox" value="TAB22" name="size">TAB22<br />
What I need is that for every checkbox that is clicked, i need to reveal a text area w/ a simple title that is equal to the checkbox value above it within a div called <div id="inputArea"> From here the user will then paste in file names in the corresponding text areas. Basically each text area is tied to a checkbox option.
I use PHP to process the form, so when it is submitted, at that point I will need to store the value of each text area that has values into separate variables. Is there a way to do that dynamically as well?
I'm open to jquery, javascript, php or anything.
I'm just curious as the best to do this. Otherwise my knowledge is only good enough to manually create 150 checkboxes, then create 150 text areas, then create 150 jQuery hide/reveal methods, then create 150 php checks to determine what text areas have values and assign them to variables.
You may try this
HTML
<form action="some_action.php" method="post">
<input type="checkbox" value="NOT" name="size">NOT<br />
<input type="checkbox" value="THA" name="size">THA<br />
<input type="checkbox" value="TAB22" name="size">TAB22<br />
....
</form>
JS
$('input:checkbox[name="size"]').on('click', function(){
if($(this).is(':checked'))
{
$('<div class="inputArea"></div>') // inputArea is a class not an ID because ID should be anique
.append($('<textarea />', {id:'txtArea_'+$(this).val(), name:'txtArea_'+$(this).val()}))
.insertAfter($(this).next('br'));
}
else
{
$(this).next('br').next('div.inputArea').remove();
}
});
DEMO.
Every textarea has name and id with prefix txtArea_ with value of it's corresponding checkbox so if a checkbox is submitted and it's value is NOT then you can retrive the value of that corresponding textarea in php as
$txtArea_NOT=$_POST['txtArea_NOT']; // When form's method is post
If you're using jQuery, you should be able to use/modify the following as a base.
$('input[type=checkbox]').click(function() {
var value = $(this).val();
$(this).append(value +'<br /><textarea name="'+ value +'"></textarea>');
});
You can try to use the Wrap and unwrap methods to get your things done.
Remember ID's should be unique in a page. So instead of id I have assigned it a class for the textarea div..
$('input[type=checkbox]').on('click', function() {
var isChecked = $(this).is(':checked');
if (isChecked) {
$(this).wrap('<div class="inputArea"></div>');
$(this).closest('div').prepend('<textarea class="text-area" cols="10" rows="2"></textarea>');
}
else{
$(this).closest('div').find('.text-area').remove();
$(this).unwrap();
}
});​
DEMO HERE
So basically your are wrapping your checkbox inside a div and assigning it.. When you uncheck it , the wrapper is removed... This is independent of other checkboxe's. So it should work for any number of checkboxes.
HTML
You should have unique ids for the checkboxes, just as good practice. This also will show/hide textareas, to preserve any text that has already been entered -- this could be a good or a bad thing, depending on your requirements.
<form name="frmSize" method="POST" action="somePage.php">
<div><input id="cbNot" class="cbFileList" type="checkbox" value="NOT" name="not">NOT</div>
<div><input id="cbTha" class="cbFileList" type="checkbox" value="THA" name="tha">THA</div>
<div><input id="cbTab22" class="cbFileList" type="checkbox" value="TAB22" name="tab22">TAB22</div>
</form>
JavaScript
var cbList = document.getElementsByClassName( 'cbFileList' );
var i;
for ( i = 0; i < cbList.length; i++ ) {
createTextArea( cbList[i] );
cbList[i].addEventListener( 'click', function() {
var cb = this;
if ( cb.checked ) {
showTextArea( cb );
} else {
hideTextArea( cb );
}
});
}
function showTextArea( cb ) {
document.getElementById( 'div-' + cb.id).style.display = '';
}
function hideTextArea( cb ) {
document.getElementById( 'div-' + cb.id).style.display = 'none';
}
function createTextArea( cb ) {
var newDiv = document.createElement( 'div' );
var newTextArea = document.createElement( 'textarea' );
newDiv.setAttribute( 'id', 'div-' + cb.id );
newDiv.innerHTML = '<b>' + cb.value + '</b><br/>'; // Create bold text using checkbox's value
newTextArea.setAttribute( 'id', 'ta-' + cb.id );
newTextArea.setAttribute( 'name', 'ta-' + cb.id );
newTextArea.innerHTML = cb.value;
newDiv.appendChild( newTextArea );
cb.parentNode.appendChild( newDiv );
}
The Output
<div>
<input id="cbNot" class="cbFileList" type="checkbox" value="NOT" name="not">NOT
<div id="div-cbNot">
<b>NOT</b><br/>
<textarea id="ta-cbNot"></textarea>
</div>
</div>
<div>
<input id="cbTha" class="cbFileList" type="checkbox" value="THA" name="tha">THA
<div id="div-cbTha">
<b>THA</b><br/>
<textarea id="ta-cbTha" name="ta-cbTha"></textarea>
</div>
</div>
...
PHP
<?
// run a for loop through $_POST[] and check for any field prefixed with 'ta-'
foreach( $_POST as $key => $value ) {
if ( strpos( $key, 'ta-' ) !== false && strlen( $value ) > 0 ) {
// Found a textarea with content!
// Do something with $_POST[$key], which contains the contents of textarea
}
}
?>

Deleting value="Comment?" as soon as it is clicked from the input box

I created an input box and says "comments?" before the user enters anything in it.Code;
<input type="text" name="saysome" value = "comments?"/>
But, i want to delete this "comments?" as soon as it is clicked.I am trying to do input box just like the search box in here, actually exaclty same. How can i do that?Can it be done by only javascipt? :(
Thanks
You can use the html5 placeholder attribute found here:
HTML5 Specs
For example:
<input type="text" name="saysome" placeholder = "comments?"/>
You could also take a javascript approach for browsers that do not support HTML5.
Simple method that will clear it anytime the box has focus, and not if the user has entered anything into it
<input type="text" name="TB" value="Please Enter.." onfocus="this.value==this.defaultValue?this.value='':null"/>
As other commenters mentioned, you should check out placeholder. To answer your question though, this method will remove the text on mouse click if the user has not already entered something. This assumes that the id of the input is textbox. You will have to change it to whatever you have or else assign the input an id.
<input id="textbox" type="text"/>
and the JS:
document.getElementById('textbox').onclick = function()
{
var box = document.getElementById('textbox');
if(box.value==box.defaulValue)box.value =='';
}
<input type="text" name="saysome" onblur="if(this.value=='') this.value='comments?';" onclick="this.value=''" value="comments?" />
See this example # http://x.co/Z2pa
Non-jquery:
onClick="clearComments()"
function clearComments() {
commentInput = document.getElementById("commentsId");
if(commentInput.value == 'comments?') {
commentInput.value = '';
}
}
Without jQuery:
Give the input an ID, and clear its value using an onclick event.
<input type="text" name="test" id="test" value="test" onclick="if(document.getElementById('test').value=='test')document.getElementById('test').value='';">
Also supports older browsers that don't use HTML 5.

Allow user to create and submit up to 5 text boxes with jquery, and parse them into one array in php?

Is it possible?
I want a user to post an array full of 1-5 pieces of data.
At first there would be only one text field on show, but on clicking a 'plus' icon next to it, it would create another text field below it for more user input.
I would also want to have a delete icon next to text boxes 2-5, to remove them if necessary.
My JQuery knowledge is limited, and I can work out how to append text boxes to a list, but not to keep track of them/delete them. Ideally I would also want to pass them as an array to php, so I can easily loop through them.
<input type="text" size="15" maxlength="15" name="1"><img src="add.png" onclick="add();">
<!-- Below is hidden by default, and each one shows on click of the add image -->
<input type="text" size="15" maxlength="15" name="2"><img src="delete.png" onclick="delete(2);">
<input type="text" size="15" maxlength="15" name="3"><img src="delete.png" onclick="delete(3);">
<input type="text" size="15" maxlength="15" name="4"><img src="delete.png" onclick="delete(4);">
<input type="text" size="15" maxlength="15" name="5"><img src="delete.png" onclick="delete(5);">
jQuery clone() is very handy for this. A small example how it could be done (working example on jsfiddle)
<ul>
<li><input type="text" name="textbox[]" /></li>
</ul>
<input type="button" id="addTextbox" value="Add textbox" />
<script type="text/javascript">
$(function(){
$('#addTextbox').click(function(){
var li = $('ul li:first').clone().appendTo($('ul'));
// empty the value if something is already filled in the cloned copy
li.children('input').val('');
li.append($('<button />').click(function(){
li.remove();
// don't need to check how many there are, since it will be less than 5.
$('#addTextbox').attr('disabled',false);
}).text('Remove'));
// disable button if its the 5th that was added
if ($('ul').children().length==5){
$(this).attr('disabled',true);
}
});
});
</script>
For the server-side part, you could then do a foreach() loop through the $_POST['textbox']
As long as you give each text box a name like "my_input[]", then when the form is submitted, PHP can get the answer(s) as an array.
$_REQUEST['my_input']; would be an array of the values stored in each text box.
Source: Add and Remove items with jQuery
Add
Remove
<p><input type="text" value="1" /></p>
<script type="text/javascript">
$(function() { // when document has loaded
var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});
$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});
$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});
});
</script>
You will need to create DOM elements dynamically. See how it is done for example in this question. Notice that
document.createElement
is faster then using jquery's syntax like
$('<div></div>')
Using that technick, you could create inputs like
<input name="id1"/>
<input name="id2"/>
<input name="id3"/>
<input name="id4"/>
<input name="id5"/>
On submitting your form you'll get all them in your query string like
...id1=someval1&id2=someval2&...
Having that, you could process this query as you want on server side.
<form method="POST" id="myform">
<input />
Add textbox
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#add_textbox').click(function(){
var form=$(this).closest('form');
var count=form.find('input').length();
form.append('<div class="removable_textbox"><input />delete</div>');
$('.delete_input').click(function(){
$(this).find('.removable_textbox').remove();
return false;
});
return false;
});
$('#myform').submit(function(){
var i=1;
$(this).find('input').each(function(){
$(this).attr('name','input-'+i);
i++;
})
});
});
</script>
<?php
if(isset($_POST['input-1'])){
$input_array=$_POST;
}
?>
something like this?
I wrote a litte jQuery plugin called textbox. You can find it here: http://jsfiddle.net/mkuklis/pQyYy/2/
You can initialize it on the form element like this:
$('#form').textbox({
maxNum: 5,
values: ["test1"],
name: "textbox",
onSubmit: function(data) {
// do something with form data
}
});
the settings are optional and they indicate:
maxNum - the max number of elements rendered on the screen
values - an array of initial values (you can use this to pass initial values which for example could come from server)
name - the name of the input text field
onSubmit - onSubmit callback executed when save button is clicked. The passed data parameter holds serialized form data.
The plugin is not perfect but it could be a good start.

Categories