I want to know if the line below is needed in this script, and if so, what purpose it serves.
$("#quantity-0").focus();
If I do not have a form field with id "quantity-0" what other elements could I focus (if required)? Can I focus a hidden form element?
Here's my code. It comes from this blog.
<script type="text/javascript" charset="utf-8">
//<![CDATA[
// Including jQuery conditionnally.
if (typeof jQuery === 'undefined') {
document.write({{ "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" | script_tag | json }});
document.write('<script type="text/javascript">jQuery.noConflict();<\/script>');
}
//]]>
</script>
<script>
$(document).ready(function () {
$("#quantity-0").focus();
var length = $("#linklist-length").val();
$("#submit-table").click(function(e) {
e.preventDefault();
//array for Variant Titles
var toAdd = new Array();
var qty;
for(i=0; i < length; i++){
toAdd.push({
variant_id: $("#variant-"+i).val(),
quantity_id: $("#quantity-"+i).val() || 0
});
}
function moveAlong(){
if (toAdd.length) {
var request = toAdd.shift();
var tempId= request.variant_id;
var tempQty = request.quantity_id;
var params = {
type: 'POST',
url: '/cart/add.js',
data: 'quantity='+tempQty+'&id='+tempId,
dataType: 'json',
success: function(line_item) {
//console.log("success!");
moveAlong();
},
error: function() {
//console.log("fail");
moveAlong();
}
};
$.ajax(params);
}
else {
document.location.href = '/cart';
}
};
moveAlong();
});
});
</script>
I want to know if the line below is needed in this script, and if so, what purpose it serves.
Calling the jQuery .focus() method with no arguments sets focus to the specified element. That line is the first line inside the document ready handler. So its purpose is to set focus to that particular field when the page first opens/loads.
As to whether it is needed, that's really up to the page designer. Setting focus to the field the user will most likely want to interact with first is generally helpful to them. If you didn't have that it wouldn't stop the page from working or anything.
If I do not have a form field with id "quantity-0" what other elements could I focus (if required)?
You can set focus to whatever element you like. Normally this would be either a form element of some kind (input, button, etc.) or a hyperlink. Whichever one makes most sense for a user to interact with first upon page load.
Can I focus a hidden form element?
Why would you want to do that? It doesn't make sense for a user to interact with a hidden element. I believe attempting to set focus to a hidden element may give an error in some browsers.
Related
this is my server-side code:
modify_emp.php
<?php
echo $_POST[id];
?>
And this is my Javascript in my html page:
<script>
$(document).ready(function () {
var alreadyClicked = false;
$('.element').hover(
//mouseenter function
function(){
$('.element').click(
function(){
$(this).css("color","blue");
var objName = $(this).attr('name');
var objColumn = $(this).attr('id');
if(!alreadyClicked){
alreadyClicked = true;
$(this)
.prepend('<form method="POST" class="newInput"><input type="text" name="newInput" style="width:140px"></input></form>');
var elemento = $(".newInput");
var position = elemento.position();
$(".newInput").css({
'position': 'absolute',
'top': position.top + 15,
'opacity':0.9,
'z-index':5000,
})
.focus();
//on enter keypress
$(document).keypress(function(e) {
if(e.which == 13) {
$.ajax({
url: 'modify_imp.php',
type: 'post',
data: { id : objName, column : objColumn },
success: function(data, status){
$("#debug").html(data);
}
});
}
});
} //if (!alreadyClicked) end
}); //end mouseenter function
},
//mouseleave function
function () {
alreadyClicked = false;
$(this).css("color","red");
$(".newInput").remove();
}
); //end .hover
});
The debug is a <div id="debug"> </div> at the end of my html page where i want to show my response from server. When i press 'ENTER' I can actually see the value for 0.1s inside that div, but then it disappears.
I already tried to pass the return value to a local or global variable but it didn't work.
For some reason the value inside response is lost after 0.1s, even if i pass it to another variable elsewhere.
Can someone explain me why and how can i "store" the server response?
EDIT: Just edited with my entire <script>
Since you see the result momentarily, I'm going to hazard a guess that you have a form element on your page and when you hit return, it's actually submitting the form. You briefly see the result of the ajax operation and then your form submits causing the page to reload as a new blank page. This is a common issue and always has these same symptoms.
You can either remove the form element or block the default submission of the form with javascript.
If you show us more of your actual HTML, we could help more specifically with how to prevent the form from submitting.
You can solve this by calling the function in the form tag i.e,
<form action="javascript:AnyFunction();">
your code goes here
.
Another way would be to assign a BUTTON to trigger the ajax, and set the button outside of the FORM
I have multiple anchor tag generated by php from database like this
Now I got JQuery script
$(document).ready(function(){
$("#reply_doc").click(function () {
var a = $(this).data("doc_value");
if (a != "") {
$.ajax({
type: "POST",
url: "ajax_check/",
data: "doc_reply=" + a,
success: function (b) {
alert(a+' ok. '+b)
}
});
}
});
});
This is only applying for the first anchor tag.
How can I do this for each anchor tag when that particular is clicked only that anchor will be affected and that particular value will be send with ajax.
Any help will be appreciated. thanks in advance.
The id attribute is an identifier. As the name might suggest, that means it has to be unique so that it can identify a single element. In order to recognise multiple elements, you'll need to use a class instead:
$(".reply_doc").click(...);
Change the id to a class, and change your selector to ".reply_doc".
Your html is currently invalid because the id attribute should be unique. Although the browser doesn't jump up and down complaining when you break this rule, when you try to select an element by id it only finds the first (or, in some browsers, the last).
If, hypothetically, you have no control over the html structure you could instead select all anchor elements with the data-doc_value attribute:
$("a[data-doc_value]")...
Elements cannot have same id so bind event on same class .
a href="#" class="option" id="reply_doc" data-doc_value="1"></a>
JQuery script
$(document).ready(function(){
$(".option").click(function () {
var a = $(this).data("doc_value");
if (a != "") {
$.ajax({
type: "POST",
url: "ajax_check/",
data: "doc_reply=" + a,
success: function (b) {
alert(a+' ok. '+b)
}
});
}
});
});
Edited again DEMO
111<br>
222<br>
333<br>
$(document).ready(function(){
$(".reply_doc").click(function () {
var a = $("a.reply_doc").attr("data-doc_value"); //<-- Add this
if (a != "") {
$.ajax({
type: "POST",
url: "ajax_check/",
data: "doc_reply=" + a,
success: function (b) {
alert(a+' ok. '+b)
}
});
}
});
});
This way each time "a" will have unique value contained in data-doc_value on click
I have a blockUI plugin for jquery through which i call another php file in a overlaid box. I want to activate the function through more than one button of same id(here it is pageDemo1). But when i do so, only one button works while all other don't.Can anyone explain why is it so? and what should i do to make it work?
$(document).ready(function() {
$('#pageDemo1').click(function() {
$.blockUI({ message: $('#domMessage') });
test();
});
$('#submit').click(function() {
var action = $("#form1").attr('action');
var form_data = {
message: $("#message").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
$("#form1").slideUp('slow', function() {
$("#message").html("<p class='success'>message</p>");
});
else
$("#message").html("<p class='error'>message</p>");
}
});
return false;
});
});
On first look dont use html elements with the same id. you can attach your events on elements with the same class, name etc.
Are you saying that you have two elements (buttons) with the same ID? If so, this is not valid HTML (See W3C standards). You could try using a class instead. Also remember you can use multiple classes to still keep the buttons unique in some way. E.g.
<input type="button" class="pageDemo pageDemo1" value="My Click does this"/>
<input type="button" class="pageDemo pageDemo2" value="My Click also does this/>
Then to access these in your JS:
$('.pageDemo').click(function() {
// Put code here which should happen when either of your elements with class 'pageDemo' get clicked
});
$('.pageDemo.pageDemo1').click(function() {
// Put code here which should only happen when elements with 'pageDemo1' class get clicked
});
I have a JavaScript file here http://www.problemio.com/js/problemio.js and I am trying to place some jQuery code into it that looks like this:
$(document).ready(function()
{
queue = new Object;
queue.login = false;
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
var $problemId = $('#theProblemId', '#loginpopup');
$("#newprofile").click(function ()
{
$("#login_div").hide();
$("#newprofileform").show();
});
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
queue.voteUp = $(this).attr('problem_id');
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id)
{
alert ("In vote up function, problem_id: " + problem_id );
queue.voteUp = problem_id;
var dataString = 'problem_id=' + problem_id + '&vote=+';
if ( queue.login = false)
{
// Call the ajax to try to log in...or the dialog box to log in. requireLogin()
}
else
{
// The person is actually logged in so lets have him vote
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
alert ("vote success, data: " + data);
// Try to update the vote count on the page
//$('p').each(function()
//{
//on each paragraph in the page:
// $(this).find('span').each()
// {
//find each span within the paragraph being iterated over
// }
//}
},
error : function(data)
{
alert ("vote error");
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
alert ("after dialog was open");
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
} // End of error case
}
}); // Closing AJAX call.
};
$('.vote_down').click(function()
{
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
$('#loginButton', '#loginpopup').click(function()
{
alert("in login button fnction");
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>
There are two reasons why I am trying to do that:
1) I am guessing this is just good practice (hopefully it will be easier to keep track of my global variables, etc.
2) More importantly, I am trying to call the voteUp(someId) function in the original code from the problemio.js file, and I am getting an error that it is an undefined function, so I figured I'd have better luck calling that function if it was in a global scope. Am I correct in my approach?
So can I just copy/paste the code I placed into this question into the problemio.js file, or do I have to remove certain parts of it like the opening/closing tags? What about the document.ready() function? Should I just have one of those in the global file? Or should I have multiple of them and that won't hurt?
Thanks!!
1) I am guessing this is just good practice (hopefully it will be
easier to keep track of my global variables, etc.
Yes and no, you now have your 'global' variables in one spot but the chances that you're going to collide with 'Global' variables (ie those defined by the browser) have increased 100% :)
For example say you decided to have a variable called location, as soon as you give that variable a value the browser decides to fly off to another URL because location is a reserved word for redirecting.
The solution to this is to use namespacing, as described here
2) More importantly, I am trying to call the voteUp(someId) function
in the original code from the problemio.js file, and I am getting an
error that it is an undefined function, so I figured I'd have better
luck calling that function if it was in a global scope. Am I correct
in my approach?
Here's an example using namespacing that will call the voteUp function:
(function($) {
var myApp = {};
$('.vote_up').click(function(e) {
e.preventDefault();
myApp.voteUp();
});
myApp.voteUp = function() {
console.log("vote!");
}
})(jQuery);
What about the document.ready() function? Should I just have one of
those in the global file? Or should I have multiple of them and that
won't hurt?
You can have as many document.ready listeners as you need, you are not overriding document.ready you are listening for that event to fire and then defining what will happen. You could even have them in separate javascript files.
Be sure your page is finding the jquery file BEFORE this file is included in the page. If jquery is not there first you will get function not defined. Otherwise, you might have other things conflicting with your jquery, I would look into jquery noConflict.
var j = jQuery.noConflict();
as seen here:
http://api.jquery.com/jQuery.noConflict/
Happy haxin
_wryteowl
Extending what KreeK has already provided: there's no need to define your "myApp" within the document ready function. Without testing, I don't know off the top of my head if doing so is a potential source for scope issues. However, I CAN say that the pattern below will not have scope problems. If this doesn't work, the undefined is possibly a script-loading issue (loading in the right order, for example) rather than scope.
var myApp = myApp || {}; // just adds extra insurance, making sure "myApp" isn't taken
myApp.voteUp = function() {
console.log("vote!");
}
$(function() { // or whatever syntax you prefer for document ready
$('.vote_up').click(function(e) {
e.preventDefault();
myApp.voteUp();
});
});
In my html page, I have a select with some options.
When selecting an option, an ajax call is fired passing the option's value to a php script, which returns an html fragment (another select) with a certain id that is appended to the page.
When the user selects another option from the first select, the event is fired again, the ajax call is executed and another html fragment (with the same id) gets appended to the page.
I want that, if the event is fired a second time, the appended element is removed form the page before appending the new one.
At the moment I'm using this code:
$(document).ready(function() {
$("#id_serie").change(function() { //#id_serie is the if of the first select
if ($("#id_subserie_label")) { //#id_subserie_label is the id of the html element returned by the ajax call
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
This is not working though, the html element returned by the second ajax call is appended after the element returned from the first call (because the element with id #id_subserie_label is not in the page when the script is loaded?).
How can I achieve what I need?
You're very close.
Just change if ($("#id_subserie_label")) to if ($("#id_subserie_label").length):
$(document).ready(function() {
$("#id_serie").change(function() {
if ($("#id_subserie_label").length) { // <=== change this line
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
See The jQuery FAQ: How do I test whether an element exists?.
This is because, as Ivo points out:
$("#id_subserie_label") is an object, and objects always evaluate to true.
As per Andy E's comment, you can simplify your code to this, if you don't need the console.log() call:
$(document).ready(function() {
$("#id_serie").change(function() {
$("#id_subserie_label").empty().remove();
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});