get data-price of selected value in dropdown in a array - javascript

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.

Related

Looping Table Rows in Form

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.

Placing id on input and select tags inside td depending on query result looping

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;
}
}

How can I get the data from hidden field in jQuery? (hidden field has class in place of id)

I am getting data from the database:
<table>
<?php
$select_data = mysql_query(" select * from `data_table` ") or die(mysql_error());
while($data_row = mysql_fetch_array($select_data))
{
?>
<tr>
<td>
<img src="../Stuff-site_data_images/<?php echo$data_row['data_image_name']?>" width="100" height="100" />
</td>
<td> <?php echo $data_row['data_image_name'];?> </td>
<td> <?php echo $data_row['data_description'];?> </td>
I want to get data from here:
<td align="center" class="row_id">
<input class="inner_row_id" type="hidden" value="<?php echo $data_row['data_id'];?>" name="show_detail_button" id="show_detail_button"> Show All
</td>
I want to get data from here:
</tr>
<?php
}
?>
</table>
so as far as I know jQuery will conflict when there is more than 1 id so that's why I used CSS class names "row_id" & "inner_row_id".
When I click on "row_id" I want the value of "inner_row_id"
and for that I have written the code below:
$(".row_id").click(function(e){
var row_id = $(".inner_row_id").val();
alert("Le click thyuu....");
});
Is there any one who suggest me what to do in this...
This should work
$(".row_id").click(function(e){
alert($(this).find('.inner_row_id').val());
})
The "click" function gives you access to this, which is the element that you clicked on. Find then looks for any decedents of the element which have class .inner_row_id.
Link to jsFiddle
As I see you are creating the input dynamically so use below JS:
$(".row_id").on('click',function(e){
var row_id = $(this).children('.inner_row_id').val();
alert("Le click thyuu....");
});
DEMO.

How do i get the javascript dynamic row values in php?

jsfiddle
I'm trying to print the input text field values on nextpage (postdata.php). But it always print the first row result only. I didn't get the remaining row values on next page. I've posted my full codes on jsfiddle.. How do i get the remaining js dynamic row values in php (postdata.php page)?
JS
$(document).ready(function(){
$("span").click(function(){
$("#container").append('<tr><td>Email : </td><td><input type="text" name="email[]" placeholder="Email id" /></td> <td>Name : </td><td><input type="text" name="name[]" placeholder="Your Name "/></td> <td><a title="Delete this row" href="javascript:void(0);" class="remove">Del</a></td></tr>');
});
$("#container").on('click','.remove',function(){
$(this).parent().parent().remove();
});
});
Php
<?php
echo "
<table>
<tr>
<td>
Email :
</td>
<td>
$_POST[email]
</td>
<td>
Name :
</td>
<td>
$_POST[name]
</td>
</tr>
</table>";
?>
Since name of fields you declared is array the $_POST becomes multidimensional array.So try like this
<?php
$size = sizeof($_POST['email']);
echo "<table>" ;
for($i=0; $i<$size;$i++)
{
echo "
<tr>
<td>
Email :
</td>
<td>
".$_POST['email'][$i]."
</td>
<td>
Name :
</td>
<td>
".$_POST['name'][$i]."
</td>
</tr>
";
}
echo "</table>";
?>
also in your html change names of Name and Email field to name[] and email[] respectively.Also you have misplaced the form tag. It starts after <table> and ends after <table>. which was not correct. so place form tag before table tag
When you add square brackets to the name of an input field, PHP will receive it's value as an array. Your JS code is fine, but the PHP code doesn't handle arrays at all. Look at the following:
echo "
<table>";
if(!is_array($_POST['email'])) {
$_POST['email'] = array($_POST['email']);
$_POST['name'] = array($_POST['name']);
}
foreach($_POST['email'] as $key => $email) {
// get the corresponding name to the email
$name = $_POST['name'][$key];
echo "<tr>
<td>
Email :
</td>
<td>
$email
</td>
<td>
Name :
</td>
<td>
$name
</td>
</tr>";
}
echo "</table>";
Note: This code will check whether multiple values were submitted or not and will work in both scenarios.

Display data on blur

I have a simple table (dynamically generated from an array) where i can put the amount of pieces so the price can calculate automaticly (on blur) in the price field. Both fields are form-input fields.
So the source therefore looks like this:
<?php
foreach($ItemArray['1'] as $key => $value) {
echo '
<tr>
<td height="30" valign="middle">'.$value['nr'].'</td>
<td valign="middle">'.$value['product'].'</td>
<td valign="middle">'.$value['describe'].'</td>
<td valign="middle" id="stockprice_'.$key.'">
<input name="Field_Price_'.$key.'" id="Field_Price_'.$key.'" value="'.$value['price'].'" type="text" /></td>
<td valign="middle" class="box_darker" id="amount_'.$key.'">
<input name="Field_Amount_'.$key.'" id="Field_Amount_'.$key.'" type="text" /></td>
<td valign="middle" id="price_'.$key.'">
<input name="Field_Total_'.$key.'" id="Field_Total_'.$key.'" type="text" />
</td>
</tr>'; }
;?>
The way i would realize that is when a user inputs any amount (in "Field_Amount_") and go out from this (onblur) so the amount field should take the value (from "Field_Amount_") and then have to put the total price (in "Field_Total_"). So i try this solution, but it won't work.
$(document).on('blur', '[id^=Field_Amount_]', function(){
Amount = $(this).parent().find('[id^=Field_Amount_]').val();
StockPrice = $(this).parent().find('[id^=Field_Price_]').val();
Price = $(this).parent().find('[id^=Field_Total_]');
RowPrice = Amount * StockPrice;
if(Amount) { $(Price).text(accounting.formatNumber(RowPrice, 2, ".", ","));}
});
Can anyone give me a suggestion how i have to do this? Many thanks.
Thanks a lot for helping me.
I have a feeling that the code:
$(this).parent().find('input[id^=Field_Amount_]').val();
actually points to the <td> tag itself.
The `$(this)` is actually pointing to the input field of the amount.
var amount = $(this).val();
//field - td - tr
var stockPrice = $(this).parent().parent().find('input[id^=Field_Price_]').val();
and so forth...
Change your selector from [id^=Field_Amount_] to input[id^=Field_Amount_]

Categories