Send multiple fields on form - javascript

I am developing a system for equipment rental in PHP.
I need to send a form that contains the id, quantity, time and value fields of the selected equipment.
Each rent can have N equipments, consequently N amount of fields.
How do I do this? Do I generate the fields by javascript? To send, an array for each piece of equipment?
It would be something like that:
<input type='text' name='equipment[]'>
<input type='text' name='quantity[]'>
<input type='text' name='time[]'>
But how would I do it like this:
array(array[0](equipment=>1,quantity=>2,time=>4),array[1](equipment=>2,quantity=>2,time=>4),array[2](equipment=>1,quantity=>2,time=>4));

I think you could group by rental doing like this:
<div id="rental_group_1">
<input type="text" name="rent_1[]" id="equipment_1">
<input type="text" name="rent_1[]" id="quantity_1">
<input type="text" name="rent_1[]" id="time_1">
</div>
<div id="rental_group_2">
<input type="text" name="rent_2[]" id="equipment_2">
<input type="text" name="rent_2[]" id="quantity_2">
<input type="text" name="rent_2[]" id="time_2">
</div>...
This way you will get on Post an array per group so:
$rent_1[0] = equipment_1
$rent_1[0] = quantity_1
$rent_1[0] = time_1
...
Adding this to #Blesson Christy solution will create a good UI/UX for what you want.
Hope it helps! :D

A small example :
HTML:
<div id="content">
<input type="text" class="fieldone" id="fields_1" name="fields[]"/>
</div><input type="button" id="addmore" />
Jquery:
counter=1;
$(document).on('click','#addmore',function(){
counter++;
var htmltoadd='<input type="text" class="fieldone" id="fields_"'+counter+' name="fields[]"/>';
$("#content").append(htmltoadd);
});
You need to include jquery in this example.

Related

How to get text-box counts in javascript

H i have a button "Add text" when on-click it creates the text-boxes,now How can i get the count of text-boxes in JavaScript i create text-boxes like
<input type="text" name="my_textbox[1]" id="my_textbox1" />
<input type="text" name="my_textbox[2]" id="my_textbox2" />
<input type="text" name="my_textbox[3]" id="my_textbox3" />
<input type="text" name="my_textbox[4]" id="my_textbox4" />
the reason why i need to count is ,i am fetching values from ajax and creating new text-box appending new text-box like :
<input type="text" name="my_textbox[5]" id="my_textbox5" value="seomthing"/>
Now I would like to know the number of text-boxes present. It would be best if I can get the count through JavaScript .
Thanks in advance.
Give your inputs a classname so you can identify them as a group:
<input class="myInputs" type="text" name="my_textbox[1]" id="my_textbox1" />
Then in your javascript select them with querySelectorAll() and look at the length of the returned collection:
var inputs = document.querySelectorAll('.myInputs')
var number_of_inputs = inputs.length
Use document.querySelectorAll() to get all the elements matching substring of id (https://www.w3.org/TR/selectors/#attribute-substrings). This '[id^="my_textbox"]' syntax means you are selecting all elements with id starting with "my_textbox" string. The just take the length of queried collection and you are done. Please see snippet below:
var textboxCount = document.querySelectorAll('[id^="my_textbox"]').length;
console.log(textboxCount);
<input type="text" name="my_textbox[1]" id="my_textbox1" />
<input type="text" name="my_textbox[2]" id="my_textbox2" />
<input type="text" name="my_textbox[3]" id="my_textbox3" />
<input type="text" name="my_textbox[4]" id="my_textbox4" />

Jquery Validation on dynamically populated fields

Im having issues getting Jquery Validation to work properly on dynamically populated fields. First off im using asp.net so I need my name fields to stay the same because on the server side im pulling that array of information splitting it and updating a database.
<form id="insert_additions" action="http://yahoo.com" method="post">
<label>
Name1<input type="text" name="testing" value="" required/>
</label>
<label>
Name2<input type="text" name="box_setup" required value="" />
</label>
<label>
Comments:&nbsp<input type="text" name="comments" value="" /></label><br />
<div id="work"></div>
<br />
<hr align="left" width="50%"/>
<span style="margin: 0 0 0 300px;">
<input class="submit" type="submit" value="Submit">
<input type="button" id="addbutton" class="flatBtn" value="Add Another Project Line" /></span>
</form>
This here is the code that is adding the fields
var work_count = 2;
$("#addbutton").click(function () { //sets up the validator
//Html to create a new field
var newField = "<hr align='left' width='50%'>\
<label>Name1\
<input type='text' name='testing"+work_count+"' required size='8' value='' \
</label>\
<label>Name2\
<input type='text' name='box_setup' required value='' />\
</label>\
<label>Comments:\
<input type='text' name='comments' value='' />\
</label>\
";
$("#work").before(newField);
$('input[id="testing'+work_count+'"]').rules("add", { // <- apply rule to new field
required: true
});
work_count++;
});
As you can see I have tried adding the validate.rules() with in the javascript so that when it add's the new input's into the page it could also insert new rules. I have tried making the id variable but im not sure what im doing wrong. Validation is only working on the first set of fields. I have read and tried implementing various solutions that I have read on this website but im just lost I have started beating my head against my keyboard. Any help would be great I appreciate and love this web forum.
How about just setting the attribute through jquery?
$('input[name="testing'+work_count+'"]').attr('required', true);
btw, there is no id attribute on your added inputs.
so:
$('input[id="testing'+work_count+'"]').rules("add"
should be
$('input[name="testing'+work_count+'"]').rules("ad

Update Div Hidden Field on jQuery Sortable Drag and Drop Update

I am using an HTML5 jQuery Sortable library. Not jQuery UI Sortable but this one here http://farhadi.ir/projects/html5sortable/
I have used it on many projects in the past and generally I use AJAX to save the sort order as a string of ID's into a database field.
On my current project, I need to do things completely different though. I am not using AJAX to save the order this time.
Basically I have the Sortable library running on a Form edit screen which will have a list of DIV's, inside these div's will be form fields. At the bottom of the page is a save button that submits the form to save all the data on the page. So I would like to instead store the sort order of each DIV into a hidden form field for each item.
I have set up a demo to work with on CodePen.io here http://codepen.io/jasondavis/pen/ztirw?editors=101
I could use some help to update a Form filed under each Div to update the fields with the Sort order each time a Drop occurs. So instead of saving a string of ID's in the correct sorted order, I would instead like to update every record on a Drop event into a Form filed with the current sort position.
Any help please?
The demo HTML structure looks like this...
<div id="project_tasks" class="tasks_block sortable">
<div id="task_13" class="task_row">
<span class="handle"></span>
<input name="taskid_13" id="taskid_13" size="15" type="text" value="taskID 1">
<input name="projectid_13" id="projectid_13" size="15" type="text" value="917fdb60-96d7-346f-10b3-54175c9a2f34">
Sort Order: <input name="sort_order_19" id="sort_order_19" size="15" type="text" value="1">
<br style="clear:both;">
</div>
<div id="task_14" class="task_row">
<span class="handle"></span>
<input name="taskid_14" id="taskid_14" size="15" type="text" value="taskID 2">
<input name="projectid_14" id="projectid_14" size="15" type="text" value="917fdb60-96d7-346f-10b3-54175c9a2f34">
Sort Order: <input name="sort_order_19" id="sort_order_19" size="15" type="text" value="2">
<br style="clear:both;">
</div>
<div id="task_15" class="task_row">
<span class="handle"></span>
<input name="taskid_15" id="taskid_15" size="15" type="text" value="taskID 3">
<input name="projectid_15" id="projectid_15" size="15" type="text" value="917fdb60-96d7-346f-10b3-54175c9a2f34">
Sort Order: <input name="sort_order_19" id="sort_order_19" size="15" type="text" value="3">
<br style="clear:both;">
</div>
<div id="task_15" class="task_row taskheading">
<span class="handle"></span>
<h2>List Heading 1</h2>
Sort Order: <input name="sort_order_19" id="sort_order_19" size="15" type="text" value="4">
<br style="clear:both;">
</div>
<div id="task_16" class="task_row">
<span class="handle"></span>
<input name="taskid_16" id="taskid_16" size="15" type="text" value="taskID 4">
<input name="projectid_16" id="projectid_16" size="15" type="text" value="917fdb60-96d7-346f-10b3-54175c9a2f34">
Sort Order: <input name="sort_order_19" id="sort_order_19" size="15" type="text" value="5">
<br style="clear:both;">
</div>
</div>
A little JavaScript to start things off...
$( document ).ready(function() {
$('#project_tasks').sortable({
handle: '.handle',
onStartDrag: function() {},
onEndDrag: function() {},
onChangeOrder: function() {}
}).bind('sortupdate', function() {
$('.sortable div').each(function() {
// Update a HIDDEN Field under each DIV with the current sort order
// So when my Form is submitted/saved, it can save the sort order for
// each record into the database.
});
});
});
Ok - here you go:
http://codepen.io/anon/pen/IEKvA
$('.sortable div').each(function(idx) {
var inputField = $(this).find("[id^='sort_order']");
$(inputField).val(idx);
});
The idea is to everytime and item is dropped you run thru your divs, find all the input fields that start with the id sort_order and set the index accordingly.

What is the most efficient way of submitting a form whose inputs are not direct children of the form element itself using native JavaScript?

I am currently creating a form for my employer which tracks individual employee statistics throughout a typical day, such as number of calls, revenue, items sold, etc. I would like to asynchronously update a database using a simple html form without necessarily having to use the entire jQuery library since all I would be using is the $.ajax method, which I do know is effective.
The trouble I'm running into is in finding a way to serialize a form using the form's <input type="submit"> button. My form's input fields are spatially organized using <div></div> tags between the <form> element itself and its <input /> fields themselves, as seen below:
<form name="tour_1" id="tour_1">
<div class="num_calls_cell">
<input type="text" value="3" name="total_calls" autocomplete="off" />
</div>
<div class="acw_cell">
<input type="text" value="24.35" name="acw" autocomplete="off" />
</div>
<div class="rev_cell">
<input type="text" value="125.34" name="revenue" autocomplete="off" />
</div>
<div class="env_cell">
<input type="text" value="0" name="envelopes" autocomplete="off" />
</div>
<div class="pen_cell">
<input type="text" value="1" name="pens" autocomplete="off" />
</div>
<div class="cal_cell">
<input type="text" value="0" name="other" autocomplete="off" />
</div>
<div class="comment_cell">
<input type="text" value="comment" name="comments" autocomplete="off" />
</div>
<div class="submit_cell">
<input type="submit" class="submit_tour" value="Submit Tour" />
</div>
</form>
There are a total of four of these forms that I have in one "day" (you may view the actual project here (http://ryanvold.com/prototype/prototype.php).
How could I most effectively transfer my form data into a PHP file that can easily update a MySQL database using my <input type="submit"> buttons?
You can serialize form like this:
document.getElementById('tour_1').addEventListener('submit', function(e) {
e.preventDefault();
var params = [];
for (var i = 0; i < this.elements.length; i++) {
params.push(this.elements[i].name + '=' + encodeURIComponent(this.elements[i].value));
}
params = params.join('&');
alert(params);
}, false);
This will give you params as follows:
total_calls=3&acw=24.35&revenue=125.34&envelopes=0&pens=1&other=0&comments=comment&=Submit%20Tour
Having constructed params string like this you can use it as ajax request POST parameters:
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
This is just an example, remember to take care of IE if you need to support it (attachEvent).
Demo: http://jsfiddle.net/LnLaT/

Serialize multiple select boxes for Ajax POST

I'll use a toy example to illustrate my problem:
I have a form which gets some details about a user:
<form action="#" method="post" id="myform">
<input type="text" name="fname" />
<input type="text" name="sname" />
<input type="text" name="birthdate" />
<select name="hobbies">
<option>Programming</option>
<option>Eating cats</option>
<option>Explaining string theory to my grandmother</option>
</select>
</form>
and I'm going to send it to my server with an ajax call so I can give some kind of response without a page refresh:
$.post("myserverscript.php", $('#myform').serialize(), function(){...callback...});
This works fine.
Now, I need to take the same information about multiple users on the same page. No problem, I just add [] to my input names:
<form action="#" method="post" id="myform">
<input type="text" name="fname[]" />
<input type="text" name="sname[]" />
<input type="text" name="birthdate[]" />
<select name="hobbies[]">
<option>Programming</option>
<option>Eating cats</option>
<option>Explaining string theory to my grandmother</option>
</select>
</form>
And again, all is well with the world.
Now, I want to allow the user to pick more than one hobby each:
<form action="#" method="post" id="myform">
<input type="text" name="fname[]" />
<input type="text" name="sname[]" />
<input type="text" name="birthdate[]" />
<select name="hobbies[]" multiple>
<option>Programming</option>
<option>Eating cats</option>
<option>Explaining string theory to my grandmother</option>
</select>
</form>
and this is where things start going a little pear-shaped. When I call serialize() now, all the hobbies are put into one array - so I'm unable to say which user has which hobbies.
I've tried using [][] instead of [] but that just puts each individual item into it's own array within the hobbies array so I still lose the user->hobby link.
The only way that I can see of doing this is writing my own serialize() which groups things as I need them.
Is there a better, simpler or more elegant way of doing this?
My standard approach is to append the UserID to the input name, with an underscore between them.
So, instead of this:
<input type="text" name="fname[]" />
it would be:
<input type="text" name="fname_23423" />
Then, server-side, you split the input names on _. The first element is the input name, the second is the UserID, and you're all set.
I've had a similar problem but the way I did it was to assign each user a specific array
for example this fiddle
<form action="#" method="post" id="myform">
<input type="text" name="user1[fname]" />
<input type="text" name="user1[sname]" />
<input type="text" name="user1[birthdate]" />
<select name="user1[hobbies]" multiple>
<option>Programming</option>
<option>Eating cats</option>
<option>Explaining string theory to my grandmother</option>
</select>
Submit
</form>

Categories