How to pass a JavaScript variable in onClick function - javascript

Here is my code, I wanna get the element info in the click function like my annotation says.
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> ";
//here is where i want to use onclick function with curid and curname
var td1="<td>"+"<input type='radio' name='as' value='json['success'][i]['courier_id']' id='curiid' onclick='courierselect(<?php echo $shyam='\'+curname+\''; ?>);'/>"+"</td> ";
var td2="<td id='curnname'>"+json['success'][i]['courier_name']+"</td> ";
var td3="<td>"+json['success'][i]['country_charge']+"</td> ";
var td4="<td>"+json['success'][i]['estimate_delivery_time']+"</td> ";
var td5="<td>"+json['success'][i]['tracking_available']+"</td></tr> ";
$("#results").append(tr+td1+td2+td3+td4+td5);
}

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+\''; ?>) ...
echo $shyam='\'+curname+\''; you can't set a PHP variable with a JS value. Understand why
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> ');
$("#results").append('<td><input type="radio" name="as" value="' + curid + '" id="curiid" onclick="courierselect(\'' + curname + '\');"/></td> ');
$("#results").append('<td id="curnname">' + curname + '</td> ');
$("#results").append('<td>' + json['success'][i]['country_charge'] + '</td> ');
$("#results").append('<td>' + json['success'][i]['estimate_delivery_time'] + '</td> ');
$("#results").append('<td>' + json['success'][i]['tracking_available'] + '</td></tr> ');
}

Related

How to get input from dynamically created checkboxes and radio buttons in javascript?

I need to dynamically create checkboxes and radio buttons in groups of data displayed, then I need to take the user choices and put them in variables.
I have made an example with a few checkboxes and radio buttons, but I don't have a clue how to actually get the input:
Here is the jsfidle
var t = document.getElementById("container");
var data1 = ['TV', 'Newspaper', 'Internet'];
var data2 = ['New York', 'Washington', 'Los Angeles'];
t.innerHTML += checkbutton(data1);
t.innerHTML += radiobutton(data2);
function checkbutton(d) {
var output = "";
for (var i = 0; i < d.length; i++) {
output += '<input type="checkbox" value=' + d[i] + ' name="box2">' + ' ' + d[i] + ' ' + '<br><br>';
}
return output;
}
function radiobutton(d) {
var output = "";
for (var i = 0; i < d.length; i++) {
output += '<input type="radio" value=' + d[i] + ' name="box2">' + ' ' + d[i] + ' ' + '<br><br>';
}
return output;
}
<div id="container"></div>
Using javascript you can query specific properties of html elements - like the radio buttons and the checkboxes.
To be able to do this, each element should have an unique id - so we can get an element using document.getElementById(id).
The other option is to get elements by their type e.g. document.getElementsByTagName("input"). This will return a html collection - an array - of all the input elements.
With a simple for-loop you can iterate over this array and using the .checked property you can find out if one of those input boxes is selected.
var t = document.getElementById("container");
var data1 = ['TV', 'Newspaper', 'Internet'];
var data2 = ['New York', 'Washington', 'Los Angeles'];
t.innerHTML += checkbutton(data1);
t.innerHTML += radiobutton(data2);
function checkbutton(d) {
var output = "";
for (var i = 0; i < d.length; i++) {
output += '<input type="checkbox" value="' + d[i] + '" name="box2">' + ' ' + d[i] + ' ' + '<br><br>';
}
return output;
}
function radiobutton(d) {
var output = "";
for (var i = 0; i < d.length; i++) {
output += '<input type="radio" value="' + d[i] + '" name="box2">' + d[i] + '<br><br>';
}
return output;
}
function check() {
var elements = document.getElementsByTagName("input");
for (var a = 0; a < elements.length; a++) {
if (elements[a].checked) {
console.log(elements[a].value + " is checked");
}
}
}
<div id="container"></div>
<button id="check" onclick="check()">
check
</button>
Like this?
Note the event listeners and the change of names
Also make sure you quote the names and values
function checkbutton(d) {
var output = "";
for (var i = 0; i < d.length; i++) {
output += '<label><input type="checkbox" value="' + d[i] + '" name="box'+i+'">' + ' ' + d[i] + ' ' + '</label><br><br>';
}
return output;
}
function radiobutton(d) {
var output = "";
for (var i = 0; i < d.length; i++) {
output += '<label><input type="radio" value="' + d[i] + '" name="rad">' + ' ' + d[i] + ' ' + '</label><br><br>';
}
return output;
}
window.addEventListener("load", function() {
var t = document.getElementById("container");
var b = document.getElementById("but");
var data1 = ['TV', 'Newspaper', 'Internet'];
var data2 = ['New York', 'Washington', 'Los Angeles'];
t.innerHTML += checkbutton(data1);
t.innerHTML += radiobutton(data2);
t.addEventListener("change",function(e) {
var tgt = e.target;
if (["radio","checkbox"].indexOf(tgt.type) !=-1) { // only look at checkboxes and radios. Change if needed
console.log(tgt.value);
}
});
b.addEventListener("click",function() {
var vars = {}
t.querySelectorAll("input").forEach(inp => {
if (inp.checked) vars[inp.name]=inp.value
});
console.log(vars);
})
})
<div id="container"></div>
<button type="button" id="but">Click</button>

Dynamic option list from an array

I have the following code which works perfectly, but can I make the drop menu dynamic using quantityAllowed as the maximum the drop menu goes to. at the moment I have added 10 options for every print, but what i would prefer is the drop menus only have the correct quantity in. I think the loop I need would go where the options begin using the value of the loop, but when i have tried, i just get an error, so I know I have done something wrong.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
$("#tbNames tr:last").after("<tr>" +
"<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>" +
"<td class='printpoints'>" + calcTable[index].printPrice + "</td>" +
"<td>" + calcTable[index].quantityAllowed + "</td>" +
"<td><select " + myclass + "><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td></td> </tr>");
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
You can separate out your HTML generation code from the jQuery DOM assignment. This makes it a little easier to read and manipulate. When you come to your select/option area, drop it into a for... loop to generate the appropriate number of options.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
var output = '';
output += "<tr>";
output += "<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>";
output += "<td class='printpoints'>" + calcTable[index].printPrice + "</td>";
output += "<td>" + calcTable[index].quantityAllowed + "</td>";
output += "<td><select " + myclass + ">";
for( var i=0, x=calcTable[index].quantityAllowed; i<x; i++ ){
output += '<option value="' + i + '">' + i + '</option>';
}
output += "</select></td><td></td> </tr>";
$("#tbNames tr:last").after(output);
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
arrayData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbNames">
<tr></tr>
<tr></tr>
</table>

How to create a dynamic table in jQuery?

I want to create a dynamic table in jQuery. But my code creates a table for each of my element.
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content = "<table>" + "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
Which part of my code is wrong?
as you were adding table in for loop, so it was creating table for each item.Try this:
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
content ="<table>"
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 = content;
}
content += "</table>"
// you can also assign spl2 = content; over here.
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
var content = "<table>";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
Updated your script

Fill table in javascript with data from db

I have an html <table> that I need to fill with data from a database query. The query returns 10 rows and then sends the data to the method fill(data) to fill the table:
function getTopQ() {
alert("Get top Qs");
callServer('fill', 'checkConnection', false, 'SelectTopQues.php');
}
function fill(data) {
alert("ready to fill now");
$('#table').html('');
var search = '#table';
for (var i = 0; i < data.length; i++) {
$('#table').listview("refresh");
var Questions = data[i];
var str = '<td " ID="' + Questions[0] +
'" Question="' + Questions[1] +
'" UserID="' + Questions[2] +
'"CategoryId"' + '" SubCategoryId"' + '" DatePosted"' + '"';
str += '">'; //end li
str += '<a href="" data-transition="fade">';
str += Questions[1];
str += '</a>';
//str += '<span class="hiddenData">' + item[13] + '</span>';
str += '</td>';
$('#table').append(str);
$('#table').listview("refresh");
}
console.log(data);
console.log($('#table'));
$('#table').listview("refresh");
}

local storage iteration get the value of clicked button inside for loop

I have this code:
for(var i = 0; i < localStorage.length; i++){
var dataNya = JSON.parse(localStorage.key(i));
// console.log(dataNya);
var displayUlit = "";
displayUlit += "<br/>";
var spaceTo = "";
spaceTo += " || ";
console.log(dataNya);
var keme = localStorage.getItem(localStorage.key(i));
$("#pangDisplay").append(dataNya + spaceTo + "<button class='pangEdit' value="+dataNya+">"+JSON.parse(keme)+"</button>" + " " + displayUlit);
console.log(JSON.parse(keme));
// localStorage.setItem(JSON.stringify(dataNya), JSON.stringify("complete"));
}
$(".pangEdit").click(function(e){
e.preventDefault();
var pangInput = $(".pangEdit").val();
console.log(pangInput);
localStorage.setItem(JSON.stringify(pangInput), JSON.stringify("complete"));
});
i want to get the key of the localstorage where i can pass the data and update its value. help me thanks
You can use an attached data attributes in jQuery for this:
for (var i = 0; i < localStorage.length; i++) {
var dataNya = localStorage.key(i);
var displayUlit = "";
displayUlit += "<br/>";
var spaceTo = "";
spaceTo += " || ";
var keme = localStorage.getItem(dataNya);
var button = "<button class='pangEdit' data-storagekey='" + dataNya + "' value='" + dataNya + "'>" + keme + "</button>";
$("#pangDisplay").append(dataNya + spaceTo + button + " " + displayUlit);
}
$(".pangEdit").click(function(e) {
e.preventDefault();
var dataNya = $(this).data('storagekey');
localStorage.setItem(dataNya, "complete");
});

Categories

Resources