Kris MP
Kris MP

Reputation: 2415

Jquery failed to call function on inline html script

I try to delete element with my custom function which is called inside inline html on my script tag, please see my code below:

HTML

<div id="form">
  <input type="text" name="name", id="name"><br>
  <input type="text" name="address", id="address"><br>
  <br>
  <button id="save">Save</button>
</div>

<br><br>

<table border="1">
  <thead>
    <tr>
      <th>Name</th>
      <th>Address</th>
      <th>Unique ID</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody id="content">
  </tbody>
</table>

Javascript

var data = [];

console.log('Initial Data: ');
console.log(data);

$('#save').click(function() {
    var unique_id = new Date().getUTCMilliseconds();
    var returnData = "<tr><td>" + $('#name').val() + "</td><td>" + $('#address').val() + "</td><td>"+unique_id+"</td><td><span onclick='this.removeThis("+unique_id+")'>X</span></td></tr>";
    data.push({
        name: $('#name').val(),
        address: $('#address').val(),
        unique_id: unique_id
    });
    $('#name').val('');
    $('#address').val('');
    console.log('Updated: ');
    console.log(data);
    $('#content').append(returnData);
});

function removeThis(unique_id){
  alert(unique_id);
}

the console said:

Uncaught TypeError: this.removeThis is not a function

same thing happen when i change this.removeThis with removeThis

Here is the Fiddle

Any idea? thanks.

Upvotes: 0

Views: 66

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206348

(P.S.) use DOM ready in the jsFiddle options
A better variant of your code:

jsFiddle demo

var $content = $("#content"),                         // Cache your elements!
    $name    = $("#name"),
    $address = $("#address"),
    data     = [];

function createNewTR() {                              // Helpful function naming

  var name      = $name.val(),                        // Get values
      address   = $address.val(),                     // Get values
      unique_id = new Date().getUTCMilliseconds(),    // UID? whatever...
      $tr       = $("<tr/>", {                        // New ($)TRElement
                   appendTo: $content,                // Where do I go?
                   html: "<td>"+ name +"</td>      \
                          <td>"+ address +"</td>   \
                          <td>"+ unique_id +"</td> \
                          <td></td>"
                   });

  $("<span/>", {                                     // Tell immediately to your SPAN
      html: "X",                                     // what's he's supposed to do:
      appendTo: $tr.find("td:last"),                 // Where to get appended and
      click: function(){ $tr.remove(); }             // remove our $tr element on click
  });

  data.push({
    name:      name,
    address:   address,
    unique_id: unique_id
  });

  $name.add( $address ).val("");
}

$('#save').click(createNewTR);

Upvotes: 0

Try using data attributes with associated event handlers:

'<span data-unique-id="' + unique_id + '">X</span>'

And when you append the string, or when #content is created, you attach an event handler for click events. (It's enough only once)

$('#content').append(returnData);

// "this" will be the current dom span in the event handler function, where the event occured
var self = this;

// attach event handler on every span that is in #content (if you need only one type of them, you need to use a class, or attribute selector
$('#content span').click(
    function(event)
    {
        self.removeThis( $(this).attr("data-unique-id") );
    }
);

Upvotes: 0

Patrick Evans
Patrick Evans

Reputation: 42736

You are getting the error because JSFiddle defaults to putting all code you enter in the "javascript" section into a onload event, meaning your removeThis function is not in global scope and not visible to your inline javascript. Also it would be removeThis() not this.removeThis()

https://jsfiddle.net/w2f7dux7/

Upvotes: 4

Related Questions