I have the following code which works:
$(document).ready(function() {
var xhr = false;
func_two();
$('.button_one').click( function(event) {
event.preventDefault();
if ($("#textbox_one").val().length > 0) {
func_one( $("#textbox_one").val() );
} else {
func_two();
}
});
function func_one( phrase ) {
xhr = $.ajax({
type: 'POST',
url: 'url here',
data: '{phrase: "' + phrase + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function( data ) {
$("#inner_div").empty();
if( data.d[0] ) {
$.each( data.d, function( index, row ) {
$("#inner_div").append( "dynamic data goes here" );
});
}
}
});
}
function func_two() {
$('#inner_div').empty().append( "static data goes here" );
}
});
This works fine as I am directly specifying which tags cause an effect and which tags get affected. The problem is that these div’s are infact widgets or gadgets, and I need to allow the user to have more than 1 of these widgets or gadgets on the screen at at any given time. Things seem to go totally wrong when I try this because “I assume” of the use of an id for the controls and divs.
So, I have tried using classes instead, which seem to work in the test code here:
$(this).closest('.main_div').find('.sub-div').text("data goes here");
However, when I try to apply this code to the original code above, it does not seem to work. It gives me an Cannot call method 'closest' of undefined according to Chromium’s Developer tools.
The code which I have tried which does not seem to work looks like this:
$(document).ready(function() {
var xhr = false;
func_two();
$('.button_one').click( function(event) {
event.preventDefault();
if ($("#textbox_one").val().length > 0) {
func_one( $(this), $("#textbox_one").val() );
} else {
func_two( $(this) );
}
});
function func_one( that, phrase ) {
xhr = $.ajax({
type: 'POST',
url: 'url here',
data: '{phrase: "' + phrase + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function( data ) {
$("#inner_div").empty();
that.closest('.outer_div').find('.inner_div').empty();
if( data.d[0] ) {
$.each( data.d, function( index, row ) {
that.closest('.outer_div').find('.inner_div').append( row.column );
});
}
}
});
}
function func_two( that ) {
that.closest('.outer_div').find('.inner_div').append( "static data goes here" );
}
});
The HTML looks like this
<div class="outer_div">
<div class="inner_div">
results go here
</div>
<div class="footer_div">
<input type="button" class="button_one" />
</div>
</div>
Can someone please help me implement the test code into the original code?
Try this out, I believe your button is being deleted, and there’s no longer a reference to that element. By storing a reference to the targetted sub div, THAT stays in the context of what you’re trying to do 🙂