-1

There have been many post about passing parameters into Javascript but it seems none has solved my issue here. Therefore, I hope you can help me with this.

I have an object of string (actually its a time) but it seems that only integers are allowed to be passed into the function

Could it be a syntax problem?

displayBidder += "<button class='btn'><a href='javascript:void(null);' onClick='decline(" + obj.Data[i].jobid + ", " + obj.Data[i].bidtime + ") '>Decline</a></button>"

function decline(jobid, time){

    alert(time);

}

$("#display").html(displayBidder);
Bryan Learn
  • 1,563
  • 3
  • 15
  • 13

1 Answers1

0

I have an object of string (actually its a time) but it seems that only integers are allowed to be passed into the function

No. But numbers (and booleans, null and undefined) are the only primitives that will yield an evaluable value for themselves if they are stringified. Do a console.log(displayBidder) to see what html you are producing. If the ids are numbers it will become

<button … onClick='decline(1, 2) '>Decline</button>

but if they're strings it will become

<button … onClick='decline(one, two) '>Decline</button>

(which are variables!) and if you used (non-array) objects it would even be

<button … onClick='decline([object Object], [object Object]) '>Decline</button>

That means you need to serialize the values properly so that they can be interpreted. JSON.stringify could do that, but there's a much better solution:

Use proper event handlers. Inline event attributes are disapproved, especially if created by js. Instead, use

$("#display")
  .html(displayBidder)
  .append($("<button class='btn'>Decline</button>").on("click", /*(function(i) {
       return*/ function(event) {
           alert( obj.Data[i].jobid );
           // and do whatever you want
       }/*;
   })(i)*/));

Uncomment the IEFE if you use this snippet in a loop and i has changed when the handler is executed. See JavaScript closure inside loops – simple practical example for an explanation

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375