Hussain Aali
Hussain Aali

Reputation: 49

How can I get the text from dynamic textbox by dynamic button in HTML and ajax

I'm trying to get data from a database and update the records one by one, I had made a table I created a text input field and button which will build dynamically with the records, the text input field will have the previous record, then I should change that and submit it. the problem is when I try to edit and submit which I changed, it gives the first text input value for all the button

this is my Javascript code:

$("body").delegate("a","click",function(event){
//$("#category_editing").click(function(){
event.preventDefault();
var cat_name = $("#new_cat_name").val();
//var cat_name = $(this).attr('new_cat_name');
var cat_id   = $(this).attr('cat_id');
console.log('starting ajax');
alert(cat_name);
 $.ajax({
        url : "update_cat.php",
        method: "POST",
        data  : {cat_id:cat_id,cat_name:cat_name},
        success : function(data){
           alert(data);
        }

    });
});

and this is my php and html code:

 $category_query = "SELECT * FROM `CATEGORIES`";
    $run_query = mysqli_query($connect,$category_query);
    echo "
    <div class='nav nav-pills nav-stacked'>
  <li class='active'><a href='#'

    >Categories</a></li>";
        if(mysqli_num_rows($run_query)>0){
            while

($row = mysqli_fetch_array($run_query))
        {

            $CATEGORY_ID = $row['CATEGORY_ID'];
            $CATEGORY_NAME = $row['CATEGORY_NAME'];
            $CATEGORY_DESC = $row['CATEGORY_DESC'];
            $CATEGORY_IMAGE_PATH = $row['CATEGORY_IMAGE_PATH'];


            echo "

           <li><a class='category_editing' cat_id='$CATEGORY_ID'><input type='text' class='form-control' id='new_cat_name' value='$CATEGORY_NAME'><a href='#' class='category_editing btn btn-warning' cat_id='$CATEGORY_ID' cat_name='$CATEGORY_NAME'>Submit</a></a></li>";

        }

    }

      //}

?>

enter image description here

Upvotes: 0

Views: 180

Answers (1)

David Ibl
David Ibl

Reputation: 911

That's the problem:

var cat_name = $("#new_cat_name").val();

You should access the changed input by the id of the anchor tag or something like this. You have to select a specific input. You could render it this way:

cat_id='$CATEGORY_ID'><input type='text' class='form-control' id='input_$CATEGORY_ID'

And try to access the input by concatenation of the string 'input' and the id of the anchor text in the handler context.

Upvotes: 1

Related Questions