I am working on an ecommerce site and the products are being dynamically generated with foreach loop, within each product there are product options, when the product option is selected I my intended behaviour is for the price to update.
I have this working, however jQuery is updating every instance of the price on the page and the select option only works for the first item generated. How do I add/bind the jQuery to the object/every product and have the price change on individual basis?
<?php
foreach($items as $item):
<?php echo $the_name ?>
<select id="choose">
foreach($selection as $select):
<option value="$some_var" data-value="$the_price">$some_var</option>
endforeach;
</select>
<div id="price"><?php echo $the_price ?></div>
endforeach;
?>
<script type="text/javascript">
jQuery('#choose').change(function (event) {
jQuery('#price').html(jQuery('#choose option:selected').data('value'));
}).change();
</script>
Working Code
After playing about for a while, and taking into consideration the other comments below, this code works.
<script type="text/javascript">
jQuery('.choose').change(function (event) {
var $t = jQuery(this);
var price = $t.find('option:selected').data('value');
$t.parents('form').find('.price').html(price);
}).change();
</script>
ID's are unique. Because 'choose' is in a loop, you've got multiple choose ID's, which isn't helping things. Same with the 'price'. So, let's change it a bit:
<?php
foreach($items as $item):
<?php echo $the_name ?>
<select class="choose">
foreach($selection as $select):
<option value="$some_var" data-value="$the_price">$some_var</option>
endforeach;
</select>
<div class="price"><?php echo $the_price ?></div>
endforeach;
?>
<script type="text/javascript">
jQuery('.choose').change(function (event) {
jQuery(this).next().html(jQuery(this).data('value'));
}).change();
</script>
Explanation:
Since you can have more than one choose, you then need to do a bit of DOM navigation to get the price that is relative to the select. So, whenever a select box is changed it will look for the next element in the DOM tree that is a sibling , which if your code snippet is complete will be the price element, and then update the html to that value. One thought though - you may want to use text instead of html, unless you have HTML in your prices. Also, when you're inside an event (unless you've done something special to rebind the scope), in jQuery this will refer to the element that the event fired on. So, jQuery(this) will return a jQuery reference to the element that was changed.
<?php
foreach($items as $item):
<?php echo $the_name ?>
<select class="choose">
foreach($selection as $select):
<option value="$some_var" data-value="$the_price">$some_var</option>
endforeach;
</select>
<div class="price"><?php echo $the_price ?></div>
endforeach;
?>
<script type="text/javascript">
jQuery('.choose').change(function (event) {
jQuery$(this).parent().next(".price").html(jQuery('#choose option:selected').data('value'));
}).change();
</script>
Related
I have an odd problem with my jQuery. I have an element that I want to toggleTo once a dropdown option has been selected. The odd thing is that it only triggers AFTER the first time it has been changed. It will not scroll to the right element on the first change, but subsequent changes after that!
Why is it ignoring the first one? Maybe I selected the wrong event attribute? I have tried other ones such as mouseleave() with no luck. I feel like I have used the right attribute because I want it to scroll when the user selects or changes the dropdown value.
Any help would be appreciated.
Please find my code attached below:
home.php
//SCROLL TO TRANSFER GUIDE ON click
$("#major").on('change',function() {
$('html, body').animate({
scrollTop: $("#scrollHere").offset().top
}, 1000);
});
major.php
<?php
session_start();
require 'db_connect_clearmaze.php';
?>
<body>
<h3 align="center" class="header whitetext">Choose Your Major</h3>
<?php
$uni = trim($_GET['uni']);
$_SESSION['uni'] = $uni;
$cc = $_SESSION['cc'];
?>
<form align="center">
<select id = "major" class="dropbtn" onmouseover="DropListMajor()"
onmouseout="this.size=1;" onchange="loadTransferGuide(this.value,'<?php echo $uni; ?>','<?php echo $cc; ?>')">
<?php
echo '<option value=""> Select Your Major </option>';
$query = $db -> query("SELECT major FROM majors WHERE university = '".$uni."';");
while($row = $query -> fetch()){
echo '<option value = "'.$row['major'].'">' ?>
<?php echo $row['major'].'<br>' ?> <?php '</option>';
}
?>
</select>
</form>
</body>
This change event handler $("#major").on('change',function(){...} was defined inside another change handler...
So on 1st change, the first inline handler defined the second handler.
That is why it was not firing on the first change.
I guessed it because it was fitting the behavior described...
but also because of this comment //SCROLL TO TRANSFER GUIDE ON click.
;)
I have two tables in my database:
Table 1: Country => countryid(primary),countryname and
Table 2: State => stateid(primary),countryid(foreign),state
Now I want to make a drop down list. For example:
Country India (dropdown 1) should show States Goa, UP and MP (dropdown 2)
Country Pakistan (dropdown 1) should show States Lahore and Karachi (dropdown 2)
I have populated both tables with these values.
Here I am including my code files. I am able to get the first menu working but no values in the second menu. I want the second menu to change instantly when the value selected in the first menu is changed (not just when the page is loaded).
index.php
<?php
include('config.php');
$query_parent = mysql_query("SELECT * FROM country") or die("Query failed: ".mysql_error());
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#countryname").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?countryid=' + $(this).val(), function(data) {
$("#stateid").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
</script>
</head>
<body>
<form method="get">
<label for="category">Parent Category</label>
<select name="countryname" id="countryname">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['countryid']; ?>"><?php echo $row['countryname']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label>Sub Category</label>
<select name="state" id="stateid"></select>
</form>
</body>
</html>
config.php
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('login');
?>
loadsubcat.php
<?php
include('config.php');
$countryid = $_GET['countryid'];
$query = mysql_query("SELECT * FROM state WHERE countryid = {$countryid}");
while($row = mysql_fetch_array($query)) {
echo "<option value='$row['stateid']'>$row['state']</option>";
}
?>
I am not able to figure out my problem. Also I have not done PHP before. This is the first time I am learning and that too with this project, so forgive me if I made disastrous mistakes.
Here you are sending the country id with key name countryname:
$.get('loadsubcat.php?countryname=' + $(this).val(), function(data) {
But on your PHP file, you are trying to get the value by using countryid:
$countryid = $_GET['countryid'];
Change and make it same for both. It will work!
UPDATE:
$("#state").html(data);
Here you are referring state but on your HTML, you are using stateid.
<select name="state" id="stateid"></select>
What Muhammad Sumon Molla Selim said is correct and there is one more mistake in loadsubcat.php
you need to change, echoing options statement
From:
echo "<option value='$row['stateid']'>$row['state']</option>";
To:
echo "<option value=".$row['stateid'].">".$row['statename']."</option>";
Then second dropdown will get states based on change in coutries dropdown.
when I excecuted your code in my local machine I was not getting data. The mistake you did was you are not concatinating the strings and variables properly.
I have problem how to put seach box inside in a dropbox, I had already a code using some javascript but It didn't work can you please help me about it?
Here's my code
<script type="text/javascript">
$(document).ready(function() {
$(".js-example-basic-single").select2();
});
</script>
here's my select tag codes:
<?php
$sql = mysql_query("SELECT * FROM barangay");
?>
<select class="js-example-basic-single" name="barangay_ID" style='width:160px;height:38px;border-radius:8px;border-color:#D7D7D7;margin-left:55px;' autofocus required>
<option disabled selected hidden>← Please select →</option>
<?php
while ($row = mysql_fetch_array($sql)){
echo "<option value='".$row['barangay_ID']."'>".$row['barangay_name']."</option>";
}
echo "</select>";
?>
Don't know why it doesn't work please help mean example
I am developing a list of submissions in the admin area of my website, which I can approve/disprove with a form, with an ID of the submission in a hidden input, and the select box with Approve/Reject in. When the select box is changed, the ajax submits the form, along with the hidden ID input, then the PHP script edits the submission in the database.
It was all working fine with one submission (1 form) on the page, but now there is more than one form, it is POSTing the wrong values to the PHP script.
<tbody>
<?php
// connect to mysql
mysql_connect('#######', '#######', '#######');
mysql_select_db('jcvideos');
// query
$query = mysql_query("SELECT * FROM videos");
// loop thru
while($row = mysql_fetch_assoc($query)) {
?>
<tr<?php if($row['accepted']==0) {echo " class='warning'";}?>>
<td><?php echo $row['id'];?></td>
<td>
<a href="//youtu.be/<?php echo $row['ytid'];?>" target="_blank">
<?php
$url = "http://gdata.youtube.com/feeds/api/videos/". $row['ytid'];
$doc = new DOMDocument;
$doc->load($url);
echo $doc->getElementsByTagName("title")->item(0)->nodeValue;
?>
</a>
</td>
<td><?php echo $row['date'];?></td>
<td>
<a href="mailto:<?php echo $row['submitter'];?>">
<?php echo $row['submitter'];?>
</a>
</td>
<td>
<form id="form<?php echo $row['id'];?>" class="reviewform" method="post" action="review.php">
<input type="hidden" value="<?php echo $row['id'];?>" name="vidid">
<select name="status">
<option value="0"<?php if($row['accepted']==0) {echo ' selected';}?>>Pending review</option>
<option value="1"<?php if($row['accepted']==1) {echo ' selected';}?>>Rejected</option>
<option value="2"<?php if($row['accepted']==2) {echo ' selected';}?>>Accepted</option>
</select>
</form>
</td>
<td><?php echo $row['showdate'];?></td>
</tr>
<?php
} // end of loop
?>
</tbody>
</table>
<?php include('../includes/footer.php');?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$("select").change(function(){
$('.reviewform').ajaxSubmit();
});
</script>
I tried using IDs, then it didn't POST at all. What am I missing here?
You can try this assign common class like i have assigned in fiddle (status) to selectbox then get the form by the change of its children (<select>) like in fiddle i tried to get the id of from by change event of its child element (<select>) ,once you got the id get the data of form and submit it
$('.status').on('change', function(){
var id=$(this).parent("form").attr('id');
alert(id)
$('#'+id).ajaxSubmit();
/* $("#"+id).serialize() form data */
});
See Fiddle
It depends on your event listener/selector:
$("select").change(function(){
$('.reviewform').ajaxSubmit();
});
This will always submit .reviewform even if a select of anoter form has been changed.
(Basicly it registers the function for the change event of all select tags in you page)
Please try:
$(".reviewform select").change(function(){
$('.reviewform').ajaxSubmit();
});
$(".anotherform select").change(function(){
$('.anotherform').ajaxSubmit();
});
I have the following Drop Down List in php:
<select id="choice" name="choice" style="width: 121px">
<?php
foreach($xml->children() as $pizza){
?>
<option value="<?php echo $pizza; ?>" selected=""><?php echo $pizza; ?></option>
<?php }?>
</select><input TYPE = "button" id="addbt" Name = "addbt" VALUE = "Add Pizza">
and I am using the following Jquery:
<script type="text/javascript">
$("#addbt").click(function () {
$('#choice').clone().insertAfter("#choice");
});
</script>
I am trying to clone the Drop Down List which is attached to an xml file (I managed till here) and add the Jquery necessary so each new drop down list clone has a new id (a single number difference would be enough. Something like choices_00 then choices_01 and so on).
Since I am totally new to Jquery and php I am asking for any advice or help.
$("#addbt").click(function () {
$('#choice').clone()
.attr('id', 'newid')
.attr('name', 'newname')
.insertAfter("#choice");
});
To ensure you get a new name and id each time, consider adding a class name to the select so you can count how many exist.
HTML:
<select id="choice" name="choice" class="ddl" style="width: 121px">
<?php
foreach($xml->children() as $pizza){
?>
<option value="<?php echo $pizza; ?>" selected=""><?php echo $pizza; ?></option>
<?php }?>
</select>
JS:
$("#addbt").click(function () {
$('#choice').clone()
.attr('id', 'choice' + $('.ddl').length)
.attr('name', 'choice' + $('.ddl').length)
.insertAfter(".ddl:last");
});
Otherwise, track how many times the button has been clicked with a global variable (ugh) or data attribute.
I think you are after this: http://jsfiddle.net/ehQan/
$("#addbt").click(function () {
$('#choice').clone().attr( 'id', 'choices_' +$(this).index()).insertAfter("#choice");
});
You can change the id using the jQuery attr() method before you insert it:
<script type="text/javascript">
$("#addbt").click(function () {
$('#choice').clone().attr('id','Your new id').insertAfter("#choice");
});
</script>
With this code you can push the button as many times as you want:
<script type="text/javascript">
var times = 0;
$("#addbt").click(function () {
times++;
$('#choice').clone().attr( 'id', 'choices_' + times ).insertAfter("#choice");
});
</script>