problem in loop for - javascript

i am using this code, that works well. Now i need to change only the name of inputs, input1, input 2, and so on.
<script type="text/javascript">
$(document).ready(function() {
$("#input1 > select.profissao").live('change', function(){
$.ajax({
type: "POST",
data: "data=" + $(this).val(),
url: "drop1.php",
success: function(html) {
$("#input1 > select.estatistica").html(html);
}
});
});
});
</script>
why reason this version doesn't work? i already check the code in lint, and none error is detected.
Basically if i copy the code above and change input1 to input2, works well, but my objective is reduce the redundancy.
<script type="text/javascript">
$(document).ready(function() {
for (i=1; i<3; i++) {
$("#input"+i+" > select.profissao").live('change', function(){
$.ajax({
type: "POST",
data: "data=" + $(this).val(),
url: "drop1.php",
success: function(html) {
$("#input"+i+" > select.estatistica").html(html);
}
});
});
}
});
</script>
EDIT: the output is something like that <option value=2>Artes</option><option value=1>Humanidades</option> but this is not added to the html
with the loop my drop down simple stops to work

You can try
<script type="text/javascript">
$(document).ready(function() {
for (i=1; i<3; i++) {
(function(idx){
$("#input"+idx+" > select.profissao").live('change', function(){
$.ajax({
type: "POST",
data: "data=" + $(this).val(),
url: "drop1.php",
success: function(html) {
$("#input"+idx+" > select.estatistica").html(html);
}
});
});
})(i);
}
});
</script>
And your function get the same reference of i in a scope.

The top and bottom block have different classes for the selects is that one problem?
Also the concatenation approach seems less maintainable.
Perhaps consider using something like this
$('#input1, #input2, #input3').children('select.area').each(function () {
$(this).live(...);
});
Edit: also swapping out html contents of selects in ie is not very well supported and has led to quite a few bugs for me so you may want to consider rebuilding the select each time

Related

How can I do a conditional statement so ajax fetchs the correct xml document

I have a simple code to fetch a xml file and display it as a drop down list. However, I would like to fetch the xml file according to a condition. If it equals to study1 then .ajax selects ctc3.xml, else it selects ctc5.xml.
My code was working fine if I was fetching a specific xml file, but the conditional does not work.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script lang="Javascript"> $.noConflict();
jQuery(document).ready(function($) {
var myField = $("#myList") var myOutputField = $("#myOutput").parent().parent().find("input");
myOutputField.attr("readonly",true);
var studyID="${studyName}";
if (studyID!="Test"){
$.ajax({
type: "GET",
url: "includes/ctcae3.xml",
dataType: "xml",
success: parseXML
});
}
else {
$.ajax({
type: "GET",
url: "includes/ctcae5.xml",
dataType: "xml",
success: parseXML
});
}
function parseXML(xml){
$(xml).find("atccode").each(function(){
myField.append($("<option />").val($(this).attr("code")).text($(this).find("description").text()));
});
myField.val(myOutputField.val());
}
myField.change(function(){
myOutputField.val(myField.val());
myOutputField.change();
});
});
</script><select id="myList"> <option val="None"/>None </select> `
problem resolved. Clearly my brain was already fried. It was just a matter of adding the ';' to var myField = $("#myList");

How to resolve jQuery conflict?

I have a jQuery custom file which is disabling or conflicting my other jQuery file, please how do i resolve this. Please see below:
My Custom file:
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
Conflicting Files:
<script src="js/jquery.isotope.min.js"></script>
<script src="js/nprogress.js"></script>
I would be more than happy if this is resolved.
I'm assuming that you know for certain jQuery is conflicting - you've checked the console errors, etc.
You could wrap your jQuery in a self-executing anonymous function as follows:
(function($) {
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
})(jQuery);
EDIT - a bit of explanation of what's happened above. In order to prevent any potential conflicts with other scripts / frameworks we are passing the jQuery object as an argument to our function (hence function($)). The benefits of doing this is that you can now use $ locally within the function at will. Without fear of conflicting with other scripts on a global scope.
I Was able to fix the problem by just wrapping it with:
$(document).ready(function() {
//-----
});

Not to remove object without confirmation

I try to remove elements from my table in my django project, but I would like to have such a removal to be confirmed. Using this article
http://www.developmentwall.com/delete-row-from-html-table-jquery/
I wrote such function:
<script>
function deleteAjax(row_id){
$.ajax({
url: "delete_item/"+ row_id +"/",
type: "POST",
data: {'id':row_id},
success: function (){
if(!confirm('Are you sure you want to delete?')){
ev.preventDefault();
return false;
}else{
$('#my_row_'+row_id).remove();
}
}
});
}
</script>
Unfortunately, despite of the fact that I click that I won't to delete object, the object is removed.
Have you any hints? I suppose that it can be something wrong with ev, but I am fairly new to javascript and ajax and I do not know how to cope with this.
try this:
<script>
function deleteAjax(row_id){
if (!confirm('Are you sure you want to delete?')) { return; }
$.ajax({
url: "delete_item/"+ row_id +"/",
type: "POST",
data: {'id':row_id},
success: function (){
$('#my_row_'+row_id).remove();
}
});
}
</script>

JavaScript - Results Displaying in IE but not Chrome or FF

So, i'm new to Javascript, let's get that out of the way.
Anyway, I have the following code that works in IE, but not in Chrome or FF. It's supposed to grab the data from the Reddit RSS, then just output it, that's it. It only is working in IE. Can anyone explain what I'm doing wrong here?
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
document.write(result);
</script>
</head>
</body>
</html>
yes, this code doesn't look right. it's a race condition. document.write executes immediately. the ajax may or may not have set the result in time. you need to add the result to the page in the success event...something like:
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get', dataType: 'html',
async: false,
success: function(data) {
$("#some-div").html(data);
} });
You have race condition due to $.ajax being asynchronous. Display the result in the success handler instead, so that the request is guaranteed to have finished.
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
document.write(data);
}
});
Update
Since you set async to false, the above statement isn't applicable. However, I haven't ever found a good reason to use document.write(), which might be part of your issue. Try using another method to inject the data into your page such as .html(), .append(), alert(), etc. And it wouldn't hurt to do this inside document.ready either.
$(document).ready(function() {
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
alert(result);
$("body").append(result);
});
What about processing in this manner:
(function(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
})('http://www.reddit.com/.rss', function(feed) {
var entries = feed.entries,
feedList = '';
for (var i = 0; i < entries.length; i++) {
feedList += '<li>' + entries[i].title + '</li>';
}
jQuery('.rssfeed > ul').append(feedList);
});
HTML:
<div class="rssfeed">
<h4>RSS News</h4>
<ul></ul>
</div>
sample: http://jsfiddle.net/QusQC/

.keyup() is only working once, why?

I am using this pretty simple jquery function, but it seems to work only on the first keyup..
$('#cmentuser').keyup(function() {
var mess = document.getElementById('cmentuser').value;
var dataString = 'message='+ mess;
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: dataString,
success: function() {
}
});
});
any ideas on how to keep it active?
It works, also in the following form (changed mess into jQuery(this).val() and relied on jQuery when encoding the data string):
$('#cmentuser').keyup(function() {
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: {
'message': jQuery(this).val()
},
success: function() {
// success callback
}
});
});
Proof that it works: jsfiddle.net/xfxPR/
You may be dynamically changing some elements (eg. changing ID or assuming id does not need to be unique), or maybe unbinding the event. Just make sure the event is being attached and stays attached to the element you need.
$(document).on('keyup', '#cmentuser', function(e) {//try to find lower element then doc
var dataString = 'message='+ $(e.target).val();
$.ajax({
type: "POST",
url: "/comentbyuser.php", //no cross domain requests, no need for domain name
data: dataString,
success: function() {}
});
});
try this
$('#cmentuser').live('keyup',function() {
var mess = $(this).val();
var dataString = 'message='+ mess;
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: dataString,
success: function() {
}
});
});

Categories

Resources