So I'm trying to code a form that sits inside a table that has only one row. The row contains a drop down box, text box and a checkbox.
<table class="table text-size-12">
<thead>
<tr>
<th scope="col">Location</th>
<th scope="col" class="text-nowrap">COD Charge</th>
<th scope="col">Allow Negotiate</th>
</tr>
</thead>
<tbody>
<?php
for($rows = 0; $rows < 5; $rows++):
?>
<tr>
<td>
<select name="location" class="form-control" style="width:250px">
<option value="">--- Select Location ---</option>
<?php foreach ($locations as $state): ?>
<optgroup label="--- <?= $state->name ?> ---">
<?php foreach ($state->locations as $area): ?>
<option value="{{ $key }}"><?= $area->name ?></option>
<?php endforeach ?>
</optgroup>
<?php endforeach ?>
</select>
</td>
<td>
<input type="text" id="shipping_fee_value">
</td>
<td>
<input type="checkbox" id="shipping_fee_allow_negotiate">
<script>
document.getElementById('shipping_fee_allow_negotiate').onchange = function (){
document.getElementById('shipping_fee_value').disabled = this.checked;
}
</script>
</td>
</tr>
<?php endfor ?>
</tbody>
</table>
As you can see, I've used Javascript so that if the checkbox is checked, the text box will be disabled.
<td>
<input type="text" id="shipping_fee_value">
</td>
<td>
<input type="checkbox" id="shipping_fee_allow_negotiate">
<script>
document.getElementById('shipping_fee_allow_negotiate').onchange = function (){
document.getElementById('shipping_fee_value').disabled = this.checked;
}
</script>
</td>
And I've also looped the rows 5 times using for. My problem is, the checkbox disabling text box script only works in the first row, how do I allow each row to be independent?
P.S. I prefer not hard coding every specific row just because so.
You are repeating the id of the elements. You can't do this. id are meant to be unique. Set a unique id on the every element.
<td>
<input type="text" id="shipping_fee_value_<?= $rows ?>">
</td>
<td>
<input type="checkbox" class="shipping_fee_allow_negotiate" data-target="shipping_fee_value_<?= $rows ?>">
<script>
var elements = document.getElementsByClassName('shipping_fee_allow_negotiate');
for (var i = 0; i < elements.length; i++) {
elements[i].onchange = function() {
document.getElementById(this.dataset.target).disabled = this.checked;
}
}
</script>
</td>
Here we are using the $row variable to add a index to the id property on the input.
<input type="text" id="shipping_fee_value_0"/>
Also we use the data-target property on the checkbox to tell him which specific input to handle on the onchange callback.
<input type="checkbox" class="shipping_fee_allow_negotiate" data-target="shipping_fee_value_0">
And finally the selector to assign the callback is using getElementsByClassName to select all the checkboxes.
Because your id is common that's why they consider only the first row instead of common id use dynamic id.
Related
asigning id for each input tag and select tag in tr depending on query result
I tried a code like this putting an id inside the input tag and select tag
<table id="myTable">
<thead>
<th>Progress</th>
<th>Amount</th>
<th>Action</th>
</thead>
<tbody>
<?php $qry = "SELECT * FROM trade";
foreach($conn->query($qry) as $data){
?>
<form action="update.php" method="post">
<tr>
<td><select name="progress" id="select_progress" onclick="changeSetting()">
<option value="Partial">Partial</option>
<option value="Full">Full</option>
</select></td>
<td><input type="number" name="amount" id="amount"></td>
<td><input type="submit" name="update" value="Update"></td>
<input type="hidden" name="tradeid" value="<?php echo $data['tradeID'];?>">
</tr>
</form>
<?php }?>
</tbody>
</table>
Now i coded the javascript like this:
function changeSetting(){
var selectValue = document.getElementById("select_progress").value;
var amountValue = document.getElementById("amount");
if(selectValue.value === "Partial"){
amountValue.required = true;
}else if(selectValue.value === "Full"){
amountValue.required = false;
}
}
The first row seems to be doing fine, but the second row doesn't apply the javascript i wrote. Any suggestion on how to approach this would be welcome. I know, that an id should be unique for each element but if i have about 50 results in my query i dont know how to place id's on each input and select tag inside my table. Any suggestions or help is greatly appreciated.
All your elements have the same id value, so when you try to getElementById it always returns the first one. One way to work around this is to add the tradeID value to each element's id value to distinguish them. For example:
<td><select name="progress" id="select_progress<?php echo $data['tradeID'];?>" onchange="changeSetting(<?php echo $data['tradeID'];?>)">
<option value="Partial">Partial</option>
<option value="Full">Full</option>
</select></td>
<td><input type="number" name="amount" id="amount<?php echo $data['tradeID'];?>"></td>
<td><input type="submit" name="update" value="Update"></td>
Then you would modify your JS as so:
function changeSetting(id){
var selectValue = document.getElementById("select_progress" + id).value;
var amountValue = document.getElementById("amount" + id);
if(selectValue === "Partial"){
amountValue.required = true;
}else if(selectValue === "Full"){
amountValue.required = false;
}
}
I am using session variable to keep track of items in the cart. I generate a table using loop to display contents of the cart. The code for table is as follow:
<?php
$count=0;
$grandTotal=0;
foreach($_SESSION['cart'] AS $product) {
$table=$product['table'];
$id=$product['id'];
$Name=$product['name'];
$qty=$product['quantity'];
$price=$product['price'];
$total=$qty*$price;
$grandTotal +=$total;
?>
<tr>
<td class="cart_product">
<img src=<?php $i=2; echo "images/".$table."/".$id.".jpg"?> height="150" width="150">
</td>
<td class="cart_description">
<h4><?php echo $Name?></h4>
<p><?php echo "Web ID: ".$id?></p>
</td>
<td class="cart_price">
<p><?php echo $price?></p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" id="increment"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" id="qty" value="<?php echo $qty?>" autocomplete="off" size="2">
<!-- <p class="cart_quantity_input" name="qunatity" id="qty"><?php echo $qty?></p>-->
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" > - </a>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price"><?php echo $total ?></p>
</td>
<td class="cart_delete">
<a class="cart_quantity_delete" href="addToCart.php?table=men&action=del&id=<?php echo $id ?>"><i class="fa fa-times"></i></a>
</td>
</tr>
<?php
}
$tax=0.15*$grandTotal;
?>
I am having problem with + and - buttons within a tags. I want to increment or decrement value in input field named quantity. But since i am generating table in a loop i do not know the id of each field. I want to do something like this:
<script>
$(document).ready(function () {
$("#increment").click(function () {
var oldval=document.getElementById("qty").value;
var newval=parseInt(oldval);
document.getElementById("qty").value=newval++;
});
});
</script>
But this method always increments first quantity field in the table. How do i get ids of other quantity fields in the table?
Dont use ids inside loop.Just use class for that>check the snippet for a smaple demo
$(document).ready(function () {
$(".increment").click(function () {
var oldval = $(this).prev('.qty').val();
var newval = parseInt(oldval)+ 1;
$(this).prev('.qty').val(newval);
});
$(".decrement").click(function () {
var oldval = $(this).next('.qty').val();
var newval = parseInt(oldval) - 1;
$(this).next('.qty').val(newval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <tr>
<td>sl No</td>
<td>name</td>
<td>Dept</td>
<td>dummy</td>
<td>dummy</td>
<td>dummy</td>
</tr>
<tr>
<td>1</td>
<td>name</td>
<td>
</td>
<td>name</td>
<td>name</td>
<td> </td>
</tr>
<tr>
<td>2</td>
<td>name</td>
<td>Dept</td>
<td>name</td>
<td> <button class="decrement"> - </button>
<input type="text" class="qty" value="1"/>
<button class="increment">+ </button>
</td>
<td>name</td>
</tr>
<tr>
<td>3</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
</tr>
</table>
There are 2 solutions to this problem:
When generating table using php, assign unique id to each row's <a> and <input>, such as #increment_id8878 and #input_id8878. Then when #increment or #decrement button is clicked, operate <input> with corresponding id.
Operate <input> element with jQuery's relative selector.
For example:
$('.increment').click(function() {
var inputEle = $(this).siblings('input');
var originVal = inputEle.val();
inputEle.val(parseInt(originVal) + 1);
});
A jsfiddle is made for the 2nd solution.
BTW, duplicate id should be avoided in HTML code.
Don't use same id for multiple elements instead use class like below
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" class="increment">
same is case of decrement button user class
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" class="decrement"> - </a>
You can bind click event to these anchors and change the quantity in input inside same parent div
$(function(){
$('.increment').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)+1;
$input.val(value);
});
$('.decrement').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)-1;
$input.val(value);
});
});
I am trying to figure out how to submit button with two actions based on dropdown list that I get from MySQL. One is for updating to database and then proceed to nextpage while the other actions is to proceed to specific page. I've tried all the solution but most of them only has a few dropdown menu, mine have 40 menus.
This is my JavaScript
<script type='text/javascript'>
$(window).load(function(){
//$(document).ready(function() {
<!--To Enable button "MULA"-->
$('#lst_respon').change(function() {
if ($(this).find(":selected").val()!='11') {
$('#button').attr('disabled',true);
} else {
$('#button').removeAttr('disabled');
}
});
$('#lst_respon').change(function()
{
$('#form1').submit();
});
});
function changeTextBox()
{
var val=$('#lst_respon').val();
if(val==='11')
{
$('#value').prop('disabled', true);
}
else{$('#value').removeAttr("disabled");}
}
</script>
And this is my HTML
<div align="center">
<table width="60%" border="1" class="zui-table">
<thead>
<tr>
<th colspan="3" align="center">Status</th>
</tr>
</thead>
<tr>
<?php
$smt = $conn->prepare('select * From lookup_caraterima');
$smt->execute();
$data = $smt->fetchAll();
$smt2 = $conn->prepare('select * From lookup_kodrespon');
$smt2->execute();
$data2 = $smt2->fetchAll();
?>
<td width="253">Cara Terima</td>
<td width="5">:</td>
<td width="164">
<select name="lst_cterima" id="lst_cterima">
<?php foreach ($data as $row): ?>
<option value="<? echo $row["kodterima"];?>"><? echo $row["jenis"];?>
</option>
<?php endforeach ?>
</select>
</td>
</tr>
<tr>
<td>Kod Respon</td>
<td>:</td>
<td>
<select name="lst_respon" id="lst_respon" onchange="changeTextBox()">
<?php foreach ($data2 as $row2): ?>
<option value="<? echo $row2["kod"];?>"><? echo $row2["kod"].'- '.$row2 ["Keterangan"];?></option>
<?php endforeach ?>
</select></td>
</tr>
<tr>
<td><label for ="sebab">Sebab</label></td>
<td>:</td>
<td><input type="textbox" id="value" size="100" disabled</td>
</tr>
<tr>
<td colspan="3" align="center"><form name="form1" method="post" action="main.php?load=4&SerialID=<?php echo $noSiri; ?>&month=<?php echo $monthA;?>&year=<?php echo $yearA;?>&tab=A">
<input type="submit" name="button" id="button" value="Teruskan" class="myButton">
</form></td>
</tr>
</table>
</div>
For an automated solution to submit a form based a dropdown selection, you could try using the data attribute, something like:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form id="tester">
<select name="test">
<option value="best" data-instructions='<?php echo json_encode(array('action'=>'page1')); ?>'>Best</option>
<option value="rest" data-instructions='<?php echo json_encode(array('action'=>'page2')); ?>'>Rest</option>
<option value="guest" data-instructions='<?php echo json_encode(array('action'=>'page3')); ?>'>Guest</option>
<option value="lest" data-instructions='<?php echo json_encode(array('action'=>'page4')); ?>'>Lest</option>
</select>
<input type="submit" name="submit" value="SUBMIT" />
</form>
<script>
$(document).ready(function() {
$('#tester').submit(function(e) {
// Stop form from submitting
e.preventDefault();
// Get the select dropdown
var thisSelect = $(this).find('select[name=test]');
// Get the value
var thisVal = thisSelect.val();
// Get the options separately
var thisOpts = thisSelect.children();
// Create a holder
var thisData = {};
// Loop through the options
$.each(thisOpts,function(k,v) {
// Get the current value
var currVal = $(v).attr('value');
// If the current value is the same as the value selected
if(currVal == thisVal) {
// Get the instructions from the option
thisData = $(v).data('instructions');
// Stop looping
return false
}
});
console.log(thisData);
});
});
</script>
On submission, the selection will give you an object that you can use to instruct how to submit the form:
// thisData.action
{action: "page2"}
I have following code
<tbody>
<tr>
<td style="width:40%">
<select id="pname.0" name="pname[]" class="form-control ">
<?php
$this->db->order_by('name','asc');
$prod = $this->db->get('product')->result_array();
foreach($prod as $row): ?>
<option data-price="<?php echo $row['price'];?>" value="<?php echo $row['prod_id'];?>" >
<?php echo ucwords($row['name']);?>
</option>
<?php endforeach; ?>
</select>
</td>
<td style="width:10%">
<input class="form-control" onchange="javascript:calc();" id="item_quantity.0" name="qnty[]" value=""/>
</td>
<td class="text-right" style="width:10%">
<input class="form-control text-right" onchange="javascript:calc();" id="item_price.0" name="price[]" value=""/>
</td>
<td class="text-right" style="width:10%">
<input class="form-control text-right" id="subtot.0" readonly name="item_sub_total" value=""/>
</td>
</tr>
</tbody>
Now I want to get the value of data-price attribute of selected option on change in Dropdown to the textbox having dynamic id item_price_0. This is changing as I have added the add row button. When I click on Add row, the id will become item_price_1.
Kindly help me how can I get these value using jquery or javascript
Is this what you were after?
//if your table has an id or class, use it as tag selector is not good without context.
//$(".tableClass") OR $("#tableID")
$("table").on('change', "select[id^='pname']", function() {
var $row = $(this).closest("tr");
$row.find("input[id^='item_price']").val( $(this).find('option:selected').data("price") );
});
So, to use . in selectors, you need to escape them as mentioned (2nd para) in jQuery selectors API
Demo#fiddle
You can listen the change on your element, and get the price attribute like so:
$('#pname.0').on('change', function(){
var price = $(this).find('option:selected').data('price');
});
PS: I'm not sure you can use "." in ID attribute.
First assign a class to all select. (in addition to "form-control"). I suppose selects have test class
var selectedPrices = [];
var i = 0;
$(".test").each(function(){
selectedPrices[i] = $(this).find(":selected").attr("data-price");
i++;
});
Now, selectedPrices is an array of prices. You can do anything you want with it.
In my code,when any text is entered into the textbox and click on add attribute button, entered value displayed on page for two times, one in first row of table and another one is in first row of second table. Now question is, when i entered text into another textbox which is in second row of second table, it should display the entered text.but it can't display. it is not working.
<script>
var i = 0;
document.getElementById('add-val').innerHTML='';
function insRow()
{
i++;
var x=document.getElementById('myTable').insertRow(-1)
var a=x.insertCell(-1)
var txt=document.getElementById('add-val').value;
a.innerHTML=txt;
// for <tr> of table
var row = document.getElementById("myRow");
var newrow=document.getElementById("myRow1");
var x = row.insertCell(-1);
var y = newrow.insertCell(-1);
x.innerHTML=txt; //+ '<br>' +
y.innerHTML='<input type="text" name="nm" />';
}
document.getElementById('add-val').innerHTML='';
</script>
& this is html code.
<form method="post" name="form">
<input type="text" name="attr" id="add-val"> <input type="button" onClick="insRow()" value="Add Attribute">
<table width="27" height="17" id="myTable"> </table>
<table cellpadding="13px">
<tr id="myRow"> </tr>
<tr id="myRow1"> </tr>
</table>
<input type="submit" value="Add option" onClick="insRow()"/>
<?php
if(isset($_POST['submit']))
{
$val= $_POST['add'];
echo $val;
}
?>
</form>
It should be
y.innerHTML='<input type="text" name="nm[]" />';
The []'s after nm
name="nm[]"
Serve to store all new generated fields into an array, which can then be accessed by $_POST
Which you then just access like so....
$val = $_POST['nm'];
foreach($val as $v){
echo $v; // display what user entered
}
// var_dump($val) will show you all the users seperate input for each field
HTML Code :
<form method="post" name="form">
<input type="text" name="attr" id="add-val"> <input type="button" onClick="insRow()" value="Add Attribute">
<table width="27" height="17" id="myTable"> </table>
<table cellpadding="13px">
<tr id="myRow"> </tr>
<tr id="myRow1"> </tr>
</table>
<input type="submit" value="Add option" onClick="insRow()"/>
<?php
if(isset($_POST['submit']))
{
$val= $_POST['nm'];
echo $val;
}
?>
</form>
put the name of input whos value you want to print in place of attr
$val= $_POST['attr'];