简体   繁体   中英

Javascript: how to write document.getElementsByClassName() inside while loop in php

How to write for loop inside php while loop?

I have numDifferentiation() javascript function. I want to write this function() inside <span class="price"></span> . I tried document.write() but it replaces entire html page. How to write document.getElementsByClassName('price')[].innerHTML = numDifferentiation('<?php echo $row['msp']; ?>'); inside while loop of php.

I tried:

<?php
for($=0;$i<10;$i++){
?>
<script>
 document.getElementsByClassName('price')[<?php echo $i ?>].innerHTML = numDifferentiation('<?php echo $row['msp']; ?>');
</script>
<?php
}
?>

My entire code javascript function, form submit on keyup via ajax. Ajax code and PHP.

Javascript

function numDifferentiation(val) {
          if(val >= 10000000) val = (val/10000000).toFixed(2) + ' Cr';
          else if(val >= 100000) val = (val/100000).toFixed(2) + ' Lac';
          else if(val >= 1000) val = (val/1000).toFixed(2) + ' K';
          return val;
}

Form Submit via Ajax

$( document ).ready( function () {
        $( ".searchTerm" ).keyup( function () {
            var text = $( this ).val();

            $.ajax( {
                type: "POST",
                url: "read-project.php",
                data: 'text=' + text,
                dataType: "html",
                async: false,
                success: function ( data ) {
                        if(text == ""){
                            $( '.search_box' ).hide();
                            $( '#project-list-all' ).show();
                            $( '.search_box' ).html("");
                        }


                        else if(text.length >= 2){
                            $( '.search_box' ).show();
                            $( '.search_box' ).html( data );
                        $("#project-list-all:empty").parent().hide();
                        $( '#project-list-all' ).hide();
                        }
                },
                error: function ( errorThrown ) {
                    alert( errorThrown );
                    alert( "There is an error with AJAX!" );
                }

            } );
        } );
    } );

PHP

<?php
require_once('config.php');
//require_once('config.php');

$text = $_POST['text'];

$result = $conn->query("select * from project where name LIKE '%$text%' or type LIKE '%$text%' or sector LIKE '%$text%' or city LIKE '%$text%' or builder LIKE '%$text%' LIMIT 6");


    if($result){
        echo '<ul>';
        if(mysqli_num_rows($result) > 0) {



        while ($row = $result->fetch_assoc()) 
        { 
            echo "<li>";
            ?>

                <div class="col-md-4 col-sm-6 col-xs-12">
                <div class="flat-item" style="box-shadow: 2px 2px 9px #000; padding: 5px;">
                    <div class="flat-item-image">

                        <a href="project-details.php?id=<?php echo $row['id'] ?>"><img src="images/small_images/<?php echo $row['small_img']; ?>" alt=""></a>
                        <div class="flat-link">
                            <a href="project-details.php?id=<?php echo $row['id'] ?>">More Details</a>
                        </div>
                        <ul class="flat-desc">
                            <li>
                                    <h5 class="clr-white project-heading"><a href="project-details.php?id=<?php echo $row['id'] ?>"><?php echo $row['name'];?> </a></h5>
                                    <P class="uderline"></P>
                                    <p class="property-type"><?php echo $row['type'];?></p>
                            </li>

                        </ul>
                    </div>
                    <div class="flat-item-info">
                        <div class="flat-title-price">
                        <p class="pull-left"><img src="images/icons/location.png" alt=""><?php echo $row['sector'];?>,<?php echo $row['city'];?></p>
                            <span class="price" id="price"><script>
                            document.getElementsByClassName('price')[].innerHTML = numDifferentiation('<?php echo $row['msp']; ?>');
                            </script></span>
                        </div>

                    </div>
                </div>

            <?php 
            echo '<li>';
        }


        echo '</ul>';
    }

    else {
            echo '<h2 style="color: red;">No Result Found: '.$text.'</h2>';
        }
}

?>

Scripts shouldn't be put inside of HTML content like that - ideally, put them in separate .js files.

Note that it's invalid HTML to have multiple elements with the same ID in the same document: remove id="price" .

Give the .price s data- attributes with PHP, and then have Javascript loop over the .price s to run numDifferentiation. For example:

<span class="price" data-msp="<?php echo $row['msp']; ?>">

and then, in your Javascript (somewhere else, written only once):

document.querySelectorAll('.price').forEach((priceSpan) => {
  priceSpan.textContent = numDifferentiation(priceSpan.getAttribute('data-msp'));
});

to run on page load.

You should probably make your numDifferentiation better too:

function numDifferentiation(val) {
  if(val >= 10000000) return (val/10000000).toFixed(2) + ' Cr';
  else if(val >= 100000) return (val/100000).toFixed(2) + ' Lac';
  else if(val >= 1000) return (val/1000).toFixed(2) + ' K';
  return val;
}

(you don't want to reassign the parameter, you just want to return when the desired condition is found)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM