I have n dynamically generated sliders each with the given DOM id slider{n}.
Because I don't know how many sliders I will have, I have attached my on slideStop event to the class, and then using $(this) to get the id, and do whatever's relevant to that slider.
$(".slider").on("slideStop", function(slideEvt) {
var rowoffset = $(this).attr("id").substring(6);
$("#percentage" + rowoffset).text(slideEvt.value);
updateNumbers(rowoffset);
});
Everything works as planned except the script is executing the updateNumbers() method twice.
As you can see here my postdata is logged to console twice along with each response, one with the correct values, and a 2nd call which has undefined values.
it's clear that the first response is a response to the 2nd call.
Why is my method firing twice? Is it something to do with the slider library or jquery?
How come the response to the failed call comes back first even though the failed call is always executed 2nd?
Here is the updateNumbers method, which certainly doesn't call its self.
function updateNumbers(rowoffset){
//get variables from DOM element values
var percentage = $("#slider" + rowoffset).val();
var group = $("#rrgroup").val();
var rrclass = $("#rrclass").val();
var category = $("#rrcategory").val();
var subcategory = $("#subcategory" + rowoffset).val();
var period = $("#rrperiod").val();
var year = $("#rryear").val();
var yearmonth = $("#rryearmonth").val();
var rangesize = $("#rangesize" + rowoffset).text();
var storesstring = $("#rrstores").val();
if(storesstring == ""){
storesarray = [];
} else {
var storesarray = storesstring.split(",");
}
var postdata = {percentage: percentage,
group: group,
class: rrclass,
category: category,
subcategory: subcategory,
period: period,
year: year,
yearmonth: yearmonth,
stores: storesarray,
rangesize: rangesize};
console.log(postdata);
$.ajax({
url: "ajaxrangemix.php",
type: "post",
dataType: 'json',
data: postdata,
success: function (response) {
console.log(response);
$("#dropskus" + rowoffset).text(response.skus);
$("#keepsales" + rowoffset).text(response.sales);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
HTML
<div class='panel-body' id='rangemixbody'>
<input type='hidden' id='rrgroup' value="<?php echo $group; ?>">
<input type='hidden' id='rrclass' value="<?php echo $class; ?>">
<input type='hidden' id='rrcategory' value="<?php echo $category; ?>">
<input type='hidden' id='rrperiod' value="<?php echo $period; ?>">
<input type='hidden' id='rryear' value="<?php echo $yr; ?>">
<input type='hidden' id='rryearmonth' value="<?php echo $yrmth; ?>">
<input type='hidden' id='rrstores' value='<?php implode(",", $storename); ?>'>
<table class='table table-striped'>
<thead>
<tr>
<th>Subcategory</th>
<th><span>0%</span><span class="pull-right">100%</span></th>
<th>%</th>
<th>Current Range Size</th>
<th>Drop Skus</th>
<th>Keep Sales</th>
<th>Sales Share</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
$subcategories = array();
foreach($rangereviewarray as $row){
?>
<tr>
<td>
<input type="hidden" id="subcategory<?php echo $i;?>" value="<?php echo $row['subcategory']; ?>">
<?php $subcategories[$i] = $row['subcategory']; ?>
<?php echo $row['subcategory']; ?>
</td>
<td>
<input id="slider<?php echo $i; ?>" type="text" class="slider" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="100" data-slider-tooltip="hide">
</td>
<td>
<span id="percentage<?php echo $i; ?>">100</span>%
</td>
<td>
<span id="rangesize<?php echo $i; ?>"><?php echo $row['rangesize']; ?></span>
</td>
<td><span id="dropskus<?php echo $i; ?>">0</span></td>
<td>
<input type="hidden" id="sales<?php echo $i; ?>" value="<?php echo $row['sales']; ?>">
<span id="keepsales<?php echo $i; ?>"><?php echo number_format($row['sales'], 2); ?></span>
</td>
<td><?php echo number_format($row['share'], 2); ?></td>
</tr>
<?php
$i++;
}
?>
</tbody>
</table>
<input type='hidden' id='rrsubcategories' value='<?php implode(",", $subcategories); ?>'>
</div>
It's really hard to determine the reason for the event fire twice from the question. My only suggestion, based on the attached screenshot, is to cancel the request when the slider is not related to any DOM element:
function updateNumbers(rowoffset){
var $el = $("#slider" + rowoffset);
if( $el.length == 0 ) {
return;
}
//get variables from DOM element values
var percentage = $el.val();
var group = $("#rrgroup").val();
var rrclass = $("#rrclass").val();
var category = $("#rrcategory").val();
var subcategory = $("#subcategory" + rowoffset).val();
..... rest of the function
}
Related
I'm currently building a form, and using a PHP loop to build the elements in a table which hold the values I'm submitting after clicking a checkbox.
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td id="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td id="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td id="category">{{$list['CATEGORY']}}</td>
<td><input id="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
</form>
My issue is, I have an id on the checkbox and id's on the values so I can only get the console log when I click the very first checkbox and it only logs the very first item. How can I change this so that I can submit with any checkbox in the table and it's associated values?
$("#addToLineup").click(function (e) {
var productNumber = document.getElementById("productNumber").innerHTML = productNumber;
var detailColor = document.getElementById("detailColor").innerHTML = detailColor;
var category = document.getElementById("category").innerHTML = category;
updatedata.productNumber = productNumber;
updatedata.detailColor = detailColor;
updatedata.category = category;
$.ajax({
url: "/test/addToLineup",
data: updatedata,
_token: phpVariables.csrfToken,
type: "POST",
beforeSend: function () {
showLoading(element);
},
success: function (data) {
location.reload();
},
});
});
Here is the solution to your problem, you need to use classes instead of IDs.
#foreach($lists as $list)
<tr style="text-align:center;">
<td class="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td class="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td class="category">{{$list['CATEGORY']}}</td>
<td><input class="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
Now, in your JS section, you can fetch them by their class:
var productNumber = document.getElementsByClassName("productNumber").innerHTML = productNumber;
var detailColor = document.getElementsByClassName("detailColor").innerHTML = detailColor;
var category = document.getElementsByClassName("category").innerHTML = category;
Note: If you're applying CSS styles to those elements via their ID, you can change #productNumber to .productNumber in your CSS or you can leave the ID tag with the same name as your previous code.
In PHP code
<form id="saveLineup">
<?php $i=0; ?>
#foreach($lists as $list)
<?php $i+=1; ?>
<tr style="text-align:center;">
<td id="groupNumber<?php echo $i ?>">.
{{$list['product']}} - {{$list['product_NAME']}}
</td>
<td id="detailColor<?php echo $i ?>">.
{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}.
</td>
<td id="category<?php echo $i ?>">.
{{$list['CATEGORY']}}
</td>
<td>
<input id="addToLineup<?php echo $i ?>"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo
"checked='checked'"; ?>>
</td>
</tr>
#endforeach
<input id="listcount"> type="hidden" value="<?php echo $i; ?>" >
</form>
Js function
$("#addToLineup").click(function (e) {
for(var i=1 ; i <= parseInt(document.getElementById("listcount").value); i++) {
Console.log(document.getElementById("productNumber"+i).innerHTML);
Console.log(document.getElementById("detailColor"+i).innerHTML);
Console.log(document.getElementById("category"+i).innerHTML);
}
});
I am trying to use JavaScript to calculate total price for the tickets which are selected by using the checkbox. The result is should be shown in a alert window by clicking on the check button which invokes the JavaScript function. But when I click the button nothing happens. I don't even get any error message. I am a beginner so please if anyone can help me, I will be extremely thankful.
<?php foreach ($res as $row): ?>
<form action="book.php" method="get">
<tr><td><?php echo $row['RowNumber']; ?></td><td><?php echo $row['Price']; ?></td>
<td><input type="checkbox" type="hidden" name="myForm[<?php echo $row['RowNumber']; ?>][row]" id="row" value="<?php echo $row['RowNumber']; ?>"></input></td></tr>
<input type="hidden" name="myForm[<?php echo $row['RowNumber']; ?>][price]" id="price" value="<?php echo $row['Price']; ?>"></input>
</form>
<?php endforeach; ?>
</table>
<form action='book.php' method='get'>
Enter Email:<input type='text' name='name'></form>
<script>
function summary() {
var total = 0.0;
var seats = document.getElementById("row").value;
for(i = 1; i <= document.getElementById("row").value; i++) {
if(document.getElementId("row").checked) {
total = total + parseFloat(document.getElementById("price").innerHTML);
}
}
return total;
alert("Price of seats =" + total);
}
</script>
<input type="button" onclick="summary()" value="check">
<?php
You're returning before calling the alert, which means you never get to the alert itself. Remove the return total line.
This is a very common problem.All we have face atleast once.you should use Chrome istead of firefox or internet explorer.close your webpage and restart again.
return total should be after alertbox.
thankx.
You can try this sample
<form action="book.php" method="get">
<table>
<?php foreach ($res as $row): ?>
<tr data-rownumber="<?php echo $row['RowNumber']; ?>">
<td><?php echo $row['RowNumber']; ?></td>
<td><?php echo $row['Price']; ?></td>
<td>
<input type="checkbox" name="myForm[<?php echo $row['RowNumber']; ?>][row]" id="row-<?php echo $row['RowNumber']; ?>" value="<?php echo $row['RowNumber']; ?>" onclick="summary()" />
<input type="hidden" name="myForm[<?php echo $row['RowNumber']; ?>][price]" id="price-<?php echo $row['RowNumber']; ?>" value="<?php echo $row['Price']; ?>" />
</td>
</tr>
<?php endforeach; ?>
</table>
</form>
<form action='book.php' method='get'>
Enter Email:<input type='text' name='name'>
</form>
<script>
function summary() {
var total = 0.0;
var table = document.getElementById('items-table');
var rows = table.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var rowNumber = row.getAttribute('data-rownumber');
var isChecked = document.getElementById('row-' + rowNumber).checked;
if (isChecked) {
var price = parseFloat(document.getElementById('price-' + rowNumber).value);
total += price;
}
}
alert("Price of seats = " + total);
return total;
}
</script>
<input type="button" onclick="summary()" value="check">
When I click the checkbox, only the first row shows the text box.
Expected When I check the checkbox, the text box will show in that row.
When i click the submit button, it only inserts the data from the first row.
Example When I checked 3 boxes, it will insert the data from the first row 3 times.
How can I fix my code?
<script type="text/javascript">
function changeText(codeasset){
if(codeasset.checked){
document.getElementById('hotStuff').innerHTML = '<input type="text" id="hotStuff" style="width: 150px;" />';
}else {
document.getElementById('hotStuff').innerHTML='';
}}
</script>
<?php
$assets_supplier_query = mysql_query("SELECT * FROM supplier_assets WHERE status = '0' AND supplier_id = '$supplier_id'");
while ($get_supplier_asset = mysql_fetch_array($assets_supplier_query))
{
$asset_code = $get_supplier_asset['asset_code'];
$asset_qty = $get_supplier_asset['supply_quantity'];
$asset_query = mysql_query("SELECT * FROM ref_assetmodel WHERE modelID = '$asset_code' ");
$get_asset = mysql_fetch_array($asset_query);
$asset_model = $get_asset['assetModel'];
$specifications = $get_asset['specifications'];
$category_id = $get_asset['categoryID'];
$type_id = $get_asset['typeID'];
$category_query = mysql_query("SELECT * FROM ref_assetcategory WHERE categoryID = '$category_id' ORDER BY categoryID");
$get_category = mysql_fetch_array($category_query);
$category = $get_category['assetCategory'];
$type_query = mysql_query("SELECT * FROM ref_assettype WHERE typeID = '$type_id' ");
$get_type = mysql_fetch_array($type_query);
$type = $get_type['assetType'];
?>
<form action="../process/approve_supplies_process.php" method="post" name="supplier">
<td><input type="checkbox" id="codeasset" name="supply[]" onclick="changeText(this)" value="<?php echo $asset_code ?>"> </td>
<td name="supply[]"><?php echo $type; ?></td>
<td name="supply[]"><?php echo $asset_model; ?></td>
<td name="supply[]"><?php echo $asset_qty; ?></td>
<td name="supply[]" id="hotStuff" value="<?php echo $asset_code ?>"></td>
<?php
}
?>
<tr>
<td align="center"><input type="submit" class="edit_butt" name="action" value="Submit" onclick=""></td>
<input type="hidden" name="supplier_id" value="<?php echo $supplier_id; ?>">
</tr>
</form>
<?php
$asset_code = $_POST['asset_code'];
$categoryID = $_POST['category_id'];
$type_id = $_POST['type_id'];
$supplier_id = $_POST['supplier_id'];
date_default_timezone_set('Asia/Manila');
$inventoryDate= date("Y-m-d");
if(isset($_POST['supply'])){
foreach ($_POST['supply'] as $_value)
{
echo "Box #{$_value} was selected!\n";
mysql_query("INSERT INTO ref_inventory(inventoryDate, categoryID, typeID, modelID, serialNumber, qrCode, is_owned, supplier_id)
VALUES('$inventoryDate', '$categoryID', '$type_id', '$asset_code', '954', '', 1, '$supplier_id') ");
}
}
?>
With this code, the ajax html is loaded fine and the click event triggers but when I try to get the form parent of the clicked button it seems to fail. The output from the alert is 'undefined'. How can I get the form data?
$( "#offertable" ).load( "offer-get.php", function() {
//$('#loadingDiv').hide();
$("#offertable").on('click', '#submit', function(event){
alert($(this).parents('form:first').attr("action"));
//event.preventDefault(); // this will prevent from submitting the form
//$(this).prop('disabled',true);
var postData = $(this).parents('form:first').serialize();
var formURL = $(this).parents('form:first').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert("Offer updated successfully");
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("Failed to update offer");
}
});
return false;
});
} );
I've tried using the submit event on the form (which would give me form object that I can get the data from);
$("#offertable").on('submit', '#updateoffer', function(event){
But it never fires.
EDIT: Form returned from offer-get.php
<tr>
<form action="offer-update.php" id="updateoffer" name="updateoffer" method='post'>
<input type="hidden" name="pendingofferid" value="<?php echo $record['pendingofferid'] ?>">
<input type="hidden" name="offerid" value="<?php echo $record['offerid'] ?>">
<input type="hidden" name="oldpaused" value="<?php echo $record['paused'] ?>">
<input type="hidden" name="oldpayout" value="<?php echo $record['payout'] ?>">
<td><?php echo $record['offerid']; ?></td>
<td><img src="<?php echo $record['picture']; ?>" height="50" width="50"></td>
<td><?php echo $record['name']; ?></td>
<td><?php echo $record['trackinglink']; ?></td>
<td><?php echo $record['country']; ?></td>
<td><?php echo $record['device']; ?></td>
<td>
<?php if ($approved) : ?>
<input type="number" name="payout" min="0" step="0.01" value="<?php echo $record['payout']; ?>">
<?php else: echo $record['payout']; ?>
<?php endif; ?>
</td>
<td>
<?php if ($approved) : ?>
<select name="status" class="form-control required" >
<option value="Live" <?php if(!$paused) echo 'selected="selected"'; ?> >Live</option>
<option value="Paused" <?php if($paused) echo 'selected="selected"'; ?> >Paused</option>
</select>
<?php else: echo 'Pending'; ?>
<?php endif; ?>
</td>
<td>
<?php if ($approved) : ?>
<button type='submit' name='submit' id='submit' class='btn btn-userid'>Update</button>
<?php endif; ?>
</td>
</form>
</tr>
Obviously this is not the whole code, don't want to release clients sensitive information but this should be enough. This part is looped for each result from the DB query. So there are multiple forms with same ids. If I use different ids for each form, I'm not sure how I'd get the event to fire otherwise since the number of rows isn't known until the data is returned.
I have this table i've built with jquery and ajax (watching some tutorials, so i'm not an advanced programmer). Well, what i do is i insert some values in a table and i need to get all the sum of this values in an input form.
I can do that, but what i need is to get the sum without refreshing the page, so anytime i enter:
200 in the Value column, the Sum should become :
Sum + 200
Please i need some help with what to do, i've searched for datagrid, but sincerely i don't know how can i do it.
Thanks
Php code of the input :
<table class="vlera">
<tr id="<?php echo $id; ?>" class="edit_tr">
<td class="edit_td">
<span id="first_<?php echo $id; ?>" class="text"><?php echo $kodi; ?></span>
<input type="text" value="<?php echo $kodi; ?>" class="editbox" id="first_input_<?php echo $id; ?>" />
</td>
<td class="edit_td">
<span id="last1_<?php echo $id; ?>" class="text"><?php echo $pershkrimi_pjeses; ?></span>
<input type="text" value="<?php echo $pershkrimi_pjeses; ?>" class="editbox" id="last_input1_<?php echo $id; ?>"/>
</td>
<td class="edit_td">
<span id="last_<?php echo $id; ?>" class="text"><?php echo $vlera; ?></span>
<input type="text" value="<?php echo $vlera; ?>" class="editbox" id="last_input_<?php echo $id; ?>"/>
</td>
<td class="edit_td">
<span id="last2_<?php echo $id; ?>" class="text"><?php echo $kosto; ?></span>
<input type="text" value="<?php echo $kosto; ?>" class="editbox" id="last_input2_<?php echo $id; ?>"/>
</td>
</tr>
<?php
}
?>
</table>
<?php
$sql_shuma="SELECT SUM(vlera) AS shuma FROM servis_pjeset_perdorura WHERE random=$random";
$resultshuma = odbc_exec($connection, $sql_shuma) or die(odbc_error());
while( $rowshuma = odbc_fetch_array($resultshuma ) ) {
$total1 = $rowshuma['shuma'];
}
?>
<label for='shuma'>Shuma:</label>
<input id="shuma" name="shuma" type="text" value=" <?php echo $total1;?>" size="20" />
the code you posted doesn't really show the full format (what the inputs look like)... but if you do something like:
$(".values").keyup(function() {
var sum = 0;
$(".values").each(function(){
sum += Number($(this).val());
});
$("#shuma").val(sum)
});
and each of your text inputs you want to go towards the total sum has a class of "values" on it, it should work. http://jsfiddle.net/NNbtk/
try this code... This code get the value of the text box when value enter and add it to the sum.
$(document).ready(function(){
$('#shuma').keyup(function(){
var val=$('#shuma').val();
sum=sum+val;
});
});
just put this code inside another php file...say abc.php
<?php
$sql_shuma="SELECT SUM(vlera) AS shuma FROM servis_pjeset_perdorura WHERE random=$random";
$resultshuma = odbc_exec($connection, $sql_shuma) or die(odbc_error());
while( $rowshuma = odbc_fetch_array($resultshuma ) ) {
$total1 = $rowshuma['shuma'];
}
echo $total1;
?>
Then from the main page do the following call on a button lets say button1
$(document).ready({
setInterval(function(){
$.ajax({
url: 'abc.php',
type: "POST",
success: function(contents){
$('#shuma').val(contents);
}
});
}, 1000);
});
Now the explanation:
In the main page when document gets ready, setInterval method of javascript will be called which takes 2 parameters, code and delay time in ms. this code will call the abc.php after every 1 sec and check the db for the new value and return it and put it in the field.
Hope that was what you were looking for.