I want to populate HTML form input fields with JSON data I get from my API. I can display the data in a table with the following code, but I cannot make it work with a form. I tried to address the form with something like or instead of and , but it doesn't work. Does anyone know if I can transform this code to work with a form?
const url = "/api/contacts/" + localStorage.getItem("paraID");
fetch(url).then((res) => {
res.json().then((data) => {
console.log(data);
if (data.length > 0) {
var temp = "";
data.forEach((itemData) => {
temp += "<tr>";
temp += "<td>" + itemData.studentID + "</td>";
temp += "<td>" + itemData.nachname + "</td>";
temp += "<td>" + itemData.studium + "</td>";
temp += "<td>" + itemData.semester + "</td>";
temp += "<td>" + itemData.deaktiviert + "</td></tr>";
});
document.getElementById("myTable").innerHTML = temp;
}
});
});
The fetch function works, I can see the correct JSON data in the console. It looks like this:
[{…}]
0: {studentID: 1, vorname: 'Marie', nachname: 'Bauer', strasse: '', plz: '', …}
length: 1
[[Prototype]]: Array(0)
I tried all the different options I found at stackoverflow (e.g. with jQuery), but they also don't work with a form.
you can try this code:
<form id="myForm">
<input name="studentID" />
<input name="nachname" />
<input name="studium" />
<input name="semester" />
<input name="deaktiviert" />
</form>
let exampleData = [{
studentID: 'value',
nachname: 'value',
studium: 'value',
semester: 'value',
deaktiviert: 'value',
}]
const myForm = document.getElementById('myForm');
exampleData.forEach((itemData) => {
myForm['studentID'].value = itemData.studentID;
myForm['nachname'].value = itemData.nachname;
myForm['studium'].value = itemData.studium;
myForm['semester'].value = itemData.semester;
myForm['deaktiviert'].value = itemData.deaktiviert;
});
This is how I got it to work:
deleted let = exampleData
replaced exampleData.forEach((itemData) … with data.forEach((itemData) …
fetch(url).then((res) => {
res.json().then((data) => {
console.log(data);
if (data.length > 0) {
const myForm = document.getElementById("myForm");
data.forEach((itemData) => {
myForm["studentID"].value = itemData.studentID;
myForm["nachname"].value = itemData.nachname;
myForm["studium"].value = itemData.studium;
myForm["semester"].value = itemData.semester;
myForm["deaktiviert"].value = itemData.deaktiviert;
});
}
});
});
Related
I have a list of Data I get from dynamic inputs like this ones
FirstNames : Person1 FN, Person2 FN, Person3 FN, ...
LastNames : Person1 LN, Person2 LN, Person3 LN, ...
The list is dynamic and I'm Getting the values by input Name like this
var FirstNames = $("input[name='FirstName']").map(function(){return $(this).val();}).get();
I want to pass these and many others to my C# backend as an array like This
details:[
0: {FirstName: 'Person1 FN', LastName: 'Person1 LN'}
1: {FirstName: 'Person2 FN', LastName: 'Person2 LN'}
....................................................
N{FirstName: 'PersonN FN', LastName: 'PersonN LN'}
]
I tried many different approaches like split() & Push() as below
let FNs = [];
let FN = FirstNames.toString().split(',');
console.log("Splitted First Names : "+TFNs);
$.each(TFNs, function(){
FNs.push({FirstName:$(this)}.toString());
});
console.log("First Names[] : "+FNs);
Edit : Added Form markup(dynamic) & JS Save() Function
Here is the form (dynamically generated)
function GenerateFrms(Id) {
//alert('Function Scripts');
$("#FrmContainer").empty();
var html = "";
$.ajax({
type: "POST",
url: "WebService.asmx/GenerateForms",
data: "{'Id':'" + Id + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
console.log(Object.values(data))
try {
for (var i = 0; i <= data.d.length; i++) {
if (data.d[i].Persons != "0") {
html += " <div class='theme-box-shadow theme-border-radius bg-light mb-3'> ";
html += " <div class='row border-bottom py-2 m-auto'> ";
html += " <div class='col-8'>";
html += " <div class='fw-bold font-medium'> Details </div> ";
html += " </div> ";
html += "<div class='col-4 text-end align-self-center'> ";
html += " <a class='font-small' data-bs-toggle='collapse' href='#collapseFrm' role='button' aria-expanded='false' aria-controls='collapseFrm'><i class='bi bi-chevron-down ps-1'></i></a>";
html += " </div>";
html += " </div>";
html += " <div class='' id='collapseFrm'> ";
html += " <div class='row'> ";
html += " <div class='col-sm-12'> ";
html += " <div class='px-3 FrmDetails' id='FrmDetails'> ";
for(var j=1; j<=data.d[i].Persons; j++)
{
html += " <legend class='fw-bold' style='border-bottom:2px solid blue;'> Persons " + j + " Details</legend> ";
html += " <ul class='row py-3'> ";
html += " <li class='col-12 col-md-12 pb-3'> ";
html += " <div class='row'> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> selected Title </label> ";
html += " <select class='form-select Title' name='Title' id='Title" + j + "' > ";
html += " <option selected>Title</option> ";
html += " <option value='Mr'>Mr.</option> ";
html += " <option value='Mrs'>Mrs.</option> ";
html += " <option value='Ms'>Ms.</option> ";
html += " </select> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> First Name </label> ";
html += " <input type='text' class='form-control FirstName' name='FirstName' id=' FirstName" + j + "' placeholder='First Name'> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> Last Name </label> ";
html += " <input type='text' class='form-control LastName' name='LastName' id=' LastName" + j + "' placeholder=' Last Name'> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> Date of Birth </label> ";
html += " <label class='visually-hidden' for='DateofBirth'> Date of Birth</label> ";
html += " <input type='date' class='form-control DOB' name='DOB' id='DOB" + j + "'> ";
html += " </div> ";
html += " </div> ";
html += " </li> ";
html += " </li> ";
html += " </ul> ";
}
html += " </div> ";
html += " </div> ";
html += " </div> ";
html += " </div> ";
html += " </div> ";
}
$("#FrmContainer").append(html)
}
//
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}
The Script function with Sample static data I'm working with now(I want get them dynamically from the above form)
function Save() {
$('#create').prop('disabled', true);
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function(){return "Title:"+$(this).val();}).get();
var FNames = $("input[name='FirstName']").map(function(){return $(this).val();}).get();
var LNames = $("input[name='LastName']").map(function(){return $(this).val();}).get();
var DOBs = $("input[name='DOB']").map(function(){return "DOB:"+$(this).val();}).get();
//here I want to put them in array like `details[]` array below
setTimeout(function () {
let details=[];
details.push({
Title:"Mr.",
FirstName:"Person1 FN",
LastName:"Person1 LN",
DOB:"1990-05-20"
});
details.push({
Title:"Mrs.",
FirstName:"Person2 FN",
LastName:"Person2 LN",
DOB:"2001-06-18"
})
console.log(details);
var DataCarrier = {
Id: Id, //From Query string
PersonsDetails:details
};
$.ajax({
type: "POST",
url: "WebService.asmx/SavePersons",
data: JSON.stringify(DataCarrier),
contentType: "application/json",
dataType: "json",
success: function (data) {
try {
if (data != null) {
setTimeout(function () { window.location = "destinationPage.aspx?Id=" + Id; }, 500);
}
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}, 5000);
}
And the button
<input id="btnSave" class="btn btn-effect btn-book px-5" type="button" value="Continue" onclick="Save();" />
But I'm getting them as
[object Object],[object Object],[object Object],[object Object],[object Object]
I also tried .toString() but nothing changes, And console.log("FNs : "+json.stringify(FNs)); is throwing error.
How can I process these data as mentioned above before passing them to the backend? What I'm doing wrong? Is there a better way to do what I want achieve?
First step is to read the values from the inputs or select
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function() { return $(this).val(); }).get();
var FNames = $("input[name='FirstName']").map(function() { return $(this).val(); }).get();
var LNames = $("input[name='LastName']").map(function() { return $(this).val(); }).get();
var DOB = $("input[name='DOB']").map(function() { return $(this).val(); }).get();
Then split the values into array
//splitting the values into arrays
let TL = Titles.toString().split(',');
let FN = FNames.toString().split(',');
let LN = LNames.toString().split(',');
let BD = DOB.toString().split(',');
After that you can push them into the details[] array using for loop like this
let details = [];
for (var i = 0; i < FNames.length; i++) {
details.push({
Title: TL[i],
FirstName: FN[i],
LastName: LN[i],
DOB: BD[i],
TravllerType: TT[i]
});
}
console.log(JSON.stringify(details));
Note: if you console.log(details); you will find out that its object:Object stuff, to get around this, we stringify it.
finally incorprate all that into your SavePersons() function
function SavePersons() {
$('#create').prop('disabled', true);
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function () { return $(this).val(); }).get();
var FNames = $("input[name='FirstName']").map(function () { return $(this).val(); }).get();
var LNames = $("input[name='LastName']").map(function () { return $(this).val(); }).get();
var TravllerTypes = $("input[name='TravllerType']").map(function () { return $(this).val(); }).get();
var DOB = $("input[name='DOB']").map(function () { return $(this).val(); }).get();
//splitting the values into arrays
let TL = Titles.toString().split(',');
let FN = FNames.toString().split(',');
let LN = LNames.toString().split(',');
let TT = TravllerTypes.toString().split(',');
let BD = DOB.toString().split(',');
setTimeout(function () {
let details = [];
for (var i = 0; i < FNames.length; i++) {
details.push({
Title: TL[i],
FirstName: FN[i],
LastName: LN[i],
DOB: BD[i],
TravllerType: TT[i]
});
}
console.log(details);
var DataCarrier = {
Id: Id,
TravelersDetailsTT: details
};
$.ajax({
type: "POST",
url: "WebService.asmx/SavePersons",
data: JSON.stringify(DataCarrier),
contentType: "application/json",
dataType: "json",
success: function (data) {
try {
if (data != null) {
setTimeout(function () { window.location = "destinationPage.aspx?Id=" + Id; }, 5000);
}
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}, 5000);
}
it may not be the best answer but it works and I tested it. any improves are welcome. in the mean time I hope it helps.
I think the index of firstName and lastName in your array is identical so
var FirstNames = $("input[name='FirstName']")
.map(function(){return $(this).val();}).get();
var LastNames = $("input[name='LastName']")
.map(function(){return $(this).val();}).get();
var FN = FirstNames.map((FN,index) => {
return {{FirstName: FN, LastName: LastNames[index]}
})
It should be something like what you want
here I'm working with localstorage in javascript
here is my code for enter productDetails in the table using a form. when i'm enter productDetails in the table and refresh the page the entered data is in the table because of localStorage. but my problem is that when I refresh the page and again add new data so that newly added data is replaced with data which is added before refresh the page. and I want all my data instead of replacing
let productDetails = {
};
/**
* this function is for get the value from form
*/
function getValue() {
let id = document.getElementById('productId').value;
let partNo = document.getElementById('productNo').value;
let productName = document.getElementById('productName').value;
let size = getRadioValue();
let color = getCheckBoxValue();
let description = document.getElementById('description').value;
let date = document.getElementById('date').value;
let address = document.getElementById('address').value;
let companyName = document.getElementById('companyName').value;
return {
id, partNo, productName, size, color, description, date, address, companyName
};
}
/**
* function to insert data into table
*/
function insertion() {
let value = getValue();
let letter = value.productName[0];
if (!productDetails.hasOwnProperty(letter)) {
productDetails[letter] = [];
}
let object = {
weight: value.weight, id: value.id, partNo: value.partNo, productName: value.productName, size: value.size, color: value.color, description: value.description,
companyDetails: {
date: value.date,
address: value.address,
companyName: value.companyName
}
};
JSON.parse(window.localStorage.getItem('productDetails'));
productDetails[letter].push(object);
localStorage.setItem("productDetails", JSON.stringify(productDetails));
displayData();
message("");
}
/**
* this function display the data in table
*/
function displayData() {
objectArray = Object.values(productDetails);
display(objectArray);
}
/**
* function to display table
*/
function display() {
var result = JSON.parse(window.localStorage.getItem("productDetails"));
console.log(result)
messageTable(" ");
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><th colspan=7 >company Details</th><tr><th>weight</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th><th>Date</th><th>Address</th><th>Company name</th></tr>";
for (var key in result) {
for (var weight in result[key]) {
//let companyDetails = result[key][weight].companyDetails ? result[key][weight].companyDetails : { date: "", address: "", companyName: "" };
table += "<tr><td>" + key + "</td>";
table += "<td>" + result[key][weight].id + "</td>";
table += "<td>" + result[key][weight].partNo + "</td>";
table += "<td>" + result[key][weight].productName + "</td>";
table += "<td>" + result[key][weight].size + "</td>";
table += "<td>" + result[key][weight].color + "</td>";
table += "<td>" + result[key][weight].description + "</td>";
table += "<td>" + result[key][weight].companyDetails.date + "</td>";
table += "<td>" + result[key][weight].companyDetails.address + "</td>";
table += "<td>" + result[key][weight].companyDetails.companyName + "</td>";
}
} messageTable(table);
console.log(result)
}
What you need to do is add a check looking for the localstorage key for your data when the page loads, if the check is true then add the previous localstorage data to your productDetails object. This is the Example =>
window.onload = init;
var arr = [];
function init() {
if(localStorage.getItem("productDetails")) {
arr.push(JSON.parse(localStorage.getItem("productDetails")));
getValue(); /*Then Continue eg.Refer to a function*/
}
else {
getValue(); /*Do something eg.Refer to a function*/
}
}
The concept is when the page loads add a window.onload function to check whether the localStorage key "productDetails" exists. If the key exist then add/push the value stored by the key to the array arr in this example. If it does not exist then eg. Do something like => Refer to a function.
User specific infoProfile pic displayI fixed a ton of bugs I had before.
Goal: Dynamically display all signed up users with their names displayed under their profile pic.
What it does now: Dynamically displays all users(when you click it shows specific user info) and profile pics in seperate divs.
Image:Dynamic images displayed
Snippet:
const dbRef = firebase.database().ref();
const usersRef = dbRef.child('userInfo');
const userListUI = document.getElementById("userList");
usersRef.on("child_added", snap => {
let user = snap.val();
let $h3 = document.createElement("h3");
$h3.innerHTML = user.name;
$h3.setAttribute("child-key", snap.key);
$h3.addEventListener("click", userClicked)
userListUI.append($h3);
});
function userClicked(e) {
var userID = e.target.getAttribute("child-key");
const userRef = dbRef.child('userInfo/' + userID);
const userDetailUI = document.getElementById("userDetail");
userDetailUI.innerHTML = ""
userRef.on("child_added", snap => {
var $p = document.createElement("p");
$p.innerHTML = snap.key + " - " + snap.val()
userDetailUI.append($p);
});
}
var storage = firebase.storage();
var storageRef = storage.ref();
$('#List').find('tbody').html('');
var i = 0;
storageRef.child('users').listAll().then(function(result) {
result.items.forEach(function(imageRef) {
i++;
displayImage(i, imageRef);
});
});
function displayImage(row, images) {
images.getDownloadURL().then(function(url) {
// console.log(url);
let new_html = '';
// new_html += '<tr>';
new_html += '<td>';
// new_html += '</td>';
// new_html += '<td>';
new_html += '<img src= "' + url + '">';
new_html += '</td>';
// new_html += '</tr>';
new_html += row;
$('#List').find('tbody').append(new_html);
});
}
<table id="List">
<tbody>
</tbody>
</table>
<br><br>
<ul id="userList"></ul>
<div id="userDetail">
<p>
<strong class="detailName"></strong>
</p>
</div>
What I've done to try to fix:Googling, playing around with the display image function (tried moving the $('#List').find('tbody').append(new_html); below the 2nd to last });) add something to the new_html to display names but the images.getDownloadURL messes the other stuff I tried because if I add another function after or before it, I'll get an error because the images are stored in storage and the user info is in realtime database. Any pointers?
var userData = docRef.collection("userInfo");
usersRef.on("child_added", snap => {
let user = snap.val();
let $ul = document.createElement("ul");
$ul.innerHTML = user.name;
$ul.setAttribute("child-key", snap.key);
$ul.addEventListener("click", userClicked)
userListUI.append($ul);
});
function userClicked(e) {
var userID = e.target.getAttribute("child-key");
const imageRef = storageRef.child('users/' + userID);
const userRef = dbRef.child('userInfo/' + userID);
// window.location = 'profileview.html';
const userDetailUI = document.getElementById("userDetail");
userDetailUI.innerHTML = "";
userRef.on("child_added", snap => {
var $ul = document.createElement("ul");
$ul.innerHTML = snap.key + " - " + snap.val()
userDetailUI.append($ul);
});
}
I'm selecting values from my db in mysql and comparing them with values from JSON. I'm receiving the right results but since I'm using append the results shows up one by one, which looks like animation I would like to get them all at once and show some kind of loading icon while the loop is running, I've tried few different ways but nothing worked.
<?php $sql= "select a_id,b_id,res_a,res_b from betts_gr where u_id='".$u_id[0]."'";
$user_bets = mysqli_query($conn,$sql);
while($user_bets1 = mysqli_fetch_array($user_bets)){
?>
<script>
$(document).ready(function() {
var a_id = "<?php echo $user_bets1[0]?>";
.....
var car = [];
$.getJSON('http://api.football-api.com/2.0/matches?
comp_id = 1204 & from_date = '+today+' & to_date = '+plusmonth+' & Authorization ',
function(data) {
var html = "";
console.log(data);
$.each(data, function(index, value) {
var teama = value.localteam_name;
var teamb = value.visitorteam_name;
.......
function add(name, point) {
car.push({
teamb: teamb,
teama: teama,
form: form,
data: data,
teama_id: teama_id,
teamb_id: teamb_id,
a_res: a_res,
b_res: b_res
});
}
add(teama, teamb, data, form, teama_id, teamb_id, a_res, b_res);
});
for (var n = 0; n < car.length; n++) {
if (car[n].teama_id == a_id && car[n].teamb_id == b_id) {
html += "<tr><td><input type='hidden' name='aid" + n + "'
value = '"+car[n].teama_id+"' > < input type = 'hidden'
name = 'bid"+n+"'
value = '"+car[n].teamb_id+"' > " +
car[n].data +
"</td><td> " + car[n].teama + "</td><td>" + car[n].a_res + "-" +
car[n].b_res + "</td><td> " +
car[n].teamb + '</td><td> you predicted ->' + pred_resa + ' - ' + pred_resb +
'</tr>';
}
}
$(".message").append(html);
});
});
</script>
<?php } ?>
the example for using the Array.map and the template literals instead of the for loop and the plain string concat:
const isTargetTeam = item => item.teama_id == a_id && item.teamb_id == b_id;
const html = car.slice(0) // copy the array car
.filter(isTargetTeam)
.map((item, index) =>
`<tr>
<td>
<input type='hidden' name='aid${index}' value='${item.teama_id}'>
<input type='hidden' name='bid${index}' value='${item.teamb_id}'>
${item.data}
</td>
<td>
${item.a_res}-${item.b_res}
</td>
<td>
${item.teamb}
</td>
<td> you predicted -> ${pred_resa} - ${pred_resb}
</tr>`
).join('')
You should not mix PHP and Javascript like that. Currently this will result in X document.ready functions with X getJSON requests.
If you want to do the API requests from the local client, you should do ONE javascript function where you pass in the selected user_bets as an array. There are different possibilities to determine if all loadings have been finished: either counting up and checking after every callback if the max number is reached, or using Promises and Promise.all().
<script>
var user_bets = <?php echo json_encode($user_bets);?>;
$(document).ready(function () {
Promise.all(user_bets.map(function (id) {
return fetchFromApi(id);
})).then(function(array){
var html = "";
for(var i = 0; i < array.length; i++){
html += processData(array[i]);
}
$(".message").append(html);
});
});
function fetchFromApi(user_id) {
return new Promise(function (resolve, reject) {
$.getJSON()
.done(function (data) {
resolve(data);
})
.fail(function (error) {
reject(error);
});
});
}
function processData(data){
var html = '';
// do your html processing of a single api call here
return html;
}
</script>
Alternatively you can use CURL to do the API requests server-side already.
Thanks for advise I just realize I should get data with one request. I've passed the whole array to js and since I'm not sure how promise.all is working I did two for loops nested and is working fine, the only thing I still can't figure out how to check if the loops are finished so I could add loading icon while loop is running.
function add(name, point) {
car.push({ teamb : teamb, teama : teama, form:form, data:data, teama_id:teama_id,
teamb_id:teamb_id, a_res:a_res, b_res:b_res});
}
add(teama,teamb,data,form,teama_id,teamb_id,a_res,b_res);
});
for(var n=0;n<car.length;n++){
var taba = [<?php echo json_encode($at1)?>];
var tchild = taba[0];
for(var u=0;u<tchild.length;u++){
if(car[n].teama_id == tchild[u].localteam_id
&& car[n].teamb_id == tchild[u].visitorteam_id){
html += "<tr><td><input type='hidden' name='aid"+n+"'
value='"+car[n].teama_id+"'>
<input type='hidden' name='bid"+n+"'
value='"+car[n].teamb_id+"'>"
+car[n].data
+"</td><td> "+car[n].teama + "</td><td>"+ car[n].a_res
+ "-"+ car[n].b_res + "</td><td> "
+ car[n].teamb + '</td><td> you predicted -
>'+tchild[u].localteam_score +' - '+tchild[u].visitorteam_score +
'</td></tr>';
}
}
}
$(".message").append(html);
I have this code, and i need to do something with the first 2 ojects and then something else with the rest, but how?
I get data from <tr data-name='test' data-price='2' data-one='blabla' ...
data = $(this).data();
html_option = "<table id='Unit_Options_Table'>";
// Do some thing with the first 2
$.each(data, function(option, cost) { // Then do something with the rest
html_option += "<tr>" +
"<td class='Unit_Options_Name_td'>" + option + "</td>" +
"<td class='Unit_Options_Cost_td'>" + cost + "</td>" +
"</tr>";
});
html_option += "</table>";
You can’t really rely on the order of attributes. If you can change the markup, I’d recommend using JSON for your values:
<tr data-name="test" data-price="2" data-items='["blabla",…]'>
var name = this.dataset.name;
var cost = this.dataset.price;
var items = JSON.parse(this.dataset.items);
var option = $("<table>", { id: "Unit_Options_Table" });
// I’m not even sure where the loop belongs here
option.append(
$("<tr>").append(
$("<td>", { class: "name", text: name }),
$("<td>", { class: "cost", text: cost })
)
);
If not that, at least pick better names than one, two, etc. – you’re making it about as hard on yourself as possible by doing that.
In your specific situation as clarified in the comments, I’d do this:
<tr data-name="bla" data-cost="3" data-items='[{"name":"test","cost":20},…]'>
var data = $(this).data();
var items = $.parseJSON(data.items);
var option =
$("<table>", { id: "Unit_Options_Table" })
.append(
$("<tr>").append(
$("<th>", { text: data.name }),
$("<th>", { text: data.cost })
)
)
.append(
$.map(items, function(item) {
return $("<tr>").append(
$("<td>", { text: item.name }),
$("<td>", { text: item.cost })
);
})
);
Don't use .each, you'll find it much easier.
doSomething(data[0], data[1]);
for (var i = 2; i < data.length; ++i) {
doSomethingElse(data[i]);
}
Forcing yourself to use a convenience function isn't very convenient...
Shouldn´t
option
be the index if you are iterating over an array ?
so it should be as simple as
$.each(data, function(option, cost) {
if(option < 2){
//do something with first two
}else{
html_option += "<tr>" +
"<td class='Unit_Options_Name_td'>" + option + "</td>" +
"<td class='Unit_Options_Cost_td'>" + cost + "</td>" +
"</tr>";
}
});