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.
;)
Related
firstly, let me express that I have tried four methods (All slightly different) that all seem to produce the same issue, which is no data being outputted, even simple echo 'test' to rule out a DB issue (and also trying TEST in html on the called page, no result.
Here is a snapshot of the HTML and Javascript:
(document).on('change','category_id',function(){
var id = $(this).val();
$.ajax({
method: 'POST',
url: 'supportgetsubcats.php',
data: {'subcatid' : id},
success: function(data){
$('#subcatresponse').hide().html(data).fadeIn(); // update the DIV
}
});
});
<div class="form-group">
<label class="col-sm-2 control-label">Category *</label>
<div class="col-sm-4">
<select class="form-control" class="category_id" name="category_id" id="category_id">
<option value="" selected="selected">-- Select --</option>
<?php
$query="select * from support_categories where hide = '0' or hide is NULL order by name ASC";
$rs=sqlsrv_query($conn,$query);
while($row=sqlsrv_fetch_array($rs))
{
extract($row);
?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php
}
?>
</select>
</div>
</div><!-- form-group -->
<div class="form-group">
<div id="subcatresponse" name="subcatresponse" class="col-sm-4">
</div>
</div><!-- form-group -->
Here is the PHP that is called:
<?php require_once("includes/header.php");
error_reporting(E_ALL);
echo 'TEST';
if(isset($_POST["subcatid"])){
// Capture selected country
$category = $_POST["subcatid"];
$query="select * from support_subcategories where parent_category = '" . $category . "' order by name ASC";
$rsp=sqlsrv_query($conn,$query);
$subCatArr = array();
while($row=sqlsrv_fetch_array($rsp))
{
$subcat = $row['name'];
array_push($subCatArr, $category, $subcat);
}
// Display city dropdown based on country name
if($category == '-- Select --'){
} else {
echo '<label class="col-sm-2 control-label">Sub Category</label>';
echo '<select class="form-control" name="subcategory_id" id="subcategory_id">';
foreach($subCatArr[$category] as $value){
echo '<option value="'. $value .'">'. $value .'</option>';
}
echo "</select>";
}
}
?>
I get no response, not even basic text back, so I am not entirely sure what is wrong with the AJAX call, jQuery is included and proven to be working as the menu system on this interface won't display without jQuery so I am confident that is not the issue.
It looks like for whatever reason, the data from the HTML Select is not being passed to the AJAX call for POST.
Any thoughts greatly appreciated, TIA.
Try changing
(document).on('change', 'category_id', function() {
to
$(document).on('change', '#category_id', function() {
The second parameter to the on call takes a selector, but you seem to be passing in the name of the element instead. The name of the element is used when trying to access the element in PHP, and you use the selector (id, class, element) in JavaScript.
Alternatively, you could also use
$('#category_id').on('change', function()
You haven't posted it in your question, but in case you don't have it, it is always a good idea to only execute your jQuery code after the page has finished loading, otherwise your code may be trying to access an element that hasn't been loaded yet.
Surround your jQuery code with
$(document).ready(function() {
// Run jQuery code
}
add type='POST' to your ajax call
Also change this
(document).on('change','category_id',function(){
to
$(document).on('change','category_id',function(){
I tried following code in which I am trying to change paragraph tag to input fields through jquery on button click. I want my values to retain in the textbox when I click the button. Unfortunately, it isn't working! Here I have tried it with just name field. Any suggestions please.
code
<div id="menu2" class="tab-pane fade">
<h3>Address Book</h3>
<p>Default delivery address</p>
<?php
$em=$_SESSION['login_email'];
$query = mysqli_query($con,"SELECT * FROM customers where email='$em'" );
while($row=mysqli_fetch_assoc($query)){
?>
<h5>Name:</h5><p class="name" id="name"><?= $row['name'] ?></p>
<h5>Email:</h5><p class="mail"><?= $row['email'] ?></p>
<h5>Telephone:</h5><p class="tele"><?= $row['phone'] ?></p>
<h5>Address:</h5><p class="addres"><?= $row['address'] ?></p>
<h5>City:</h5><p class="city"><?= $row['city'] ?></p>
<?php
}
?>
<input type="button" id="update" value="Update Address" >
</div>
Jquery
<script src="js/jquery-1.6.2.js"></script>
<script>
$(document).ready(function() {
$('#update').click(function()
var input = $("<input>", { val: $(this).text(),type: "text" });
$('#name').replaceWith(input);
input.select();
});
});
</script>
Your code works, bar two errors. Firstly, you're missing a { after the click handler function definition. Secondly, this within the #update click handler refers to the button element, yet you're trying to read the val() of the #name input, so you need to change the selector. With that in mind, try this:
$('#update').click(function() {
var $name = $('#name');
var $input = $("<input>", {
val: $name.text(),
type: "text"
});
$name.replaceWith($input);
$input.select();
});
Working example
I would also be wary of having duplicated id attributes in your page as you are defining the elements in a loop. Should there be multiple rows returned from your query, then you will have multiple elements with the same id in the document which will lead to possible errors as the HTML will be invalid.
When I hit the select, 1 out of 10 times it will trigger the click function when I just click select. But, I want to trigger the click function when I click the select option. What did I do wrong, what should I do to trouble shoot this? By the way, this code is inside my ajax function.
$('#pagination select option').click(function(e){
alert('test');
$this = $(this).val();
window.location.hash = $this;
});
<div id="pagination">
<span href='prev' id='prev'>Prev</span>
<select >
<?php for( $i= 0 ; $i < $post_count ; $i++ ){
?>
<option value="<?php echo $i;?>" <?php if($i==$post_pagination_num){echo "selected=selected";};?>><?php echo $i+1;?></option>
<?php
}
?>
</select>
<span href='next' id='next'>Next</span>
Use change event
$('#pagination select').change(function(e){
JSFiddle demo
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>
I trying to put together a 5 day checklist app. The check list app has 5 divs that span across the page horizontally. Each div represents a day. Each div represents a day of the week and each div contains a hidden input field which holds a date value for for that particular day. Each div also has a check-list button and when the user clicks on that button the task list is removed and a form appears in its place to add a task. I'm trying to capture the value of the hidden input field, which is the date for that particular div. However, even though I'm using the "this" keyword, no matter which check-list button I click, I'm getting back the current date only. Which is the input value in the first div. How can I select the unique input value(the date) based upon which check-list button I click?
jquery:
$(".task-btn").click(function(){
// Setting form to the clone I want to acces in .on()
var refdate = $(this).closest('#replace').children('.hidden-date').val();
console.log(refdate);
});
html and php:
<?php
$date = date("F j, Y");
$refDate = date("Y-m-d");
$counterForLi = 0;
?>
<div id="replace">
<input type="hidden" name="thedate" class="hidden-date" value="<?php echo $refDate; ?>">
<h2 class="day"></h2>
<h4 class="thedate">
<?php
if ($counter > 0) {
$tomorrow = mktime(0, 0, 0, date("m"), date("d")+$counter, date("y"));
$refDate = date("Y-m-d", $tomorrow);
$date = date("F j, Y", $tomorrow);
echo $date;
} else {
echo $date;
}
?>
</h4>
<?php echo $refDate; ?>
<div class="btn-group">
<button class="btn task-btn">Add Task</button>
Note: I echoed out the date for each div and made sure there wasn't a problem with the php.
Although the answer to your question can be:
$(this).parents("#replace").find('.hidden-date').val();
Your problem is somewhere in another place because the snippet you shown should also work