How to re-index select box along with hidden fields - javascript

I'm struggling to figure out how to re-index (?) a series of hidden fields with jQuery/Javascript. The sample code below is generated each time a user clicks a create button. The numerical value applied to the hidden fields within tier[] is the index of an option selected from a drop-down.
The problem I have is every block of code (except the first i.e. tier1) should have the option to be removed. When the remove link is clicked I have implemented some jQuery which removes the div with the selected ID. The main issue is that I need to alter the name of each block on removal and re-index the drop-down so the numbers are incremental. The hidden fields will need to follow the index of the drop-down too.
I'm struggling to determine how to achieve this with Javascript or jQuery.
I've tried to include an example before any removal occurs. There are 4 blocks, each is incrementally created based on the option from the drop-down. A user could attempt to remove block 3. Currently, this will remove the option from the select using the above jQuery but as a result the display will list inconsistent block numbers, the hidden fields will have the incorrect indexes and the drop-down will be 'out of synch'.
<script type="text/javascript">
$(document).ready(function() {
$("a.removeTier").live('click', function() {
var tierId = $(this).parent().parent().attr('id').match(/\d+$/);
$('#tiers option:eq('+tierId+')').remove();
$('#tier'+tierId).remove();
return false;
});
});
</script>
<p align="left">
<label style="width: 45px;" for="newTier"><b>Tier:</b> *</label>
<button style="width: 70px; font-size: 11px;" value="New Tier" id="newTier" name="newTier">New Tier</button>
<select name="tiers" id="tiers">
<option value="0">Select</option>
<option selected="" value="1">Tier 1</option>
<option value="2">Tier 2</option>
<option value="3">Tier 3</option>
<option value="4">Tier 4</option>
</select>
</p>
<div id="tierRight">
//1
<div id="tier1">
<div style="text-align: left;">
Tier 1<br><label for="publication_date_1">Publication Date: </label>
<input type="text" value="" readonly="readonly" name="tier[1][publication_date]" id="publication_date_1" size="10" maxlength="10" class="publication_date hasDatepicker"> <input type="hidden" value="2010-09-01" name="tier[1][publication_date_db]" id="publication_date_db_1">
</div>
<span>
<a class="removePanel" id="panel132" title="Remove `Autism Initiatives` from `Tier 1`" href="#">Autism Initiatives</a>
<input type="hidden" value="132" name="tier[1][panels][132][panelId]">
<input type="hidden" value="Autism Initiatives" name="tier[1][panels][132][panelName]">
</span>
</div><br>
//2
<div id="tier2">
<div style="text-align: left;">
Tier 2 - [<a id="tier2" class="removeTier" title="Remove Tier" href="#">Remove</a>]<br><label for="tier[2][publication_date]">Publication Date: </label>
<input type="text" value="" readonly="readonly" name="tier[2][publication_date]" id="publication_date_2" size="10" maxlength="10" class="publication_date hasDatepicker">
<input type="hidden" name="tier[2][publication_date_db]" id="publication_date_db_2" value="2010-09-08">
</div>
<span>
<a class="removePanel" id="panel149" title="Remove `Autism 2` from `Tier 2`" href="#">Autism 2</a>
<input type="hidden" value="149" name="tier[2][panels][149][panelId]">
<input type="hidden" value="Autism 2" name="tier[2][panels][149][panelName]">
</span>
</div><br>
//3
<div id="tier3">
<div style="text-align: left;">
Tier 3 - [<a id="tier3" class="removeTier" title="Remove Tier" href="#">Remove</a>]<br><label for="tier[3][publication_date]">Publication Date: </label>
<input type="text" value="" readonly="readonly" name="tier[3][publication_date]" id="publication_date_3" size="10" maxlength="10" class="publication_date hasDatepicker">
<input type="hidden" name="tier[3][publication_date_db]" id="publication_date_db_3" value="2010-09-15">
</div>
<span>
<a class="removePanel" id="panel150" title="Remove `Autism 3` from `Tier 3`" href="#">Autism 3</a>
<input type="hidden" value="150" name="tier[3][panels][150][panelId]">
<input type="hidden" value="Autism 3" name="tier[3][panels][150][panelName]">
</span>
</div><br>
//4
<div id="tier4">
<div style="text-align: left;">
Tier 4 - [<a id="tier4" class="removeTier" title="Remove Tier" href="#">Remove</a>]<br><label for="tier[4][publication_date]">Publication Date: </label>
<input type="text" value="" readonly="readonly" name="tier[4][publication_date]" id="publication_date_4" size="10" maxlength="10" class="publication_date hasDatepicker">
<input type="hidden" name="tier[4][publication_date_db]" id="publication_date_db_4" value="2010-09-22">
</div>
<span>
<a class="removePanel" id="panel151" title="Remove `Autism 4` from `Tier 4`" href="#">Autism 4</a>
<input type="hidden" value="151" name="tier[4][panels][151][panelId]">
<input type="hidden" value="Autism 4" name="tier[4][panels][151][panelName]">
</span>
</div><br>
</div>

First you'll need to clean up your HTML - you're using id="tier1" on both a div and a a which will eventually cause problems.
Here's a simple variant that shows a possible approach:
<div class="tier">
<p class="title">Tier 1</p>
</div>
<div class="tier">
<p class="title">Tier 2</p>
<p class="delete">Delete Me</p>
</div>
<div class="tier">
<p class="title">Tier 3</p>
<p class="delete">Delete Me</p>
</div>
Javascript:
$(function() {
$(".delete").bind("click", function() {
$(this).parent().remove();
$(".tier").each( function(index) {
var tierIndex = index+1;
$(this).find(".title").text("Tier " + tierIndex);
});
});
});
Or as a jsFiddle here.

Related

How to show and hide multiple drop downs and buttons using single button

<div class="content">
<div class="row" style="margin-top: 27px;">
<div class="col-sm-2" style="width: 13%;">
<select id = "app" class="form_input_box">
<option value="" selected="selected">App</option>
</select>
</div>
<div class="col-sm-2" style="margin-left: -25px;width: 11%;">
<select id = "app or not" class="form_input_box">
<option value="" selected="selected" hidden>App Type</option>
<option value="" selected>App Type</option>
<option value="1">App</option>
<option value="2">Not a App</option>
</select>
</div>
<div class="col-sm-2" style="margin-left: -25px;">
<select id = "dept" class="form_input_box">
<option value="" selected="selected">Department</option>
</select>
</div>
<div class="col-sm-1" style="margin-left: -25px;width: 12%;">
<input type="text" name="date_box" id="date_box" class="form_input_box filter_date" Placeholder="Created Date">
</div>
<div class="col-sm-2" style="margin-left: -25px;width: 11%;">
<input type="text" name="search" id="search" class="form_input_box" Placeholder="Search">
</div>
<div class="col-sm-1" style="margin-left: -25px;">
<button id="erase" class="form-control btn btn-primary" name="erase">Clear values</button>
</div>
<div class="row">
<div class="col-sm-1">
<input type="month" id="month" name="month" class="form_input_box" placeholder="Month">
</div>
<div class="col-sm-2" style="right: 30px">
<button type="button" name="report" id="file" class="button">Report file</button>
</div>
</div>
</div>
</div>
i have html page with buttons drop downs like above i need to set a single button when i click on the button it will show all these things if i again click then these need to be hided how can i achieve this.
To solve the problem simply you could use javascript or jquery and hide or show the options based on the selected values...
$('idoption').hide();
$('idoption').show();

Set background-color to div from form in another blade

My project contains index.blade.php and create.blade.php.
In create.blade.php is a form for creating divs that are listed in the index.blade.php, through the form I need to pass the background-color for each div made, options red, yellow and green color.
My create.blade.php code:
<form action="{{url('warehouse')}}" method="post">
#csrf
<label for="name" style="padding-right:20px">Name</label>
<input type="text" id="name" name="name" style="padding-right:50px; margin-bottom:10px" placeholder="Name"><br>
<label for="supplier" style="padding-right:2px">Supplier</label>
<input type="text" id="supplier" name="supplier" style="padding-right:50px; margin-bottom:10px"
placeholder="Supplier"><br>
<label for="type" style="padding-right:28.5px">Type</label>
<input type="text" id="type" name="type" style="padding-right:50px; margin-bottom:10px" placeholder="Type"><br>
<label for="url" style="padding-right:41.8px">Url</label>
<input type="text" id="url" name="url" style="padding-right:50px; margin-bottom:10px" placeholder="Url"><br>
<label for="color">Color</label>
<select id="selector" name="color">
<option value="" disabled selected hidden>Please Choose...</option>
<option value="green">Green (ready for sale)</option>
<option value="yellow">Yellow (in progress)</option>
<option value="red">Red (new)</option>
</select>
<br>
<button type="submit" id="kreiraj_dugme_create" onclick="selectBackground()">Create/button>
And my index.blade.php code:
#foreach ($warehouses as $key => $warehouse)
<div class="brder1" draggable="true" ondragstart="drag(event,{{$key}})" id="{{$key}}">
<h1 class="ime_palete">{{$warehouse->name}}</h1>
<a class="link_palete" href="{{$warehouse->url}}" target="_blank">Link</a>
<a class="edit_palete" href="{{url("warehouse/".$warehouse->id."/edit")}}">Edit</a>
<a class="show_pallet" href="{{url("warehouse/".$warehouse->id)}}">Show</a>
<form action="{{url("warehouse/".$warehouse->id)}}" method="post">
#csrf
#method('DELETE')
<button type="submit" class="izbrisiDugme" onclick="remove()">Remove</button>
</form>
</div>
#endforeach
</div>
<a class="create_palete" href="{{url("warehouse/create")}}">Create</a>
All I need is to set background-color from options to div brder1
You probably need to do something like this
with jQuery:
$("#selector").change(function(){
$(".brder1").css('background-color', $(this).val());
});
You can place the code within document ready. So snippet will look like as follows
$(document).ready(function(){
$("#selector").change(function(){
$(".brder1").css('background-color', $(this).val());
});
});

How to prevent form submission until form is filled using JavaScript?

It should not be possible to submit the form if the user does not enter a value into the text entry fields, e.g. for surname or company, and at least one event has not been selected
(remember that users don’t always fill out forms in top to bottom order). Here is the sample code from php file which I can't edit. Only java script must be used.
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Thomas Bewick and His Apprentices</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span>
</div>
<div class="item">
<span class="eventTitle">Winter Festival # Discovery Museum</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span>
</div>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="makeBooking">
<h2>Make booking</h2>
Your details
Customer Type: <select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName">
</div>
<p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions
<input type="checkbox" name="termsChkbx"></p>
<p><input type="submit" name="submit" value="Book now!" disabled=""></p>
</section>
</form>
Using HTMLFormElement.elements to dynamically set required attribute:
Just use the HTMLFormElement.elements property to get all the form controls (input, select, etc) inside your form and then use the Array.from() method to get a shallow-copied array of the HTMLFormControlsCollection which you can now loop over and use the setAttribute() method to dynamically set a required attribute to all the form controls.
Check and run the following Code Snippet or open this JSFiddle link for a practical example of the above approach:
// get the form
const form = document.getElementById("bookingForm");
// get the form controls
let x = form.elements;
// Convert the list of form controls to an array and set the required attribute to each control
Array.from(x).forEach(e => {
e.setAttribute("required", "");
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Thomas Bewick and His Apprentices</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span>
</div>
<div class="item">
<span class="eventTitle">Winter Festival # Discovery Museum</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span>
</div>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="makeBooking">
<h2>Make booking</h2>
Your details
Customer Type: <select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName">
</div>
<p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions
<input type="checkbox" name="termsChkbx"></p>
<p><input type="submit" name="submit" value="Book now!"></p>
</section>
</form>
Using required:
Just add a required attribute to each input element like this:
<input type="text" name="forename" required>
<input type="text" name="forename" required>
<select name="customerType" required>
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
1_you can add required attribute to inputs by JS. :)
2_I'm not a pro and the only way I can think of , is using AJAX and JQuery .like this:
<script>
function echo() {
var name = $("#id");
if (name.val() === "") {
alert(name.attr('placeholder') + " is empty");
return;
}
$.ajax({
url: "your destination",
data: {
name: name.val(),
},
dataType: "json",
type: "POST",
success: function (data) {
if (data['error'] === false) {
alert(data['msg']);
} else {
alert(data['msg']);
}
}
});
}
</script
you need JQ just for the AJAX part of course, but the rest of the function can get done
just by JS.
I would suggest that you try and get access to your html and change it's structure e.g. the "Select Events" section could use a <select> dropdown instead of the current two checkboxes so you can make use of the cleaner and more concise required attribute approach shown in the other answer that I posted.
However, if you HAVE to use only JavaScript to validate the form, then you can just retrieve the form elements, validate each element and submit the form if they all pass.
To do that, you can just replace the current <input type="submit"> element with a <button> instead and then add a click listener to that button which in turn will run a function that will prevent the form from submitting using preventDefault() method, check and validate each form element and submit the form if all the elements pass the validation.
Check and run the following Code Snippet or open this JSFiddle for a practical example of the above approach:
const form = document.getElementById("bookingForm");
const events = document.querySelectorAll('input[name="event[]"]');
const terms = document.querySelector('input[name="termsChkbx"]');
const selectBox = document.querySelector('select[name="customerType"]');
const fName = document.querySelector('input[name="forename"]');
const sName = document.querySelector('input[name="surname"]');
const btn = document.getElementById("submitBtn");
function verifyEvents(e){
e.preventDefault();
if(selectBox.value != "" && terms.checked && fName.value != "" && sName != "" && (events[0].checked || events[1].checked)){
console.log(selectBox.value);
form.submit();
} else {
alert("Please fill the form.");
}
}
btn.addEventListener("click", verifyEvents);
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Thomas Bewick and His Apprentices</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span>
</div>
<div class="item">
<span class="eventTitle">Winter Festival # Discovery Museum</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span>
</div>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="makeBooking">
<h2>Make booking</h2>
Your details
Customer Type: <select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName">
</div>
<p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions
<input type="checkbox" name="termsChkbx"></p>
<p><button id="submitBtn" name="submitBtn" value="Book now!">Book now!</button></p>
</section>
</form>

remove fields which are added by jquery

In my code, there are three fields which are dynamically added by jQuery. For adding fields, my code is working fine, but when I want to remove those dynamically added fields, my remove fields code is not working.
Here is my code:
function clone_row() {
$('#add_more_fields').before('<div class="new_field"><div class="uk-grid" data-uk-grid-margin><div class="uk-width-medium-1-1"><div class="parsley-row"><label for="site Type">Product <span class="req">*</span></label><input type="text" name="product_require[]" data-parsley-trigger="change" required class="md-input" /></div></div>
<div class="uk-width-medium-1-1"><div class="parsley-row"><labelfor="site_area">Quantity<span class="req">*</span></label><input type="text" name="quantity[]" data-parsley-trigger="change" required class="md-input" /><input type="hidden" name="numb_array[]" value="0" class="form-control array-class" /></div></div>
<div class="uk-width-medium-1-1"><div class="parsley-row"><select id="select_demo_1" name="quantity_type[]" class="md-input"id="val_select" required data-md-selectize><option value="">Select Quantity Type</option><option value="Cubic Yard">Cubic Yard</option><option value="Ton">Ton</option><option value="Piece">Piece</option></select></div></div></div><div class="uk-grid">
<div class="uk-width-1-1"><div class="parsley-row"><button type="button" onclick="close_me(this)"; class="md-btn md-btn-primary pull-right">remove</button></br></div></div></div></div></div> ');
}
function close_me(me) {
$(me).parent('new_field').remove();
}
Try this
<script>
function close_me(me)
{
$(document).find('.new_field').remove();
}
</script>
There are slight syntax errors:
onclick="close_me(this)"; -> onclick="close_me(this);"
$(me).parent('new_field').remove(); -> $(me).parent('.new_field').remove();
You are missing the dot to specify the parent class you're searching for. Also there is a typo into your html clone_row() function.
Here is correct the answer : https://jsfiddle.net/5ufsfLz1/7/
function clone_row() {
$('#add_more_fields').before('<div class="new_field"><div class="uk-grid" data-uk-grid-margin><div class="uk-width-medium-1-1"><div class="parsley-row"><label for="site Type">Product <span class="req">*</span></label><input type="text" name="product_require[]" data-parsley-trigger="change" required class="md-input" /></div></div><div class="uk-width-medium-1-1"><div class="parsley-row"><label for="site_area">Quantity<span class="req">*</span></label><input type="text" name="quantity[]" data-parsley-trigger="change" required class="md-input" /><input type="hidden" name="numb_array[]" value="0" class="form-control array-class" /></div></div><div class="uk-width-medium-1-1"><div class="parsley-row"><select id="select_demo_1" name="quantity_type[]" class="md-input" id="val_select" required data-md-selectize><option value="">Select Quantity Type</option><option value="Cubic Yard">Cubic Yard</option><option value="Ton">Ton</option><option value="Piece">Piece</option></select></div></div></div><div class="uk-grid"><div class="uk-width-1-1"><div class="parsley-row"><button type="button" onclick="close_me(this)" ; class="md-btn md-btn-primary pull-right">remove</button><br></div> </div> </div></div>');
}
function close_me(me) {
$(me).parents('.new_field').remove();
}
With the correct HTML :
<div class="new_field">
<div class="uk-grid" data-uk-grid-margin>
<div class="uk-width-medium-1-1">
<div class="parsley-row">
<label for="site Type">Product <span class="req">*</span></label>
<input type="text" name="product_require[]" data-parsley-trigger="change" required class="md-input" />
</div>
</div>
<div class="uk-width-medium-1-1">
<div class="parsley-row">
<label for="site_area">Quantity<span class="req">*</span></label>
<input type="text" name="quantity[]" data-parsley-trigger="change" required class="md-input" />
<input type="hidden" name="numb_array[]" value="0" class="form-control array-class" />
</div>
</div>
<div class="uk-width-medium-1-1">
<div class="parsley-row">
<select id="select_demo_1" name="quantity_type[]" class="md-input" id="val_select" required data-md-selectize>
<option value="">Select Quantity Type</option>
<option value="Cubic Yard">Cubic Yard</option>
<option value="Ton">Ton</option>
<option value="Piece">Piece</option>
</select>
</div>
</div>
</div>
<div class="uk-grid">
<div class="uk-width-1-1">
<div class="parsley-row">
<button type="button" onclick="close_me(this)" ; class="md-btn md-btn-primary pull-right">remove</button>
<br>
</div>
</div>
</div>
</div>
<div id="add_more_fields">
</div>
<a id="more" href="#" onClick="clone_row()">Click me</a>

How to get the values in $_POST array from the fields which are appended to the HTML table using JQuery after form submission?

I've one HTML form. This form is containing HTML table. The actual HTML table is very large. For your reference I'm showing below the HTML code of a form with tablw containing only two records:
<form action="rebates.php" role="form" method="post">
<div style="margin-left: 12px" class="col-xs-4">
<div class="form-group">
<label for="company_name" class="col-lg-4">Manufacturer </label>
<div class="col-lg-7">
<select id="company_name" name="company_name" class="form-control">
<option value="" selected='selected'>Select Manufacturer</option>
<option value="33" >Eywa Solutions</option>
<option value="37" >Amazon</option>
<option value="40" >Test</option>
<option value="42" >RK</option>
<option value="46" >Santa Margherita</option>
</select>
</div>
</div>
</div>
<div style="margin-left: -61px" class="col-xs-4">
<div class="form-group">
<label for="product_id" class="col-lg-3">Product </label>
<div class="col-lg-7">
<select id="product_id" name="product_id" class="form-control">
<option value="" selected='selected'>Select Product</option>
<option value="5" >Chesse</option>
<option value="8" >Laptop an</option>
<option value="9" >Prosecco</option>
</select>
</div>
</div>
</div>
</div>
<br/>
<div class="col-lg-2"></div>
<div class="col-md-8">
<div style="overflow:auto" class="well">
<button style="float:right; margin-bottom: 20px" class="btnAdd" type="button" class="btn btn-default"><i class="icon-plus"></i> Add New Rebate</button>
<br/>
<div class="table-responsive">
<table id="blacklistgrid" class="table table-bordered table-hover table-striped">
<thead>
<tr id="Row1">
<th style="vertical-align:middle" >Pack Of</th>
<th style="vertical-align:middle">Quantity</th>
<th style="vertical-align:middle">Volume</th>
<th style="vertical-align:middle">Unit</th>
<th style="vertical-align:middle">Rebate Amount</th>
</tr>
</thead>
<tbody>
<tr id="Row2">
<td><input type="text" name="pack[]" value="" class="form-control" size="8"/></td>
<td><input type="text" name="quantity[]" value="2" class="form-control" size="8"/></td>
<td><input type="text" name="volume[]" value="750" class="form-control" size="8"/></td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Units
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Microsecond</li>
<li>oz</li>
<li>ml</li>
<li>L</li>
<li>gms</li>
</ul>
</div>
</td>
<td>
<input type="text" name="amount[]" value="3.00" class="form-control" size="9"/>
</td>
</tr>
<tr>
<td><input type="text" name="pack[]" value="" class="form-control" size="8"/></td>
<td><input type="text" name="quantity[]" value="4" class="form-control" size="8"/></td>
<td><input type="text" name="volume[]" value="750" class="form-control" size="8"/></td>
<td>
<div class="btn-group">
<select name="units[]" class="form-control">
<option value="" selected='selected'>Select Unit</option>
<option value="5" >Microsecond</option>
<option value="7" >oz</option>
<option value="9" >ml</option>
<option value="10" >L</option>
<option value="12" >gms</option>
</select>
</div>
</td>
<td><input type="text" name="amount[]" value="7.00" class="form-control" size="9"/></td>
</tr>
</tbody>
</table>
<button style="float:right" class="btnAdd" type="button" class="btn btn-default"><i class="icon-plus"></i> Add New Rebate</button>
</div>
</div> <!-- /span8 -->
<div class="row">
<div class="col-xs-5"></div>
<div style="margin-left: -9px" class="col-xs-5">
<button type="button" class="btn btn-default">Go Back</button>
<button type="submit" class="btn btn-primary">Preview</button>
</div>
</div>
</div>
</form>
I'm dynamically appending rows to the table by clicking on a button(the button is present in a tag, you can see in above code). The jQuery code I writen for adding rows dynamically is as follows:
/*JQuery for appending rows at the end of table*/
<script language="javascript">
$( document ).ready(function() {
$('.btnAdd').click(function () {
var count = 1,
first_row = $('#Row2');
//while (count-- > 0) first_row.clone().appendTo('#blacklistgrid');
while (count-- > 0) first_row.clone().removeAttr('id').appendTo('#blacklistgrid');
});
});
</script>
Now the issue I'm facing is if I append one or more rows at the end of table, fill data in the textfields from each appended row and submit the form by clicking on Submit button, in $_POST I'm not able to get the data from appended rows. I'm getting the data only from the rows which are previously present when the page loads. So can anyone help me in getting the values from the dynamically appended rows also?
The HTMl code of dynamically appended table row is as follows:
<tr>
<td>
<input class="form-control" type="text" size="8" value="" name="pack[]">
</td>
<td>
<input class="form-control" type="text" size="8" value="2" name="quantity[]">
</td>
<td>
<input class="form-control" type="text" size="8" value="750" name="volume[]">
</td>
<td>
<div class="btn-group">
<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" type="button">
Units
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
Microsecond
</li>
<li>
oz
</li>
<li>
ml
</li>
<li>
L
</li>
<li>
gms
</li>
</ul>
</div>
</td>
<td>
<input class="form-control" type="text" size="9" value="3.00" name="amount[]">
</td>
</tr>
Well, you have done the right thing. Please see the name field of your input element.
<input type="text" name="pack[]" value="" class="form-control" size="8"/>
Please notice the name="pack[]" using an array of name as input. If you have cloned the table, the input element will be cloned. Since you aren't using an id, it's not a problem.
Now, when sending the data, in rebates.php check if the form data is present. It can be done by checking up the request method. It's a secure way. Once the check has succeeded, you can check if the field is present
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// handle the fields
$packs = null;
if (isset($_POST['pack']) {
$packs = $_POST['pack'];
}
}
Please notice that you are using pack without the [] to get input data from pack[] input fields. The variable $pack will contain an array. If you want to check the content, use var_dump($pack);. It should reveal all data from the available pack[] elements, either added dynamically or statically.
Then, if you have collected all data, you have to loop through it. It can be done with either for- or foreach-loop.
if ($packs != null) {
foreach($packs as $pack) {
// use the field $pack to do something
echo 'amount of pack : ' . $pack;
}
}
Do the same for other name fields which is also from array.
From jQuery Doc:
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
You are cloning table row with #Row2 id. To avoid it:
first_row.clone().removeAttr('id').appendTo('#blacklistgrid');
Alternatively, you could do something like...
while (count-- > 0) first_row.clone().appendTo('#blacklistgrid').attr('id','Row' + $('#blacklistgrid tr').length);

Categories

Resources