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);
}
});
Related
I'm asking this question again and hope I get the answer this time, I have an array of number that adds and subtract on button click which works withonclick and a function created. I will like the sum up of the array 21998 and 11999 when this same button is click and will like to display the value in <p id=""sumTotal></p> find screenshot of what my array looks like:
I have an onClick function that multiple quantity with total every time - and + are clicked. I will like the sum-up of 21,998 and 11,999 when - and + are clicked. Below is what my HTML code and PHP script look like:
<p id = "sumTotal"></p>
<table class="table table-cart table-mobile">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
<tr>
<td class="price-col" id="<? echo $_SESSION['id'][$i].'_price' ?>" >₦<?php echo $_SESSION['price'][$i] ?></td>
<td>
<div onclick="clickMe(<?php echo $_SESSION['id'][$i]; ?>)">
<input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
</div><!-- End .cart-product-quantity -->
</td>
<td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">₦<?php echo $_SESSION['price'][$i] ?></td>
</tr>
<?
}
?>
<tbody>
</table>
And my javascript onclick looks like below code:
<script>
function clickMe(id) {
var price = document.getElementById(id+"_price").innerHTML;
let finalPrice = price.replace(/[^a-zA-Z0-9]/g, '')
var quantity = document.getElementById(id+"_quantityCount").value;
var totalPrice = quantity * finalPrice;
document.getElementById(id+"_totalPrice").innerHTML = "\u20A6"+totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
I will like to get the sum total of 21,998 and 11,999to <p id = "sumTotal"></p>
Call this function in the end of clickMe function.
function total() {
const priceElements = document.querySelectorAll('[id$="_totalPrice"]');
return [...priceElements].reduce((acc, curr) => acc + +curr.innerText, 0);
}
I was able to solve this myself, at first on the load of the page I sum up the all prices to get my initial sumTotal and did that in PHP with $subTotal_sum = array_sum( str_replace(",", "", $_SESSION['price']));. So <p id = "sumTotal"></p> will be <p id = "sumTotal">echo array_sum( str_replace(",", "", $_SESSION['price']));</p> And inside my javascript I made the changes with the script, I get the value of sumTotal subtracted it from Price and add the sumTotal and new price after + or - to get the new sumTotal below is my update code:
<p id = "sumTotal">$subTotal_sum = array_sum( str_replace(",", "", $_SESSION['price']));</p>
<table class="table table-cart table-mobile">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
<tr>
<td class="price-col" id="<? echo $_SESSION['id'][$i].'_price' ?>" >₦<?php echo $_SESSION['price'][$i] ?></td>
<td>
<div onclick="clickMe(<?php echo $_SESSION['id'][$i]; ?>)">
<input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
</div><!-- End .cart-product-quantity -->
</td>
<td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">₦<?php echo $_SESSION['price'][$i] ?></td>
</tr>
<?
}
?>
<tbody>
</table>
<script>
function clickMe(id) {
var sumTotal = document.getElementById("sumTotal").value;
var price = document.getElementById(id+"_price").innerHTML;
var initialSumTotal = parseInt(sumTotal) - parseInt(price);
let finalPrice = price.replace(/[^a-zA-Z0-9]/g, '')
var quantity = document.getElementById(id+"_quantityCount").value;
var totalPrice = quantity * finalPrice;
document.getElementById(id+"_totalPrice").innerHTML = "\u20A6"+totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var sumTotal= parseInt(initialSumTotal)+parseInt(totalPrice);
// parsing the value to display on sub total
document.getElementById("sumTotal").value ="\u20A6"+sumTotal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
So I have a database of vehicles and I made a form where a user can update the information of vehicles and then confirming if he/she wants to save the changes. Problem is I feel like I am still not understanding how AJAX works and here's what Iv done so far.
This is the form the users use to edit a vehicles information.
<html>
<body>
<table align = 'center' cellspacing='2'>
<tr>
<th> Enter Vehicle Information </th>
</tr>
<form enctype = 'multipart/form-data' method = 'post' action = '' >
<?php
if($v = $Vehicle->fetch())
{
?>
<input type = "hidden" id='vID' value = '<?php echo $v['Vehicle_N'];?>'/>
<img src = "Vehicles/<?php echo $v['Image']?>" height = 100 width = 100 > </img>
<tr>
<td>Vehicle Manufacturer
<select id = "Manufacturer" value = '<?php echo $v['Manufacturer'];?>'>
<?php
foreach($Manu as $m)
{?>
<option value = '<?php echo $m['Manufacturer'] ?>'> <?php echo $m['Manufacturer'] ?></option>
<?php
}
?>
<option> <a href='test.php'> + Add New</a></option>
</select>
</td>
</tr>
<tr>
<td>Vehicle Model <input id = "Model" value = '<?php echo $v['Model'];?>'/> </td>
</tr>
<tr>
<td> Model Year <input type = 'number' id = "modelYear" min='1990' max='2020' value = '<?php echo $v['Model_Year'];?>'/> </td>
</tr>
<tr>
<td> State of Vehicle <input id = "State" value = '<?php echo $v['State'];?>'/> </td>
</tr>
<tr>
<td> Color <input id = "Color" value = '<?php echo $v['Color'];?>'/> </td>
</tr>
<tr>
<td>
Vehicle Type
<select id = "Type" value = '<?php echo $v['Type'];?>'>
<?php
foreach($vehicleTypes as $vt)
{?>
<option value = '<?php echo $vt ?>'> <?php echo $vt ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td> License plate No. (If there is one) <input type = 'number' id = "licensePlate" value = '<?php echo $v['License_Plate_N'];?>' /> </td>
</tr>
<tr>
<td> Sale Price <input type = 'number' id = "salePrice" value = '<?php echo $v['Sale_Price'];?>'/> </td>
</tr>
<tr>
<td> Rent Price <input type = 'number' id = "rentPrice" value = '<?php echo $v['Rent_Price'];?>'/> </td>
</tr>
<tr>
<td> Stock <input type = 'number' id = "Stock" value = '<?php echo $v['Stock'];?>' /> </td>
</tr>
<tr>
<td><p>Vehicle Description<textarea id="Description" rows="2" cols="18" > <?php echo $v['Description'];?> </textarea></p> </td>
</tr>
<tr>
<td>Vehicle Image <input id = "i" type = 'file' /> </td>
</tr>
<tr>
<td> Update </td>
</tr>
<?php
}
?>
</form>
</table>
<script>
function confirm_edit(){
if(confirm("Save changes?") === true){
var vehicleID = document.getElementById("vID");
var Manufacturer = document.getElementById("Manufacturer");
var Model = document.getElementById("Model");
var modelYear = document.getElementById("modelYear");
var State = document.getElementById("State");
var Color = document.getElementById("Color");
var Type = document.getElementById("Type");
var salePrice = document.getElementById("salePrice");
var rentPrice = document.getElementById("rentPrice");
var Stock = document.getElementById("Stock");
var i = document.getElementById("i");
var Description = document.getElementById("Description");
$.ajax({
url: 'ajax.php',
method: 'post',
data: {vehicleID : vehicleID, Manufacturer : Manufacturer},
success: function(response){
console.log(response);
}
});
}else{
return false;
}
}
</script>
This is just some code I wrote to test if it is working before I try updating the table in my database, but it is not printing the variable so I am assuming it is not working.
<?php
extract($_POST);
if(isset($Manufacturer))
{
echo $Manufacturer;
}
?>
If someone can show me my mistakes because I am still having trouble with AJAX because I am new to it. I want the user to confirm if he/she wants to save the changes then through AJAX update the table on my database.
You over-complicated your code and therefore it makes it much harder to understand and handle.
First of all, instead of declaring every form input by finding it's ID, you should just user jQuery's built in serialize() function, which will collect all of the form data and make a simpler string to work with.
$.ajax({
data: $('form').serialize(),
success: function(data){
console.log(data);
}
});
Also, do not use extract on user data (like $_POST or $_GET) since it is extremely insecure way to handle user data. Simply use:
<?php
if(isset($_POST['manufacturer']))
{
echo $manufacturer;
}
?>
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
}
I am trying to make a simple validation in javascript for a foreach in php, but I don't know how to parse each row from view
<table>
<?php $i=1; ?>
<?php foreach($questions $row):
?>
<tr><td colspan="2"><?php echo $i++; ?><?php echo $row->question;?></td></tr>
<tr><td colspan="2"><?php echo $row->category;?></td></tr>
<tr><td colspan="2"><?php echo $row->id;?></td></tr>
<tr>
<td><input type="checkbox" id="r" value="<?php echo $row->var_1;?>"></td>
<td class="answer"><?php echo $row->var_a;?></td>
</tr><tr>
<td><input type="checkbox" id="r" value="<?php echo $row->var_2;?>"></td>
<td class="answer"><?php echo $row->var_b;?></td>
</tr><tr>
<td><input type="checkbox" id="r" value="<?php echo $row->var_3;?>"></td>
<td class="answer"><?php echo $row->var_c;?></td?
</tr>
<?php endforeach; ?>
</table>
<button type="button" id="submit">Send</button>
And in javascript I try to check every answer for each question .
<script>
$("#submit").on("click", function(){
var x=0;
if(document.getElementById("r").checked == true document.getElementById("r").value == 1){
x=x+1;
}
});
</script>
Each answer has value 1 or 0, and it can be multiple choice.
IDs need to be Unique - use class or name instead
if you have jQuery USE jQuery
$("#submit").on("click", function(e){
var x=$(".r:checked").length; // using class="r"
if (x < $(".r").length) {
alert("Please check all checkboxes");
e.preventDefault();
}
});
or using name="r"
$("#submit").on("click", function(e){
var x=$('input[name="r"]:checked').length;
if (x < $('input[name="r"]').length) {
alert("Please check all checkboxes");
e.preventDefault();
}
});
I'm getting some problems trying to set order number if sequence of checkbox checked with javascript:
<?php
for ($x=0; $x<count($UnidadesServicio); $x++){
$idunidadserv = $UnidadesServicio[$x]['idunidadserv'];
$unidadserv = utf8_encode($UnidadesServicio[$x]['lugarunidad']);
$desunidad = utf8_encode($UnidadesServicio[$x]['desunidad']);
?>
<tr>
<td width="10%"><input type="checkbox" id="cbx_<?php echo $idunidadserv;?>" name="chk_unidadserv" value="<?php echo $idunidadserv;?>" onClick="AgregarUnidadServ()" /></td>
<td width="56%" height="28"> <?php echo $unidadserv;?> </td>
<td width="13%"> </td>
<td width="21%" align="center"> <input name="txt_orden_<?php echo $x;?>" type="text" id="txt_orden_<?php echo $idunidadserv;?>" value="" size="2" maxlength="1" class="txtorden" /> </td>
</tr>
<?php
}
?>
My JavaScript function:
<script>
function AgregarUnidadServ(){
var group = document.getElementsByName('chk_unidadserv');
var i;
for (i=0; i<group.length; i++){
if (group[i].checked == true){
var id = parseFloat(i+1);
$("#txt_orden_"+id).val(i);
}
}
}
</script>
What i need to to do:
When check any checkbox, set in input text the sequence number (1, 2, 3, etc.)
That code, display like this:
Greetings.
$("#txt_orden_"+id).val(id);
And sequence will start from 1.