I have a form that has a list of checkboxes and selection option. It's basically an order form. When a customer clicks on a checkbox I'd like the value of the Select Option as well as the Checkbox's value to be sent with the form.
I really don't know AJAX. I'm using a script I found to get all the data to a php file. What do I need to add to the jquery to make the option and checkbox value of all the checked items combine as one variable?
<table>
<tr>
<td>
<select class="qty" name="qty" id="qty">
<option value="1">1</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="Part1_1" name="Part[]" type="checkbox" value="Part 1">
</td>
</tr>
<tr>
<td>
<select class="qty" name="qty" id="qty1">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="Part1_2" name="Part[]" type="checkbox" value="Part 2">
</td>
</tr>
</table>
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "orderform.php",
data: sendData,
success: function(data){
$(".response_msg").text(data);
$(".response_msg").slideDown();
}
});
});
});
</script>
EDIT:
I'd like to pass along to the php a variable for each part. So if Part 1 is checked then the value of the checkbox and the value of the quantity will be grouped together.
You could use a FormData object which would allow you to append the value of the ComboBox and Select list and send that in an ajax request.
Check this FormData
You need to add the select value this way. And you should also add the new parameter in your method on the server. In the example I named it as select_param.
$(document).ready(function() {
$("#contact-form").on("submit", function(e) {
e.preventDefault();
var sendData = $(this).serialize();
$.ajax({
type: "POST",
url: "orderform.php",
data: sendData + "&select_param1=" + $("#qty option:selected").text() +
"&select_param2=" + $("#qty1 option:selected").text(),
success: function(data) {
$(".response_msg").text(data);
$(".response_msg").slideDown();
}
});
});
});
Related
Morning,
I'm trying to create a table with dropdown (selectpicker A) fill dynamically with data selected with result of other input (selectpicker B) not into this table.
Filling (SelectPicker A) its OK for first row of table after selected value into SelectPicker B.
But when i add new line (by clone), SelectPicker A is empty for second row.
Need your help, thks !
My view code :
<select class="form-control selectpicker" name="nc_A" id="nc_A" onchange="select_B(this)" type="string" required>
<option disabled> </option>
</select>
...
<table id="sub_table" class="table">
<thead">
<tr>
<th>{{__('test.B')}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="form-control" name="nc_B[]" id="nc_B" type="string" required>
<option> </option>
</select>
</td>
</tr>
</tbody>
</table>
<i class="btn" onclick="add_row()">{{" + ".__('home.ajoutligne')}}</i>
My Jquery code :
var clonednc = $("#sub_table tbody tr:first").clone()
$("select[name*=nc_B]").selectpicker()
function add_row() {
$(clonednc).find("input").val("")
$("<tr>" + $(clonednc).html() + "</tr>").appendTo($("#sub_table tbody"))
$("#sub_table tbody tr:last select").selectpicker()
}
function select_B(e)
{
var selectionA = e.value;
$.ajax({
type: "POST",
url: "/production/selectionB",
data: {_token: CSRF_TOKEN, ncA : selectionA },
dataType: "JSON",
success: function (data) {
$(e).parents('div').find('#nc_B').empty();
$.each(data, function(key,value){
$(e).parents('div').find('#nc_B').append('<option value="'+value.NumB+'">'+ value.NumB +'</option>');
});
$("select[name*=nc_B]").selectpicker('refresh');
}
});
}
I want to control the dropdownlist to be enabled when the checkbox is checked by respective rows.
My current progress I manage to enable and disable the dropdownlist but its not controlled by the respective rows.
Whenever the checkbox is checked, all dropdownlist were enabled.
the php code is partly from html:
<td>
<select class="selection" name="lotDist[]" >
<option></option>';
==== sql queries in here ====
while ($row2 = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
echo '
<option value="'.$row["LotNo"].' / '.$row2["Grouping"].' - '.$row2["InBulkForm"].'">
'.$row2["Grouping"].' - '.$row2["InBulkForm"].'</option> ';
}
echo '
</select>
</td>
<td>'.$row["LoadingWeek"].'</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row["LotNo"].'" '.$check.'>
</td>
<script>
$(document).ready(function() {
$('.selection').attr('disabled', 'disabled');
var $checkBox = $('.chkBox');
$checkBox.on('change', function(e) {
//get the previous element to us, which is the select
var $select = $('.selection')
if (this.checked) {
$select.removeAttr('disabled');
} else {
$select.attr('disabled', 'disabled');
}
});
});
</script>
With $(this).closest('tr').find('.selection'); you can find the corresponding select box the belongs to the row of the changed checkbox.
The closest() function finds the first parent that matches the selector. Since you are using a table we can select the row with the tr selector and find the corresponding select element within the row.
Also changed the way the select box is enabled and disabled. It's better to change the property then the attribute. and code is shorter too. However your method works as well.
$(document).ready(function() {
$('.selection').attr('disabled', 'disabled');
var $checkBox = $('.chkBox');
$checkBox.on('change', function(e) {
var $select = $(this).closest('tr').find('.selection');
$select.prop('disabled', !this.checked);
/* This works too but its better to change the property and the code is shorter when using the this.checked boolean.
if (this.checked) {
$select.removeAttr('disabled');
} else {
$select.attr('disabled', 'disabled');
}
*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select class="selection" name="lotDist[]">
<option>1</option>
<option>2</option>
</select>
</td>
<td>week</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row[" LotNo "].'" '.$check.'>
</td>
</tr>
<tr>
<td>
<select class="selection" name="lotDist[]">
<option>1</option>
<option>2</option>
</select>
</td>
<td>week</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row[" LotNo "].'" '.$check.'>
</td>
</tr>
</table>
I have the following codes which makes an select list to auto populate from a table and another which auto populate from another table (both in the same db) without using a submit button. All works ok but there is also a button that if clicked will make another table row with the same select fields.
The questions are: - what is wrong in the code because when i click on add another row button, it displays another row but only the first select is operational. i need both select to be operational; - what to use instead of the first javascript code for the cloning of the row but keep full functionality
Here are the codes:
Javascript for new row
<script>
function addField(n) {
var tr = n.parentNode.parentNode.cloneNode(true);
document.getElementById('tbl').appendChild(tr);
}
</script>
script querying
<script>
$(document).ready(function() {
$("#id_produs").change(function() {
var id_produs = $(this).val();
$.ajax({
url: 'query.php',
type: 'post',
data: {
id_produs: id_produs
},
dataType: 'json',
success: function(response) {
var len = response.length;
$("#cod_produs").empty();
for (var i = 0; i < len; i++) {
var id_produs = response[i]['id_produs'];
var cod_produs = response[i]['cod_produs'];
$("#cod_produs").append("<option value='" + id_produs + "'>" + cod_produs + "</option>");
}
}
});
});
});
</script>
PHP & HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl">
<tr>
<td>Produse</td>
<td>Cod Produs</td>
<td>Cantitate</td>
<td></td>
</tr>
<tr>
<td>
<select id="id_produs">
<option value="0">- Select -</option>
<?php
if ($rezultatproduse->num_rows > 0) {
while($rowproduse = $rezultatproduse->fetch_assoc()) {
?>
<option value="<?php echo $rowproduse[" id_denumire "]; ?>">
<?php echo $rowproduse["denumire"]; ?>
</option>
<?php
}
}
?>
</select>
</td>
<td>
<select id="cod_produs">
<option value="0">- Select -</option>
</select>
</td>
<td>
<input type="text" name="cantitate" />
</td>
<td><input type="submit" class="button" value="Add another line" onclick="addField(this);" /></td>
</tr>
</table>
and also query.php
<?php
include "conn.php";
$id_produs = $_POST['id_produs'];
$sql = "SELECT id_produs, cod_produs FROM coduri_produse WHERE id_produs = ".$id_produs;
$result = mysqli_query($conn,$sql);
$coduri_arr = array();
while( $row = mysqli_fetch_array($result) ){
$id_produs = $row['id_produs'];
$cod_produs = $row['cod_produs'];
$coduri_arr[] = array("id_produs" => $id_produs, "cod_produs" => $cod_produs);
}
// encoding array to json format
echo json_encode($coduri_arr);
?>
Change this
$("#id_produs").change(function() {
to this
$(document).on('change', "#id_produs", function() {
If you want an event to work on dynamically added elements you need to bind it to document and not to elements. Because jQuery bunds an event only to elements which are currently in DOM.
$(document).on('change', "#id_produs", function() {
var id_produs = $(this).val();
$.ajax({
url: 'query.php',
type: 'post',
data: {
id_produs: id_produs
},
dataType: 'json',
success: function(response) {
var len = response.length;
$("#cod_produs").empty();
for (var i = 0; i < len; i++) {
var id_produs = response[i]['id_produs'];
var cod_produs = response[i]['cod_produs'];
$("#cod_produs").append("<option value='" + id_produs + "'>" + cod_produs + "</option>");
}
}
});
});
function addField(n) {
var tr = n.parentNode.parentNode.cloneNode(true);
document.getElementById('tbl').appendChild(tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl">
<tr>
<td>Produse</td>
<td>Cod Produs</td>
<td>Cantitate</td>
<td></td>
</tr>
<tr>
<td>
<select id="id_produs">
<option value="0">- Select -</option>
<option value="test_value">
test value
</option>
</select>
</td>
<td>
<select id="cod_produs">
<option value="0">- Select -</option>
</select>
</td>
<td>
<input type="text" name="cantitate" />
</td>
<td><input type="submit" class="button" value="Add another line" onclick="addField(this);" /></td>
</tr>
</table>
EDIT
Also you should avoid adding elements with the same id.
That is the reason why wrong select is activated. Change id to class and of course in jQuery change id to class.
The same goes for this $("#cod_produs"). Make sure that you get the exzact element. Because right now it will work for all elements with id="cod_produs".
So change to something like this (example):
Instead of this
$("#cod_produs").empty();
do
$(this).closest(".cod_produs").empty();
I am a beginner in Jquery and Rails.
I am trying to fetch data from rails controller and set the same to text fields located in Dynamic table.
HTML
<tbody id="template">
<tr>
<td>
<select name="order[order_placed][][itemname]" id="order_place_id" class="form-control delete-comment" style="width: 300px">
<option value=""></option>
<% Item.all.each do |item| %>
<option value="<%= item.item_name %>">
<%= item.item_name %>
</option>
<% end %>
</select>
</td>
<td><input name="order[order_placed][][quantity]" type="text" size='10' class="form-control" /></td>
<td><input name="order[order_placed][][unitprice]" type="text" size='10' class="form-control" /></td>
<td><input name="order[order_placed][][tax]" type="text" size='10' class="form-control"/></td>
<td><input name="order[order_placed][][discount]" type="text" size='10' class="form-control"/></td>
<td><input name="order[order_placed][][itemtotalprice]" type="text" size='10' class="form-control" /></td>
<td>
<button type="button" class="btn btn-default btn-sm sub" onClick="$(this).closest('tr').remove();">
<span class="glyphicon glyphicon-minus"></span>
</button>
</td>
</tr>
</tbody>
JS
$(document).on('change', 'select', function() { //var url = $('.delete-comment').attr('data-url');
$.ajax({
url: "/items/getdata",
type: 'get',
data: {data_value: $(this).val()},
dataType: 'json',
success: function (data) { $(this).closest('tr').next('td').next('td').next('td').find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
$('input[name="order[order_placed][][tax]"]').val(data.tax);
$('input[name="order[order_placed][][discount]"]').val(data.discount);
}, error: function () {
alert('error');
}
});
});
Data is fetched properly and is set to the text boxes if we assign them directly(data.tax and data.discount are set properly).
As the table is dynamic, i am trying to put data by finding the closest tr element followed by next td(Select element) again next td(Quantity) again next td(Unit Price). [This is the text field i wanted to place data.]
But this is not working properly.
Can some one please help.
Advance Thanks...!!!
this doesn't refers to current element the success callback, thus $(this) will not work.
You can cache the reference of TR in a variable which can be used is the success callback
$(document).on('change', 'select', function() { //var url = $('.delete-comment').attr('data-url');
//Keep a reference of current element
var tr = $(this).closest('tr');
$.ajax({
...
success: function(data) {
tr.find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
tr.find('input[name="order[order_placed][][tax]"]').val(data.tax);
tr.find('input[name="order[order_placed][][discount]"]').val(data.discount);
},
});
});
OR, You can set context option of $.ajax()
$(document).on('change', 'select', function() {
$.ajax({
...
context: $(this).closest('tr'), // Set context to TR
success: function(data) {
$(this).find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
$(this).find('input[name="order[order_placed][][tax]"]').val(data.tax);
$(this).find('input[name="order[order_placed][][discount]"]').val(data.discount);
},
});
});
I have the HTML code as follows.
<table id="items">
<tr class="item-row">
<td class="item-name"><div class="delete-wpr"><a class="delete" href="javascript:;" title="Remove row">-</a></div></td>
<td><input type="text" id="slslno" class="slno"/></td>
<td><input type="text" class="cost"/></td>
<td><input type="text" class="qty"/></td>
<!-- <td><span class="price"></span></td>-->
<td class="price"></td>
<a class="add" id="addrow" href="javascript:;" title="Add a row">+</a> </tr>
</table>
It has a button named "Add a row" which adds more rows dynamically.
Then I have this bind, which calls an update function during blur of the slno field.
function bind()
{
$(".slno").blur(update_unitcost);
}
The function update_unitcost is as follows.
function update_unitcost()
{
var unitprice1=$(this).val();
unitprice={"unitpricereal":unitprice1};
$.ajax({
type: "POST",
url: "findcost.php",
data: unitprice,
success: function(unitp){
$( ".cost" ).val(unitp);
}
});
}
In the above function, I am able to get the values of with the this selector, but when it comes to setting the value in the following line,
$( ".cost" ).val(unitp);
It just resets every ".cost" classes to that particular number. How can I set values to individual delegated rows? I tried the following approach too, but it failed.
var row = $(this).parents('.item-row');
row.find('.cost').val(unitp);
Set a variable in your function to only target the specific .cost element you wish to update instead of all of them.
function update_unitcost()
{
var unitprice1=$(this).val();
var costItem = $(this).parent().parent().find('td input.cost');
unitprice={"unitpricereal":unitprice1};
$.ajax({
type: "POST",
url: "findcost.php",
data: unitprice,
success: function(unitp){
costItem.val(unitp);
}
});
}