dynamically loaded data cant be seen by JQ

if(isChecked) {  
               
              console.log("checked");


              $('label', '#default-personal-properties').each(function(){
                var _for = $(this).attr("for");
                if( _for.length ) {
                      var emptyInput = $("#"+ _for).val();
                      if( emptyInput == "" ) {
                                  console.log(emptyInput)
                                  $("#"+ _for).fadeOut();
                                  $(this).fadeOut();
                      } else
                                  console.log("field is not blank");
                }
           });

          
            } 
            else {  
             
            
                console.log("unchecked")

                $('#default-personal-properties').find('input, label').each(function(){
                    if($(this).val() == ""){
                        console.log("showing fields");
                        $(this).fadeIn();
                    }
               });


                 
            }

Open in new window


So this code above works because i tested it on hard coded inputs, so i alter the calls to my inputs and it wont fade out, now i think i know why is because my data aint st8 forward instead the data is loaded in dynamically so JQ dont think it exists when it already is so how do i get it to fade in and out ? this is a checkbox to handle blank input fields.
Alex LordAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
line 26 I think you need same as line 6
Chris StanyonWebDevCommented:
Hey Alex,

There's nothing in the code above that wouldn't work because of dynamically injected data. That only becomes a problem if you try to bind events to elements before they've been injected. As long as your elements exist when this code is called, it will be fine.

You haven't shown us when and how you're calling that code, so my guess is that the problem is further up the call stack.

We're probably going to need to see more code to figure out what's going on
Alex LordAuthor Commented:
Hey Chris, i do apologies long weekend,

The data is stored as a php array in a ajax call and outputted once the ajax is called.  so it a array with inputs structured like so -

<div id = 'firstnamee' class=' col-md-4'>
								<label class=' control-label' for='contact-personal-fname'>First Name</label>                 
								<input id='contact-personal-fname' name = 'FIRST_NAME'  type='text' placeholder='First name'  class='form-control input-md no-border' value='".$v_item['FIRST_NAME']."' > 
								</div>

Open in new window

an this is stored in a php array like so  inputs = array("");

once the ajax call is mind that array is returned like so .  -

		$response = array(
			'subresult' => 'defaultprop success',
			'personal' => $properties
		);

Open in new window


so $properties = this array and it is returned to the ajax, now i use json here like so -

var arrayJson = JSON.stringify(response);
        var properties = JSON.parse(arrayJson);

Open in new window


so i am taking the ajax response and passing it into json like above. than i am appending it to it correct container like so -

 $("#default-personal-properties").append(properties.personal);

Open in new window


so problem with code is that it isnt hiding the blank inputs, but when i hard code inputs in it works as expected.
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

Chris StanyonWebDevCommented:
Hey Alex,

Again, there's nothing particularly wrong with your code.

Something I see that does look od though is the JSON.stingify and JSON.parse code. Not sure what you're trying to acheive here. stringify and parse do the exact opposite of each other, so you seem to be turning the response into JSON and then the JSON back into an object. Doesn't make any sense to do that. With AJAX, you should need to do anything with the response - you just tell AJAX theat you expect JSON back and it's work fine.

In your original code above, it starts with the line if(isChecked) {, but I'm presuming that's not the full code. You must have that wrapped in a function somewhere, and you must have something in your code that triggers that function (click / change event etc). We haven't seen that yet so can't check to make sure the trigger is working.

Do you have a link to a test site where we can see this in action. Seeing only parts of your code with no context makes it really difficult to figure out - there's something else going on that we're not seeing.
Alex LordAuthor Commented:
Hey chris

in relation to the is-checked that refers to this
var isChecked = $("#hide-blanks").is(":checked");

Open in new window

, as for json i would refer that back to advice on a previous question elsewhere and it seemed to work for that particular issue so it was used a template. but i will change these around and see the response, unfornatly their is no live feed it is only local. but i will display that entire function,  

trigger -

$(document).ready(function() {
    $("#hide-blanks").change(function () {
       hideBlankProps();

    });
  });

Open in new window




function . -

function hideBlankProps(){

     var isChecked = $("#hide-blanks").is(":checked");
    
            var texttest = "";
    
    
    
            if(isChecked) {  
               
              console.log("checked");


              $('label', '#default-personal-properties').each(function(){
                var _for = $(this).attr("for");
                if( _for.length) {
                      var emptyInput = $("#"+ _for).val();
                      if( emptyInput == "" ) {
                                  console.log(emptyInput)
                                  $("#"+ _for).fadeOut();
                                  $(this).fadeOut();
                      } else
                                  console.log("field is not blank");
                }
           });

          
            } 
            else {  
             
            
                console.log("unchecked")

                $('label', '#default-personal-properties').each(function(){
                    if($(this).val() == ""){
                        console.log("showing fields");
                        $(this).fadeIn();
                    }
               });


                 
            }
}

Open in new window





properties pulled form ajax,

case 'getDefaultProps':

		$properties = array("
								
							<div id = 'landline' class='col-md-4'>
							<label class=' control-label' for='contact-personal-landline'>Laneline</label>   
							<input id='contact-personal-landline' name = 'LANDLINE' type='text' placeholder='Laneline'  class='form-control input-md no-border' value=''>     
							</div>
						

							","
							<div id = 'position' class=' col-md-4'>
							<label class=' control-label' for='contact-personal-position'>Position</label>  
							<input id='contact-personal-position' name 'POSITION' type='text' placeholder='Position'  class='form-control input-md no-border' value='".$v_item['CONTACT_POSITION']."' > 
							</div>
						

						
					");

$response = array(
			'subresult' => 'defaultprop success',
			'personal' => $properties	
		);

		break;

Open in new window


ajax call to get properties -


function createDefaultProps() {
   

    $('#subaction').val("getDefaultProps");
    var data = $('#subaction') ;
    console.log(data);

    $.ajax({
        type: "POST",
        url: 'controllers/contacts.ajax.php',
        dataType: 'json',
        data: data,
    }).success(function (response) {
        
console.log(response);
        var arrayJson = JSON.stringify(response);
        var properties = JSON.parse(arrayJson);
        var leftFormProps = [];

        console.log(properties);


        


       
      



        if(properties.clientzone == "") {
         
     
            $("#default-personal-properties").append(properties.personal);
    
        } else {
            $("#default-personal-properties").append(properties.personalUS);    
        }

}).error(function (data) {
        console.log("erro default prop");
    });

}

Open in new window



Hopefully this can shred some light but all im trying to do is with a check box if the values of the inputs are blank then hide them. the jq to hide them does work as i have tested it on the same inputs but hard coded into html but seems to not when they stored and pulled.
Alex LordAuthor Commented:
function hideBlankProps(){

     var isChecked = $("#hide-blanks").is(":checked");
    
            var texttest = "";
    
    
    
            if(isChecked) {  
               
              console.log("checked");


              $('label', '#default-personal-properties').each(function(){
                var _for = $(this).attr("for");
                if( _for.length) {
                      var emptyInput = $("#"+ _for).val();
                      if( emptyInput ) {
                                  console.log(emptyInput)
                                  $("#"+ _for).fadeOut();
                                  $(this).fadeOut();
                      } else
                                  console.log("field is not blank");
                }
           });

          
            } 
            else {  
             
            
                console.log("unchecked")

                $('label', '#default-personal-properties').each(function(){
                    if($(this).val() == ""){
                        console.log("showing fields");
                        $(this).fadeIn();
                    }
               });


                 
            }
}

Open in new window



so i made changes, i removed the json and only used the response all is good outputs as expected, with the hide blank it is now doing something diffrent, it is not removing the labels or inputs but stating the inputs are not blank.


--
checked
2contact-profile.js:61 field is not blank

Open in new window



how ever - blank inputs

these inputs are indeed blank, their value comes from a session and currently their session has no value.
Chris StanyonWebDevCommented:
Hey Alex,

I'm really not sure what's going on then. Your AJAX call looks a little odd and I'm surprised it's working at all. You're still trying to send a jquery object through your AJAX request.

Also, there's absolutely no need for these 2 lines:

var arrayJson = JSON.stringify(response);
var properties = JSON.parse(arrayJson);

Your response is already JSON (or at least it should be asumming you've json_encoded in the PHP file !!). All those lines do is cancel each other out - remove them.

Have you made sure that the hideBlankProps() function is actually being called when you change the #hide-blanks element ?
Chris StanyonWebDevCommented:
Ahh OK. We cross-posted - that seems like progress :)

Output the value of emptyInput before the if to see what you get:

var emptyInput = $("#"+ _for).val();
console.log(emptyInput);
if( emptyInput ) {
    ...

Open in new window

Alex LordAuthor Commented:
Hey chris,

test data -

$('label', '#default-personal-properties').each(function(){
                var _for = $(this).attr("for");
                console.log(_for + " 1");
                if( _for.length) {
                      var emptyInput = $("#"+ _for).val();
                      console.log(emptyInput + " 2");
                      if( emptyInput ) {
                                 
                                  $("#"+ _for).fadeOut();
                                  $(this).fadeOut();
                      } else
                                  console.log("field is not blank");
                                
                }

Open in new window



response -


checked
contact-profile.js:54 contact-personal-landline 1
contact-profile.js:57  2
contact-profile.js:63 field is not blank
contact-profile.js:54 contact-personal-position 1
contact-profile.js:57  2
contact-profile.js:63 field is not blank

Open in new window


sorry had to edit wrong data
Alex LordAuthor Commented:
Ok so i did a test here, and based on it the input does not seem to exist.

test function  -

$('label', '#default-personal-properties').each(function(){
                var _for = $(this).attr("for");
                console.log(_for + " 1");
               
                      var emptyInput = $("#"+ _for).val();
                      console.log(emptyInput + " 2");
                      if( emptyInput ) {
                                 
                                  $("#contact-personal-landline").fadeOut();
                                  $(this).fadeOut();
                      } else
                                  console.log("field is not blank");
                                  $("#contact-personal-landline").fadeOut();
                                
                
           });

Open in new window


output -

checked
contact-profile.js:54 contact-personal-landline 1
contact-profile.js:57  2
contact-profile.js:63 field is not blank

Open in new window


so either way that input should of been faded out as i hardcoded its id in but it still remains.
Alex LordAuthor Commented:
function createDefaultProps() {
   

    $('#subaction').val("getDefaultProps");
    var data = $('#subaction') ;
    console.log(data);

    $.ajax({
        type: "POST",
        url: 'controllers/contacts.ajax.php',
        data: data,
    }).success(function (response) {
        
console.log(response);
        //var arrayJson = JSON.stringify(response);
        var properties = JSON.parse(response);
        var leftFormProps = [];
        var testdefault = [];

        testdefault.push($(response.personal));





        


    


        if(properties.clientzone == "") {
         
            $("#default-location-props").append(properties.location);
            $("#default-personal-properties").append(properties.personal);
     
            $("#checked-list").append(properties.checklist);
            $("#custom-properties").append(properties.custom);
        } else {
    
            $("#default-location-props").append(properties.location);
            $("#default-personal-properties").append(properties.personalUS);
      
            $("#checked-list").append(properties.checklist);
            $("#custom-properties").append(properties.custom);
        }

Open in new window



here is the solution, i am still puzzled on why but i sent it away as json and returned it back as json and it wouldn't work. but so i removed the datatype json, and parse it on response and it worked as expected. still puzzling me but if u have a explanation  on why i would be all ear to learn from this.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.