user3478891 user3478891 - 1 month ago 7
Javascript Question

ow to pass javascript variable in onclick function

my code is please check and guide me


i want to use onclick function where i want to pass json object in onclick function

for(var i = 0, len = json.length; i < length; i++) {
var curid = json['success'][i]['courier_id'];
var curname = json['success'][i]['courier_name'];
document.getElementById("gsid").value=curname;

var tr="<tr>&nbsp;&nbsp;";
var td1="<td>"+"<input type='radio' name='as' value='json['success'][i]['courier_id']' id='curiid' onclick='courierselect(<?php echo $shyam='\'+curname+\''; ?>);'/>"+"</td>&nbsp;&nbsp;";
var td2="<td id='curnname'>"+json['success'][i]['courier_name']+"</td>&nbsp;&nbsp;";
var td3="<td>"+json['success'][i]['country_charge']+"</td>&nbsp;&nbsp;";
var td4="<td>"+json['success'][i]['estimate_delivery_time']+"</td>&nbsp;&nbsp;";
var td5="<td>"+json['success'][i]['tracking_available']+"</td></tr>&nbsp;&nbsp;";
$("#results").append(tr+td1+td2+td3+td4+td5);


}

Answer

I see three problems on your code

  • ... value='json['success'][i]['courier_id']' ...

You didn't concact the variable with the string

  • ... courierselect(<?php echo $shyam='\'+curname+\''; ?>) ...

    1. echo $shyam='\'+curname+\''; you can't set a PHP variable with a JS value. Understand why
    2. You echo a string value, so you have to add some quotes around curname

for(var i = 0, len = json.length; i < length; i++) {
  var curid = json['success'][i]['courier_id'];
  var curname = json['success'][i]['courier_name'];
  document.getElementById("gsid").value = curname;

  $("#results").append('<tr>&nbsp;&nbsp;');
  $("#results").append('<td><input type="radio" name="as" value="' + curid + '" id="curiid" onclick="courierselect(\'' + curname + '\');"/></td>&nbsp;&nbsp;');
  $("#results").append('<td id="curnname">' + curname + '</td>&nbsp;&nbsp;');
  $("#results").append('<td>' + json['success'][i]['country_charge'] + '</td>&nbsp;&nbsp;');
  $("#results").append('<td>' + json['success'][i]['estimate_delivery_time'] + '</td>&nbsp;&nbsp;');
  $("#results").append('<td>' + json['success'][i]['tracking_available'] + '</td></tr>&nbsp;&nbsp;');
}
Comments