how do i display website comments above the last posted comment - html

hi on my website i've a comment box,
everytime i post a comment it get posted below the last comment
my question is: how do i place new comments on top of the old ones.
website: kru.run
This is my full code right now,
<textarea id="title1" type="text " rows="1" cols="15" onkeyup="Allow()" placeholder="username"></textarea>
<textarea id="title" type="text " rows="3" cols="125" onkeyup="Allow()" placeholder="write a comment..."></textarea>
<input type="submit" value="Send" onclick="insert()" style="width:50px;" /></form>
</div>
<div id="display"></div>
<script type="text/javascript">
var titles = [];
var titleInput = document.getElementById("title");
var titleInput1 = document.getElementById("title1");
var messageBox = document.getElementById("display");
function Allow() {
if (!user.title.value.match(/[a-zA-Z]$/) && user.title.value != "") {
user.title.value = "";
alert("Please Enter only alphabets");
}
window.location.reload()
}
function insert() {
titles.push(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
function clearAndShow() {
titleInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += " " + titles.join("<br/> ") + "<br/>";
}
</script>
</div>
</div>
</div>
<br><br>
specifically
i think the insert function is the problem
what can i use instead of push?
function insert () {
titles.push(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}

try:
function insert () {
titles.unshift(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
to insert as first item.

Related

How to edit array value using jquery?

I am trying to edit array values using jquery. here is what I did.
From a modal, everytime I click the "Add item" button it will push values to an array and just append the data to a table
var iteminfo = {
"row": 'row' + cnt,
"make": make,
"body": body,
"cabin": cabin,
"horsepower": horsepower,
"wheels": wheels,
"chassis": chassis,
"engine": engine,
"remarks": remarks,
"shipmenttag": shipmenttag
};
trucksarray.push(iteminfo);
//append to table:
$("#truckstable > tbody").prepend(<tr><td>.....</td></tr>);
and my html table looks like this:
now I am able to delete a table row and the corresponding data from the array with this code:
//removing the table row
$("#truckstable").on('click', '.remrow', function () {
var id = $(".remrow").attr("id");
$(this).parent().parent().remove();
removeitem(id)
});
//removing array item
function removeitem(row) {
const itemToRemoveIndex = trucksarray.findIndex(function (item) {
return item.row === row;
});
if (itemToRemoveIndex !== -1) {
trucksarray.splice(itemToRemoveIndex, 1);
}
toastr.warning('Item removed!');
}
Now, my problem is, If I click the edit button a modal should popup and be able to edit the selected item value , the table data and the array values as well? Any idea?
You can give data-* to your edit button i.e : data-id="row1"..etc then on click of this button get the data-id value and use filter to filter the JSON Array already created and get only data where row == data-id.
Now , once you got the array values put this values inside the input-box of modal using .val("yourfromarray"). Then, onclick of save button get the value from input box and loop through your JSON Array and update value of array with new values.Lastly add these updated value inside trs.
Demo Code :
var cnt = 0;
var trucksarray = [];
$('#BtnAddTruck').on('click', function() {
var make = $('#tmake').val();
var body = $('#tbody').val();
var cabin = $('#tcabin').val();
var horsepower = $('#thorsepower').val();
var wheels = $('#twheels').val();
var chassis = $('#tchassis').val();
var engine = $('#tengine').val();
var remarks = $('#tremarks').val();
var shipmenttag = 'Truck';
cnt = cnt + 1;
var iteminfo = {
"row": 'row' + cnt,
"make": make,
"body": body,
"cabin": cabin,
"horsepower": horsepower,
"wheels": wheels,
"chassis": chassis,
"engine": engine,
"remarks": remarks,
"shipmenttag": shipmenttag
};
trucksarray.push(iteminfo);
//added here `id` to tr and `data-id` to edit button
$("#truckstable > tbody").
prepend("<tr id='trow" + cnt + "'>" +
"<td>" + make + " " + body + " " + cabin + " " + horsepower + " " + wheels +
"</td>" +
"<td>" + chassis + "</td>" +
"<td>" + engine + "</td>" +
"<td>" + remarks + "</td>" +
"<td>" +
" <button class='btn-primary edit' data-toggle='modal' data-target='#myModal' data-id='row" + cnt + "'>Edit</button>" +
" <button class='remrow btn-danger' id='row" + cnt +
"'>delete</button>" +
"</td>" +
"</tr>"
);
//clearmodalinput();
$(".empty_k input").val("");
//toastr.info('Item added!');
console.log(trucksarray)
});
var id;//delcare this globally
//on click of edit
$(document).on('click', '.edit', function() {
id = $(this).data('id');//get id
console.log(id)
//filter json array and get value only where match
var trucks = $(trucksarray)
.filter(function(i, n) {
return n.row === id;
});
//put value inside input in modal
$('.make').val(trucks[0].make);
$('.body').val(trucks[0].body);
$('.cabin').val(trucks[0].cabin);
$('.horsepower').val(trucks[0].horsepower);
$('.wheels').val(trucks[0].wheels);
$('.chassis').val(trucks[0].chassis);
$('.engine').val(trucks[0].engine);
$('.remarks').val(trucks[0].remarks);
});
//click on save button
$(".save").click(function() {
//loop through array
$(trucksarray).each(function() {
if (this.row == id) {
//creplace value inside array
this.horsepower = $('.horsepower').val();
this.make = $('.make').val();
this.remarks = $('.remarks').val();
this.engine = $('.engine').val();
this.chassis = $('.chassis').val();
this.cabin = $('.cabin').val();
this.body = $('.body').val();
this.wheels = $('.wheels').val();
return false;//got it stop loop
}
});
replace_values(); //replace table datas
})
function replace_values() {
//get values
var make = $('.make').val();
var body = $('.body').val();
var cabin = $('.cabin').val();
var horsepower = $('.horsepower').val();
var wheels = $('.wheels').val();
var chassis = $('.chassis').val();
var engine = $('.engine').val();
var remarks = $('.remarks').val();
//replace trs values
$("#t" + id).html("<td>" + make + " " + body + " " + cabin + " " + horsepower + " " + wheels +
"</td>" +
"<td>" + chassis + "</td>" +
"<td>" + engine + "</td>" +
"<td>" + remarks + "</td>" +
"<td>" +
" <button class='btn-primary edit' data-toggle='modal' data-target='#myModal' data-id='" + id + "'>Edit</button>" +
" <button class='remrow btn-danger' id='" + id +
"'>delete</button>" +
"</td>")
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="empty_k">
<input type="text" id="tmake">
<input type="text" id="tbody">
<input type="text" id="tcabin">
<input type="text" id="thorsepower">
<input type="text" id="twheels">
<input type="text" id="tchassis">
<input type="text" id="tengine">
<input type="text" id="tremarks">
<button id="BtnAddTruck">Add</button>
</div>
<div class="table-responsive">
<table class="table table-bordered" id="truckstable">
<thead>
<tr>
<th scope="col">Description</th>
<th scope="col">Chassis</th>
<th scope="col">Engine</th>
<th scope="col">Remarks</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Edit..</p>
tmake : <input type="text" class="make"><br/> tbody : <input type="text" class="body"> <br/>tcabin : <input type="text" class="cabin"> <br/>thorsepower :<input type="text" class="horsepower"> <br/>twheels : <input type="text" class="wheels"><br/> tchassis :
<input type="text" class="chassis">
<br/> tengine :<input type="text" class="engine"><br/> tremarks : <input type="text" class="remarks">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default save" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

JavaScript id= to name= in a form

A have a JavaScript that handles localisation.
That gives me a
Position: <input type="text" id="Position1" name="Position1" value="">
This works, and i get the current position on the webpage.
Now, I want to have that position in a form and give it to my SQL by a php script. The php works.
I hva tried:
<input type="hidden" name="poss" id="Position1">
and I know this does not work.
But how do I do it? How do I convert from id= to name= ??
Script:
<script>
window.onload = function(){
var x = document.getElementById('Position1');
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.value = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.value = "" + position.coords.latitude + "," + position.coords.longitude;
}
getLocation();
};
</script>
Position: <input type="text" id="Position1" name="Position1" value="">
<input type="hidden" name="poss" id="Position1">
<input type="submit" style="height:40px;width:350px" />
</form>
try with document.getElementsByName('poss')[0].value = "" + position.coords.latitude + "," + position.coords.longitude; it should work

Validation from submitting in Apps Script

Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,
In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.

Detecting keyboard keys input

Currently am having a form which detects the user input text and prints the respective text,but my issue is if user want to input as ctrl key how can i accomplish that
For example :
If user presses key a it will get displayed,but at the same time if user press cntrl key it should also get displayed.
Fiddled here.
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="">
<p>Choose your control</p>
<p>Option : <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
Thanks
Here is you answer for control key detect with angular JS:
angular.module("mainModule", [])
.controller("mainController", function ($scope)
{
// Initialization
$scope.onKeyDownResult = "";
$scope.onKeyUpResult = "";
$scope.onKeyPressResult = "";
// Utility functions
var getKeyboardEventResult = function (keyEvent, keyEventDesc)
{
return keyEventDesc + " (keyCode: " + (window.event ? keyEvent.keyCode : keyEvent.which) + ")";
};
// Event handlers
$scope.onKeyDown = function ($event) {
if($event.keyCode === 17)
{
$scope.name += " ctrl ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else if($event.keyCode === 16)
{
$scope.name += " shift ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else if($event.keyCode === 18)
{
$scope.name += " Alt ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else
{
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<label>Type something:
<input type="text"
ng-keydown="onKeyDown($event)"
ng-model="name" />
</label><br />
<p>KEY DOWN RESULT:<p>{{name}}<br />
</div>
</body>
</html>
Hope it helps.
See AngularJS keyboard events: http://www.angularjshub.com/examples/eventhandlers/keyboardevents/
You can capture keycodes by using these events on input box:
<input type="text"
ng-keydown="onKeyDown($event)"
ng-keyup="onKeyUp($event)"
ng-keypress="onKeyPress($event)" />
Try to use "ng-keypress=check($event)", the $event object have "keyCode", check the keyCode and update your model inside the function.
Ctrl is keycode 17. So inside your function you will check specific keys like this: if($event.keyCode === 17){ $scope.model += " ctrl" };
You can see all keycodes here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Twitter JSON API with jQuery

function getUsername()
{
var userName = document.form.screen_name.value;
document.getElementById("display").innerHTML = userName;
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
document.getElementById("display2").innerHTML = apiName;
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter.name);
$('#showdata').html("<p>item1="+twitter.follwers_count+" item2="+twitter.friends_count+"</p>");
});
});
Javascript code.
<form method="get" action="#" name="form">
Username: <input type="text" name="screen_name" id="username"/>
<input type="submit" value="submit" onclick="getUsername()" />
</form>
<p>Your username is <h2 id="display"></h2></p>
<p>Your api url is <h2 id="display2"></h2></p>
HTML Code
Whats wrong with this code? The alert comes back undefined.
Thanks
The data comes back as an array. You need to get the object at index 0:
function getUsername()
{
var userName = document.form.screen_name.value;
document.getElementById("display").innerHTML = userName;
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
document.getElementById("display2").innerHTML = apiName;
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter[0].name);
$('#showdata').html("<p>item1=" + twitter[0].follwers_count + " item2=" + twitter[0].friends_count + "</p>");
});
});
}
Of course, you could always just write twitter = twitter[0]; at the start of your function.
Oh, and here's your code jQuery-ified:
function getUsername()
{
var userName = $('[name=screen_name]').val();
$("#display").html(userName);
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
$("#display2").html(apiName);
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter[0].name);
$('#showdata').html("<p>item1=" + twitter[0].follwers_count + " item2=" + twitter[0].friends_count + "</p>");
});
});
}