JQuery not registering Button click - javascript

I have a page that displays a list of products. The user can select the quantity of a product to order and then click the order button. This should place a reference to the quantity and the product ID in a Cookie. However currently the button is not even being registered. When I click on it nothing happens.
If I place the button outside of the foreach loop then it works. Does anyone know what is going on?
Below is the code for the list of products
<?php if($products): ?>
<ul>
<?php foreach($products as $product): ?>
<h3 id="stock_code"><?= get_field('stock_code', $product->ID); ?></h3>
<p>Description: <?= get_field('description', $product->ID); ?></p>
<p>Quantity Per Pallet: <?= get_field('quantity_per_pallet', $product->ID); ?></p>
<!-- Quantity Dropdown -->
Amount <select id="order_amount<?= $product->ID; ?>" name="amt">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" value="Add to Order" id="orderBtn"/>
<?php endforeach; ?>
</ul>
<? endif ?>
This is the code to be executed when the button is clicked
$("#orderBtn").click(function(event){
//Show the order Box
$(".order-alert").show();
event.preventDefault();
//Create the Array
var productArray = [];
//If no Cookie exists, create one and add the Array
if ($.cookie('order_cookie') === undefined) {
console.log("Create a new cookie");
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
//If the Cookie already exists do this
} else {
console.log("Read the cookie");
productArray = JSON.parse($.cookie('order_cookie'));
console.log($.cookie('order_cookie'));
//Append items onto the Array
}
//Display the number of items in the Array in the Order Box
$('#order_counter').html(productArray.length);
});
I'd appreciate any help on the matter

Don't use ID on button. You have to use class if you want to assign event to multiply objects.
When you are using id selector jQuery assign event only to first object becouse ID sholud be unique.
Change:
$("#orderBtn").click(function(event){
..
}
To:
$(".orderBtn").click(function(event){
..
}
And HTML declaration:
<input type="submit" value="Add to Order" id="orderBtn"/>
To:
<input type="submit" value="Add to Order" class="orderBtn"/>

Related

Select from database in a multiselect and then insert as an array

I used this code to select classes for students from the database in a dropdown. It appeared correctly. Then I when I realized that I actually want to select more than one class for a student, I added multiple. It showed as a multiple but still inserts only one value in database table.
<?php
require_once('../config.php');
$class_result = $conn->query('select * from class');
?>
<label for="exampleFormControlTextarea1">Class</label>
<select class="form-control" name="class[]" id="class" multiple>
<option value=""></option>
<?php
if ($plot_type_result->num_rows > 0) {
// output data of each row
while ($row = $plot_type_result->fetch_assoc()) {
?>
<option value="<?php echo $row["class"]; ?>">
<?php echo $row["class"]; ?>
</option>
<?php
}
}
?>
</select>
Now I want this select class to be a multi select. If I add multiple it becomes a multiple but doesn't really inserts the multiple values I select. Only selects the last selected from the database and inserts it as a single one. How can I achieve multi select and actually pass it as an array to the database with more than one value?
$classDatas= implode(", ", $datas);
You can try to save the array in a single column by converting it to text with implote.

Textbox fill empty value every time while changing the db dropdown value

I have one dropdown box and one textbox. I want when I select the dropdown value then, it will fill the matching database textbox value automatically based on the database drop-down selection.
Here is my code:-
Dropdown and Textbox:-
<select name="product" required>
<option value=""></option>
<?php
while($productRow = mysqli_fetch_assoc($productResult)){?>
<option value="<?php echo $productRow['ID'];?>">
<?php echo $productRow['Category']; ?></option><?php } ?>
</select>
<input placeholder="Phone Number" name="phoneNumber" id="pnum" type="text">
Script :-
<script>
$(document).ready(function(){
$('select[name="product"]').change(function()
{
$('#pnum').val($('select[name="product"] option:selected').data('Mobile'));
}
);
});
</script>
Now textbox fills the empty value in every time when dropdown value change.
pls help a lot.
You need to change the html to
<select name="product[]" size=20 multiple required>
<?php
while($productRow = mysqli_fetch_assoc($productResult)){?>
<option value="<?php echo $productRow['ID'];?>">
<?php echo $productRow['Category']; ?></option><?php } ?>
</select>
Then remove the script because it is no longer required. All the selection of items is done in the <select> element.
On the server-side you will pickup the values in the product array.

how to pass selected option id value to codeigniter controller

i want to pass selected option value in id to codeigniter controller.
<p>
<select id="quantity" name="quantity" tabindex="2" onchange="calculate(this)" required autofocus>
<option value="">Choose Your Quantity</option>
<?php
if($prodqty)
{
foreach($prodqty as $qty)
{
for($i = $qty->quantity_from; $i <= $qty->quantity_to; $i++)
{
?>
<option value="<?=$i?>" id="<?=$qty->discount?>"><?=$i?></option>
<?php } } } ?>
</select>
</p>
i am already getter selected option value, now i want to get id value also i.e. id="discount?>"
function add_cart_prod()
{
if(isset($_POST['submit']))
{
this is controller where i want to get id value
Use ajax call on change event of the selection of the options:
Just Changed your code little :
<select id="quantity" name="quantity" tabindex="2" onchange="calculate(this)" required autofocus>
<option value="0">Choose Your Quantity</option>
<?php
if( !empty($prodqty)):
foreach($prodqty as $qty):
for($i = $qty->quantity_from; $i <= $qty->quantity_to; $i++): ?>
<option value="<?php echo $i?>" id="<?php echo $qty->discount?>"><?php echo $i?></option>
<?php endfor;
endforeach;
endif; ?>
</select>
Your javascript function :
<script type="text/javascript">
function calculate(id)
{
var id=id;
$.ajax({
type:'POST',
url:'your controller/add_cart_prod',
data:{'id':id},
success:function(data){
// the next thing you want to do
}
});
}
</script>
Your Controller Function:
function add_cart_prod()
{
$id=$this->input->post('id',true);
//send this value to your model
}
If you subitted the data via POST, which I suppose, because you test the POST-Array, you should get them this way:
$this->input->get_post('quantity');
But perhaps you used in your HTML the option GET for the form submission, then this should work:
$this->input->get('quantity');
If you want to get both values XSS-clean you should add a second paramenter, which is set to TRUE:
$this->input->get_post('quantity',TRUE);
As discussed below you should change the value of the option to:
<option value="<?=$i?>_<?=$qty->discount?>"><?=$i?></option>
And then explode the array by this char: "_" to get the two values:
$valuearray = explode ( "_" , $this->input->get_post('quantity'));
$valuearray[0] should contain your $i-part and $valuearray[1] the discount.
Important is, that the delimiter-char cannot be a value of either $i or $qty->discount. Otherwise choose a different char
You should try this, maybe it will work, Inside the calculate(this) function:
var discount = $("select[name='quantity'] option:selected").attr('id');
alert( discount );
$("#discount").val( discount ); //this will save the discount value in the hidden field
EDIT:
Put a hidden field in your form to contain the discount value
<input type="hidden" name="discount" id="discount">
Now, submit the form as usual. Hope it helps.

How to pass parameter as POST data on selection of an Select Box value, which will reload the same page?

I had two chained Select Boxes "pr_cat" and "sl_num" . The second select box values depend on the value selected in the first select box.
<tr>
<td width="257">Select Product Category:</td>
<td width="197">
<select name="pr_cat" id="Validprcat" onChange="reload(this.form)"><option value="">< Select one ></option>
<?php while($prd=mysql_fetch_object($select_query1)) {
if ($prd->cat_id==$pcat) { ?>
<option selected value="<?php echo $prd->cat_id?>"><?php echo $prd->category_name?> </option>
<?php } else { ?>
<option value="<?php echo $prd->cat_id?>"><?php echo $prd->category_name?></option>
<?php }}?>
</select>
</td>
</tr>
<tr>
<td>Select Serial Number:</td>
<td>
<select name="sl_num" id="Validslnum" onChange="reload2(this.form)"><option value="">< Select one ></option>
<?php while($slnum=mysql_fetch_object($quer)) {
if ($slnum->serialno==$pcat2) { ?>
<option selected value="<?php echo $slnum->serialno?>"><?php echo $slnum->serialno?> </option>
<?php } else {
?>
<option value="<?php echo $slnum->serialno?>"><?php echo $slnum->serialno?></option>
<?php }} ?>
</select>
</td>
</tr>
<tr>
I used the form reload javascript to reload the page with the value selected in the Select Box. I used GET method.
<script language=JavaScript>
function reload(form)
{
var val=form.pr_cat.options[form.pr_cat.options.selectedIndex].value;
self.location='delivery.php?pcat=' + val ;
}
function reload2(form)
{
var val=form.pr_cat.options[form.pr_cat.options.selectedIndex].value;
var val2=form.sl_num.options[form.sl_num.options.selectedIndex].value;
self.location='delivery.php?pcat=' + val + '&pcat2=' + val2 ;
}
</script>
But I want to do it using POST method how to do this ?
If you don't want to use ajax, and do it via POST method, so instead of
onChange="reload(this.form)"
call
onChange="formSubmit();"
<script>
function formSubmit()
{
document.getElementById("frm1").submit(); //frm1 is form id
//OR you can use
//document.frm1.submit(); //frm1 is form name
}
</script>
Note :- if you have any submit button in this form, don't keep it's name as submit, else you will have issues in your code.
I think what you're asking is pretty much this: JavaScript post request like a form submit
However, why do you want to reload the page at all instead of doing an AJAX call?
I give you the most simple and fastest way to do what you wanted,
AJAX:
cover both select box with '' tag,
<div id='first_select'>
<select id='first' onchange='populate_second_select(this.value)'>
<option>Select</option>
</select>
</div>
<div id='second_select'>
<select>
<option>Select</option>
</select>
</div>
call populate_second_select() function upon change done in first select box.
No in ajax,
function populate_second_select(value)
{
$.ajax({
method:'POST',
url:'ajax.php',
data: {value:value},
success:function(result)
{
document.getElementById("second_select").innerHTML=result;
showLightBox();
}
});
}
This is how your javascript function should look like,
on your ajax.php file, process the DB based on chosen value and 'echo' the whole select tag (second tag). That's it.
Here are few links would help you to get this done.
Link_1Link_2

how to trigger javascript when a dropdown option is selected

I have two dropdown boxes for car makes and models, when a make is selected i need all its models to show in the next box. As of now using the following code the models show up when the dropdown is clicked.
window.onmousedown = function(e){
this.id = e.target.id;
if(this.id == "vehicle_makes"){
var make = document.getElementById("vehicle_makes").value;
ajaxCall(make);
}
}
However i need the javascript to trigger when an option from the dropdown is selected rather than when the drop down is opened.
here also is the html - with some php
<div class="vehicle-search-wrap">
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>">
<div>
<select id="vehicle_makes" name="s">
<?php
foreach($makes as $make){ //put all makes in dropdown
echo "<option value='". $make ."'>". $make ."</option>";
}
?>
</select>
<select id="model_drop" name="vmodels">
<?php
//nothing to start
?>
</select>
<input type="submit" value="Search Vehicle" />
</div>
</form>
</div>
use the onchange event of selectbox.
here is a demo
Try this:
<select name="Pizza" size="5"
onchange="myFunctionHere()">
<option value="P101">Pizza Napoli</option>
<option value="P102">Pizza Roma</option>
</select>

Categories

Resources