I am looking to post back using Jquery (Java, Spring-Data Server side). I am looking to pass back multiple objects while using dynamic input fields on client side.
Server side service can handle saving multiple TimeOffRequests as an Itterable List. However, With having 2 input fields tied to the object I am struggling to format the data properly. Currently will return 4 objects in the array vs 2 Any help would be greatly appreciated
HTML:
<div class="widget-body no-padding">
<div class="smart-form">
<fieldset>
<div id = wrapper>
<div class="row" id="addInput" >
<section class="col col-4">
<label class="input"> <i class="icon-append fa fa-calendar"></i>
<input type="date" name="startDate" id="startDate" placeholder="Request Date" class="hasDatepicker">
</label>
</section>
<section class="col col-2">
<label class="input"><i class="icon-append fa fa-clock-o"></i>
<input min="0" max="8" type="number" name="hour" id="hour" placeholder="Hours">
</label>
</section>
<section class="col col-2">
<a id="addField" title="Add More Fields" class="btn btn-primary" onclick="addInput('wrapper');"> + </a>
</section>
</div>
</div>
<section>
<label class="textarea"> <i class="icon-append fa fa-comment"></i>
<textarea rows="5" name="comment" placeholder="Notes"></textarea>
</label>
</section>
</fieldset>
<footer>
<button onclick="submitTimeOffRequest()" class="btn btn-primary">
Submit
</button>
</footer>
</div>
JS Submit
function submitTimeOffRequest(){
var timeoffRequests = [];
$("input[class = ptoDate ]").each(function () {
var date = $(this).val();
$("input[class= ptoHours]").each(function () {
var hours = $(this).val();
item = {};
item ["date"] = date;
item ["hours"] = hours;
timeoffRequests.push(item);
});
});
$.ajax({
contentType: 'application/json',
type: "post",
data: JSON.stringify(timeOffRequests),
url: "/api/timeoff/" + masterEngId,
async: true,
dataType: "json",
success: function() {
location.reload(true);
},
error: function(){
}
})}
}
JS Dynamically add input fields
var counter = 1;
function addInput(divName) {
var dateIdString = "startDate" + counter;
var hourIdString = "hour" + counter;
console.log(dateIdString);
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='row'>" +
"<section class='col col-4'> " +
"<label class='input'><i class='icon-append fa fa-calender'>" +
"</i> <input class = 'ptoDate' type='date' name="+dateIdString+" id="+dateIdString+" placeholder='Request Date'</input> " +
"</label> " +
"</section>" +
"<section class='col col-2'>" +
"<label class='input'><i class='icon-append fa fa-clock-o'></i>" +
"<input type='number' class='ptoHours' name="+hourIdString+" id="+hourIdString+" placeholder='Hours'>" +
"</label>" +
"</section>" +
"<section class='col col-2'><a id='removeField' title='Remove Field' class='btn btn-danger' onclick='removeDiv()'> x </a> " +
"</section> " +
"</div>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
Related
Codepen https://codepen.io/mehmetmasa-the-selector/pen/RwBQbOr
When I click the button, I add a new field. One of the added fields (radio button) needs to be selected. But since the user can add/delete, I can't give the value value.
HTML Code
<div id="answer">
<div class="form-group d-flex">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input trueAnswer" type="radio" name="trueAnswer">Doğru Cevap </label>
</div>
<input class="form-control answer" type="text" placeholder="Cevabı Yazınız">
<button class="btn btn-primary ml-3 col-md-1" type="button" id="addAnswer">Yeni Cevap</button>
</div>
</div>
JS Code
$('#addAnswer').on('click', function() {
$('<div class="form-group d-flex">' +
'<div class="form-check">' +
'<label class="form-check-label">' +
'<input class="form-check-input trueAnswer" type="radio" name="trueAnswer">Doğru Cevap' +
'</label>' +
'</div>' +
'<input class="form-control answer" type="text" placeholder="Cevabı Yazınız">' +
'<button class="btn btn-danger ml-3 col-md-1 deleteAnswer" type="button" >Cevabı Sil</button>' +
'</div>').appendTo('#answer');
});
$('#addQuestion').on('click', function() {
let answer = [];
$('#answer .form-group').map(function(i, val) {
if ($(val).find('.answer').val().length > 0)
answer.push({
name: $(val).find('.answer').val(),
trueAnswer: $(val).find('.trueAnswer').val()
});
});
let categoryID = $('#category').val();
let question = $('#question').val();
let questionNo = $('#questionNo').val();
let colorpicker = $('#colorpicker').val();
let formData = new FormData();
formData.append("categoryID", categoryID);
formData.append("question", question);
formData.append("questionNo", questionNo);
formData.append("colorpicker", colorpicker);
for (var i = 0; i < answer.length; i++) {
formData.append('answer' + [i], answer[i].name);
formData.append('answer' + [i], answer[i].trueAnswer);
}
How can I find which answer the user chose?
I have tried numerous ways of editing a task added to the task list, but the code is not functioning. Any clue where the error is or if there is a simpler way to add an edit task button? I want to avoid simply making all the list items contenteditable=true, but rather want to be able to click an edit button to edit first. When I try to add an edit button to the '//call append method on $todoList' line, the button functions as a done/remove from list button, instead of working as an edit button to alter the list item.
var $addButton = $(".btn-primary");
var $removeButton = $(".btn-danger");
var $editButton = $(".btn-primary");
var $todoList = $(".uncomplete");
var $doneList = $(".completed");
//Take Text Input and Add <li> to To Do List
$addButton.on("click", function(){
//Creating object Variables
var $sort = $(".sort").val();
var $newTask = $(".newTask").val();
var $taskDescr = $(".taskDescr").val();
var $taskDate = $(".taskDate").val();
// var $category= $(".category").val();
var $category= $("input[type='radio'][name='category']:checked").val();
//var $importance = $("input[type='checkbox'][name='importance']:checked").val();
var $importance = $('<input type="checkbox" name="importance"/>').val();
var $newTaskString = $sort + ", " + $taskDescr + ", " + $newTask + ", " + $taskDate + ", " + $category + ", " + $importance + " ";
var $todoList = $(".uncompleted");
//call append method on $todoList
$todoList.append("<li>" + $newTaskString + "<button><span> Done</span></button><button><span> Remove</span></button></li>").addClass("todo");
//add styles to button added to DOM by append
var $span = $(".todo button span");
var $button = $(".todo button");
$button.addClass("btn btn-success");
$span.addClass("glyphicon glyphicon-ok");
$("input").val("");
})
//Edit existing task
//var id_counter
//var $task = $("<tr class='taskList' id='"+ id_counter +"'>")
//function myEdit(){
//}
$(function(){
$(document).on('click','.my-row .col-a3',function(){
let editable = $(this).prev('.col-a2').attr('contenteditable');
if(editable){
$(this).text('Edit');
$('.col-a2').css({'border': ''});
$(this).prev('.col-a2').removeAttr('contenteditable');
}
else{
$(this).text('Save');
$('.col-a2').css({'border': '1px solid'});
$(this).prev('.col-a2').attr('contenteditable','true');
}
})
});
<div class="list-wrap" contenteditable="false">
<div class="list-inner-wrap">
<h2 class="title">ToDo List</h2>
<h3 class="title">Add Task</h2>
<!--<h4>Task Name</h4>-->
<label for="sort">Sort Order:</label><input type="text" class="sort" name="sort" id="sort" value="" placeholder="A,B,C,etc.">
<br>
<label for="task-name">Task Name:</label><input type="text" class="newTask" name="task-name" id="task-name" value="" placeholder="My task...">
<br>
</form>
<br>
<button class="btn btn-primary">
<span class="glyphicon glyphicon-plus"> Add</span>
</button>
<!--Edit task button-->
<button class="edit" onclick="myEdit()">Edit Task</button>
<p id="demoedit"></p>
<br>
<div class="my-row">
<h3 class="title">To Do</h2>
<h6><i>Click task item to edit or modify</i></h6>
<!--Change color of editable task -->
<div id='div' contenteditable='false' oninput='change()'>
<ul class="uncompleted" contenteditable="false" id="id01">
<div class="col-a2">
<li>Need to be completed task
<button class="btn btn-success" a href="#" onclick="allUsersDiv()">
<span class="glyphicon glyphicon-ok"> Done</span>
</button>
<button class="btn btn-danger">
<span class="glyphicon glyphicon-remove"> Remove</span></button>
<!-- <div class="col-a3"><button>Edit</button>
</div>-->
<br>
</li></ul></div></div>
</div></div></div>
<br><br><br><br><br><br><br><br><br>
<h3 class="title">Completed Tasks</h2>
<ul class="completed" contenteditable="false">
<li>Completed Task<button class="btn btn-danger">
<span class="glyphicon glyphicon-remove"> Remove</span>
</button></li>
</ul>
</div>
<br>
<br>
I am trying to make a travel calculator, here is the HTML, which all works fine with the CSS styling I have attached to it. No issues here.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Travel Calculator 2.0</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<div class="container-fluid">
<div id ="travel_calculator" class="row row-eq-height">
<div id ="common_and_results" class="col-sm-4 order-sm-4 pb-5 pt-3">
<div id ="results" class="card mb-3">
<img src="https://via.placeholder.com/1920x1080" alt="placeholder" class="card-img">
<div class="card-img-overlay">
<h1 class="card-title text-white h2">Change Options</h1>
</div>
<div class="col-12">
<div class="card bg-info mb-3">
<div class="form-group card-body">
<label class="h6" for="pay_rate">Pay Rate (assuming 8hr/day)</label>
<div id="pay-rate-group" class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-money"></i>
</span>
<input class="form-control" name="pay_rate" type="number"
id="pay_rate" max="80" min="8" step="1" value="15">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="travelers">Travelers</label>
<div id="travelers-group" class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-user" aria-hidden="true"></i>
</span>
<input class="form-control" name="travelers" type="number"
id="travelers" max="5" min="1" step="1" value="1">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="car" class="col-sm-4 order-sm-1 pb-5 pt-3">
<div class="card mb-3">
<img src="images/pexels-photo-car.jpg" alt="car photo" class="card-img">
<div class="card-img-overlay">
<h1 class="card-title text-white h2">By Car</h1>
</div>
</div>
<div class="col-12">
<div class="card bg-info mb-3">
<div class="form-group card-body">
<label class="h6" for="distance">Distance</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-car" aria-hidden="true"></i>
</span>
<input class="form-control" name="distance" type="number"
id="distance" max="5000" min="50" step="10" value="500">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="mpg">MPG</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-tint" aria-hidden="true"></i>
</span>
<input class="form-control" name="mpg" type="number"
id="mpg" max="100" min="10" step="1" value="23">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="ppg">PPG</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-credit-card" aria-hidden="true"></i>
</span>
<input class="form-control" name="ppg" type="number"
id="ppg" max="20" min=".10" step=".10" value="2.50">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="hotel">Hotel</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-bed"></i>
</span>
<select class="custom-select form-control" name="hotel" id="hotel">
<option value="100">Economy</option>
<option value="200">Business</option>
<option value="300">Luxury</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="plane" class="col-sm-4 order-sm-1 pb-5 pt-3">
<div class="card mb-3">
<img src="images/pexels-photo-plane.jpg" alt="plane photo" class="card-img">
<div class="card-img-overlay">
<h1 class="card-title text-white h2">By Air</h1>
</div>
</div>
<div class="col-12">
<div class="card bg-info mb-3">
<div class="form-group card-body">
<label class="h6" for="ticket">Ticket</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-credit-card"></i>
</span>
<input class="form-control" name="ticket" type="number"
id="ticket" max="3000" min="50" step="50" value="500">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="bags">Bags</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-briefcase" aria-hidden="true"></i>
</span>
<input class="form-control" name="checked_bags" type="number"
id="checked_bags" max="2" min="1" step="1" value="1">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="update-row" class="row">
<div id="update-column" class="col-12">
<button id="update_button" class="btn btn-primary btn-block">Calculate</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="travel-calculator.js"></script>
</body>
</html>
The JavaScript is supposed to display a car or plane photo on top of the placeholder in the "change options" column alongside attached prices and instructions of whether to take a car or plane. But when I press the calculate button, literally nothing happens.
$(function () {
"use strict";
var pay_rate = 0;
var travelers = 0;
var distance = 0;
var hotel = 0;
var MAX_MILES = 300; // assume driving only 300 mi/day
var WORK_HOURS = 8; // assume 8 hours of work/day
function getCommonCosts() {
pay_rate = Number($("#pay_rate").val());
console.log("pay_rate " + pay_rate);
travelers = Number($("#travelers").val());
console.log("travelers " + travelers);
}
function getCarCosts() {
var mpg = Number($("#mpg").val());
console.log("mpg " + mpg);
var ppg = Number($("#ppg").val());
console.log("ppg " + ppg);
distance = Number($("#distance").val());
console.log("distance " + distance);
hotel = Number($("#hotel").val());
console.log("hotel " + hotel);
var gallons = distance / mpg;
console.log("gallons " + gallons);
var mileage_cost = gallons * ppg;
console.log("mileage_cost " + mileage_cost);
var by_car_days = Math.ceil(distance / MAX_MILES);
console.log("by_car_days " + by_car_days);
var by_car_hotel = Math.floor(by_car_days) * hotel;
console.log("by_car_hotel " + by_car_hotel);
var by_car_pay =
Math.ceil(by_car_days) * WORK_HOURS * pay_rate * travelers;
console.log("by_car_pay " + by_car_pay);
var total = mileage_cost + by_car_hotel + by_car_pay;
console.log("(car) total " + total);
return total;
}
function getFlightCosts() {
var cost_per_bag = 50;
console.log("cost_per_bag " + cost_per_bag);
var flight_cost = Number($("#flight_cost").val());
console.log("flight_cost " + flight_cost);
var checked_bags = Number($("#checked_bags").val());
console.log("checked_bags " + checked_bags);
var by_flight_pay = WORK_HOURS * pay_rate * travelers;
console.log("by_flight_pay " + by_flight_pay);
var total = (flight_cost * travelers) +
(checked_bags * cost_per_bag) + by_flight_pay;
console.log("(plane) total " + total);
return total;
}
function showResult(cost1, cost2) {
var result_text = "";
if (cost1 < cost2) {
$("results img").attr(
"src",
"images/pexels-photo-car.jpg"
);
result_text = "Road Trip!";
} else {
$("results img").attr(
"src",
"images/pexels-photo-plane.jpg"
);
result_text = "Book a Flight!";
}
result_text = "<br/>";
cost1 = Math.round(cost1 * 100) / 100;
cost2 = Math.round(cost2 * 100) / 100;
result_text += "Car: $" + cost1 + "<br/>";
result_text += "Flight: $" + cost2 + "<br/>";
$("results h1").html(result_text);
}
function updateResults() {
getCommonCosts();
var car_costs = getCarCosts() || 0;
var flight_costs = getFlightCosts || 0;
showResult(car_costs, flight_costs);
}
$("update_button").focus();
$("update_button").click(function () {
updateResults();
});
});
Post-edit javascript:
$(function () {
"use strict";
var pay_rate = 0;
var travelers = 0;
var distance = 0;
var hotel = 0;
var MAX_MILES = 300; // assume driving only 300 mi/day
var WORK_HOURS = 8; // assume 8 hours of work/day
function getCommonCosts() {
pay_rate = Number($("#pay_rate").val());
console.log("pay_rate " + pay_rate);
travelers = Number($("#travelers").val());
console.log("travelers " + travelers);
}
function getCarCosts() {
var mpg = Number($("#mpg").val());
console.log("mpg " + mpg);
var ppg = Number($("#ppg").val());
console.log("ppg " + ppg);
distance = Number($("#distance").val());
console.log("distance " + distance);
hotel = Number($("#hotel").val());
console.log("hotel " + hotel);
var gallons = distance / mpg;
console.log("gallons " + gallons);
var mileage_cost = gallons * ppg;
console.log("mileage_cost " + mileage_cost);
var by_car_days = Math.ceil(distance / MAX_MILES);
console.log("by_car_days " + by_car_days);
var by_car_hotel = Math.floor(by_car_days) * hotel;
console.log("by_car_hotel " + by_car_hotel);
var by_car_pay =
Math.ceil(by_car_days) * WORK_HOURS * pay_rate * travelers;
console.log("by_car_pay " + by_car_pay);
var total = mileage_cost + by_car_hotel + by_car_pay;
console.log("(car) total " + total);
return total;
}
function getFlightCosts() {
var cost_per_bag = 50;
console.log("cost_per_bag " + cost_per_bag);
var flight_cost = Number($("#flight_cost").val());
console.log("flight_cost " + flight_cost);
var checked_bags = Number($("#checked_bags").val());
console.log("checked_bags " + checked_bags);
var by_flight_pay = WORK_HOURS * pay_rate * travelers;
console.log("by_flight_pay " + by_flight_pay);
var total = (flight_cost * travelers) +
(checked_bags * cost_per_bag) + by_flight_pay;
console.log("(plane) total " + total);
return total;
}
function showResult(cost1, cost2) {
var result_text = "";
if (cost1 < cost2) {
$("#results img").attr(
"src",
"images/pexels-photo-car.jpg"
);
result_text = "Road Trip!";
} else {
$("#results img").attr(
"src",
"images/pexels-photo-plane.jpg"
);
result_text = "Book a Flight!";
}
result_text = "<br/>";
cost1 = Math.round(cost1 * 100) / 100;
cost2 = Math.round(cost2 * 100) / 100;
result_text += "Car: $" + cost1 + "<br/>";
result_text += "Flight: $" + cost2 + "<br/>";
$("results h1").html(result_text);
}
function updateResults() {
getCommonCosts();
var car_costs = getCarCosts() || 0;
var flight_costs = getFlightCosts() || 0;
showResult(car_costs, flight_costs);
}
$("#update_button").focus();
$("#update_button").click(function () {
updateResults();
});
});
This line:
$("results img")
This is not targeting an element. You need the pound sign to target that ID:
$("#results img")
So it should be:
$("#results img").attr(
"src",
"images/pexels-photo-car.jpg"
);
Please note, your listeners are also not targeting by ID. They all need to prefix with # for ID targeting, or . for class
Also, I think you have a typo:
var flight_costs = getFlightCosts || 0;
should probably be
var flight_costs = getFlightCosts() || 0;
But ultimately, your console will guide you through issues better than an eyeball audit. From a glance, those 2 things are going to be problematic. I can update this answer if more insight is posted after these are fixed.
I have made contact list app which displays contact details. By Default it shows 2 contact details.
In index.html I have made 2 functions called showContacts() and editContact(id).
I am dynamically populating div tags i.e editcontact & contactlist in index.html
When I click on edit button it should show 3 input elements to take input from user and one submit button I tried to implement it (see code below) but only search bar disappear's and only default contacts are shown which should not be shown and it should display editing form.
var array = [];
function Person(fullName, number, group) {
this.fullName = fullName;
this.number = number;
this.group = group;
array.push(this);
}
Person.prototype.getFullName = function() {
return this.fullName + ' ' + this.number + ' ' + this.group;
}
var p1 = new Person("Jonathan Buell", 5804337551, "family");
var p2 = new Person("Patrick Daniel", 8186934432, "work");
console.log(array);
document.getElementById("contactlist").innerHTML = '';
function showContacts() {
for (var i in array) {
var id = i;
contactlist.innerHTML +=
`
<ul>
<div>
<p>Name: ` + p1.fullName + `</p>
<p>Number: ` + p1.number + `</p>
<p>Group: ` + p1.group + `</p>
<button type="button" class="btn btn-warning" onclick="editContact(` + id + `)">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
`
}
}
showContacts();
function editContact(id) {
document.getElementById("search").style.display = 'none';
document.getElementById("contactList").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
`<div>
<input type="text" placeholder="Name here" id="nameInput2" value="` + array[id].fullName + `">
<input type="tel" placeholder="Number here" id="numberInput2" value="` + array[id].number + `">
<input type="text" placeholder="Group Here" id="groupInput2" value="` + array[id].group + `">
<button type="button" class="btn btn-success">Submit</button>
</div>`;
}
<div class="header">
<div id="dropdown">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Sort by Group
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>All</li>
<li>Work</li>
<li>Family</li>
</ul>
</div>
</div>
<div class="title">
<h2>All Contacts</h2>
</div>
<div class="button" id="addButton">
<p>
<a href="#">
<span class="glyphicon glyphicon-plus-sign"></span>
</a>
</p>
</div>
</div>
<div id="search">
<form>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
</div>
<div id="contactlist">
</div>
<div id="editcontact">
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
screenshots :
1) Before on click editContact :
2) After onclick editContact :
Live demo can be seen here :
https://jsfiddle.net/w2hoqmts/
A couple of things.
You made a typo with your contactlist in your html (should be contactList).
In your loop for showContacts you are setting id as index and should be like
function showContacts() {
for (var i in array) {
var id = array[i].number;
document.getElementById("contactList").innerHTML +=
'<ul><div><p>Name: ' + array[i].fullName + '</p><p>Number: ' + array[i].number + '</p><p>Group: ' + array[i].group + '</p>' +
'<button type="button" class="btn btn-warning" onclick="editContact(' + id + ')">Edit</button>' +
'<button type="button" class="btn btn-danger">Delete</button>' +
'</div>';
}
}
Your editContact method is using the id as an index (as previous), which is wrong. You could do something like this instead (see code below). I filter the array with people based on the unique id provided from the link when you click edit.
function editContact(id) {
var obj = array.filter(function (ele) {
console.dir(ele);
if (ele.number === id) return ele;
});
console.dir(obj);
document.getElementById("search").style.display = 'none';
document.getElementById("contactList").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
'<div>'+
'<input type="text" placeholder="Name here" id="nameInput2" value="'+ obj[0].fullName + '">'+
'<input type="tel" placeholder="Number here" id="numberInput2" value="' + obj[0].number + '">' +
'<input type="text" placeholder="Group Here" id="groupInput2" value="' + obj[0].group + '">' +
'<button type="button" class="btn btn-success">Submit</button>'+
'</div>';
}
I've made a updated fiddle based on your own
https://jsfiddle.net/w2hoqmts/3/
Following changes should be made in editContact() and showContacts() function.
function showContacts(){
for(var i in array){
var id = i;
contactlist.innerHTML +=
`
<ul>
<div>
<p>Name: `+ p1.fullName +`</p>
<p>Number: `+ p1.number +`</p>
<p>Group: `+ p1.group +`</p>
<button type="button" class="btn btn-warning" onclick="editContact(`+ id +`)">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
`
}
}
showContacts();
function editContact(id) {
document.getElementById("search").style.display = 'none';
document.getElementById("contactlist").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
`<div>
<input type="text" placeholder="Name here" id="nameInput2" value="`+array[id].fullName+`">
<input type="tel" placeholder="Number here" id="numberInput2" value="`+array[id].number+`">
<input type="text" placeholder="Group Here" id="groupInput2" value="`+array[id].group+`">
<button type="button" class="btn btn-success">Submit</button>
</div>`;
}
this is my first time on here, Im trying to show this json file https://eu.mc-api.net/v3/uuid/(there input) as a formatted result on my pageso it only displays formatted UUID and name but I'm struggling as I'm not great at JS etc.
Like:
Name: (There name)
UUID: (there full UUID)
This is what I have so far:
HTML CODE
<div id="section">
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow- -2dp">
<!-- Simple Textfield -->
<form action="#">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="text" id="IGN">
<label class="mdl-textfield__label" for="IGN">Enter IGN</label>
<!-- Primary-colored flat button -->
<div id="id01"> </div>
<br>
<input type="button" class="mdl-button mdl-js-button mdl-button--primary" value="Show" onClick=" var jsonget = 'https://eu.mc-api.net/v3/uuid/' + document.getElementById('IGN').value; headrun();">
</form>
</section>
</div>
JS CODE
function headrun () {
$.getJSON( 'https://eu.mc-api.net/v3/uuid/' + document.getElementById('IGN').value, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"full_uuid": "my-new-list",
"name": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
document.getElementById('username').innerHTML = IGN;
Try the following code
<div id="section">
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow- -2dp">
<!-- Simple Textfield -->
<form action="#">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="text" id="IGN">
<label class="mdl-textfield__label" for="IGN">Enter IGN</label>
<!-- Primary-colored flat button -->
<script>
function headrun() {
$.getJSON('https://eu.mc-api.net/v3/uuid/' + document.getElementById('IGN').value, function(data) {
$("#details ul").append('<li>Name: ' + data.name + '</li>').append('<li>UUID: ' + data.full_uuid + '</li>');
});
}
</script>
<div id="id01"> </div>
<br>
<input type="button" class="mdl-button mdl-js-button mdl-button--primary" value="Show" onClick="headrun();">
<div id="details">
<ul>
</ul>
</div>
</form>
Here's the JSFiddle
You need to do something like this:
$.getJSON( 'https://eu.mc-api.net/v3/uuid/' + $('#IGN').val(), function(data){
var items = [];
Object.keys(data).forEach(function(key) {
items.push( "<li id='" + key + "'>" + data[key] + "</li>" );
});
});