Nested JQuery events not working - html

The purpose of my code is to solve a system of three equations.
What I want to happen is for the "p" selector and the "answer" class to be hidden. When there is a "click" event on an "h1" selector, I want it to show the next element. However, after there is a click event on the class "button" I want the "matrix" class to slide up and then the "answer" class to slide down, revealing the answer to the HTML form's results while hiding or "slideUp"ing the original form and heading.
Originally the "my_code.js" file had no problem hiding the "p" element and slideToggling it when an h1 selector before it was clicked, but once I added the additional code, things went south.
What is happening in my jquery script? Am I targeting ancestors elements incorrectly?
JQUERY DOCUMENT
$(document).ready(function() {
$("p, .answer").hide();
$("h1").click(function() {
$(this).next().slideToggle(300);
});
$(".button")click(function() { //after form submission
$(".matrix").slideUp(300, function(){ //hiding the matrix form
$(".answer").slideDown(300); //and display the answer
});
});
});
HTML DOCUMENT
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<title>Kremer's Rule: System of Three Equations</title>
<script language="JavaScript">
function testResults (form) {
function system (x1, x2, x3, y1, y2, y3, z1, z2, z3, a1, a2, a3){
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
this.y1 = y1;
this.y2 = y2;
this.y3 = y3;
this.z1 = z1;
this.z2 = z2;
this.z3 = z3;
this.a1 = a1;
this.a2 = a2;
this.a3 = a3;
this.calcDanswer = function() {
return (this.x1*((this.y2*this.z3)-(this.z2*this.y3))) - (this.y1*((this.x2*this.z3)-(this.z2*this.x3))) + (this.z1*((this.x2*D.y3)- (this.y2*this.x3)));
};
this.calcXanswer = function(){
return (this.a1*((this.y2*this.z3)-(this.z2*this.y3))) - (this.y1*((this.a2*this.z3)-(this.z2*this.a3))) + (this.z1*((this.a2*this.y3)-(this.y2*this.a3)));
};
this.calcYanswer = function(){
return (this.x1*((this.a2*this.z3)-(this.z2*this.a3))) - (this.a1*((this.x2*this.z3)-(this.z2*this.x3))) + (this.z1*((this.x2*this.a3)-(this.a2*this.x3)));
};
this.calcZanswer = function(){
return (this.x1*((this.y2*this.a3)-(this.a2*this.y3))) - (this.y1*((this.x2*this.a3)-(this.a2*this.x3))) + (this.a1*((this.x2*this.y3)-(this.y2*this.x3)));
};
}
var x1 = form.x1.value;
var x2 = form.x2.value;
var x3 = form.x3.value;
var y1 = form.y1.value;
var y2 = form.y2.value;
var y3 = form.y3.value;
var z1 = form.z1.value;
var z2 = form.z2.value;
var z3 = form.z3.value;
var a1 = form.a1.value;
var a2 = form.a2.value;
var a3 = form.a3.value;
var D = new system(x1, x2, x3, y1, y2, y3, z1, z2, z3, a1, a2, a3);
var X = D.calcXanswer()/D.calcDanswer();
var Y = D.calcYanswer()/D.calcDanswer();
var Z = D.calcZanswer()/D.calcDanswer();
// printing to console
var out = document.getElementById('real-answer');
out.innerHTML += "<b>The equations are:</b>" + "<br />" +
D.x1 + "x + " + D.y1 + "y + " + D.z1 +"z = "+D.a1 + "<br />" +
D.x2 + "x + " + D.y2 + "y + " + D.z2 +"z = "+D.a2 + "<br />" +
D.x3 + "x + " + D.y3 + "y + " + D.z3 +"z = "+D.a3 + "<br /><br />" +
"The answer for D is " + D.calcDanswer() + "<br />" +
"The answer for Dx is " + D.calcXanswer() + "<br />" +
"The answer for Dy is " + D.calcYanswer() + "<br />" +
"The answer for Dy is " + D.calcZanswer() + "<br />" +
"X is " + X + "<br />" +
"Y is " + Y + "<br />" +
"Z is " + Z;
}
</SCRIPT>
</head>
<body>
<!--DIRECTIONS-->
<h1><span id="highlight">How Does This Work?</span></h1>
<p>Type in all the information for your system of three equations.<br />
When finished hit "Go".</p>
<!--Form-->
<p class="matrix">
<FORM NAME="myform" ACTION="" METHOD="GET">
<input type="text" name="x1"> x + <input type="text" name="y1"> y + <input type="text" name="z1"> z = <input type="text" name="a1"><br />
<input type="text" name="x2"> x + <input type="text" name="y2"> y + <input type="text" name="z2"> z = <input type="text" name="a2"><br />
<input type="text" name="x3"> x + <input type="text" name="y3"> y + <input type="text" name="z3"> z = <input type="text" name="a3"><br />
<input type="button" class="button" name="button" value="GO" onClick="testResults(this.form)">
</form>
</p>
<div id="answer">
<h1><span id="highlight">The Answer:</span></h2>
<div id='real-answer'></div>
</div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="my_code.js"></script>
</html>

You have a syntax error and the answers is a id not a class
$(document).ready(function () {
//answer is an id so use id selector
$("p, #answer").hide();
$("h1").click(function () {
$(this).next().slideToggle(300);
});
//missing . before click(
$(".button").click(function () { //after form submission
$(".matrix").slideUp(300, function () { //hiding the matrix form
$("#answer").slideDown(300); //and display the answer
});
});
});
Demo: Fiddle

If "p" selector having the "answer" class is not getting hidden, then i can tell u as its a syntax error. Remove that comma after p
$("p #answer").hide();
Hope this helps you

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>

How to insert line break (enter) in Whatsapp message sent via jQuery

This is how I am sending whatsapp message via jQuery
var ques = "I";
var a = "am";
var b = "having";
var c = "a good";
var d = "time";
$(document).on("click", '.whatsapp', function() {
var whatsappMessage = ques + "\r\n\r\n" + a + "\r\n" + b + "\r\n" + c + "\r\n" + d;
var whatsapp_url = "whatsapp://send?text=" + whatsappMessage;
window.location.href = whatsapp_url;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showques" style="margin-left: 10px;font-size: 32px;">
</div>
<div style="width:300px;padding: 20px;background-color:#5755d9;">
<a class="whatsapp" style="font-size: 40px;color:white; text-decoration: none;">Whatsapp</a>
</div>
output = I \r\n\r\n am \r\n\r\n having \r\n\r\n a good \r\n\r\n time
I want an output like this:
I
am
having
a good
time
Add the following line in the code and it will work
whatsappMessage = window.encodeURIComponent(whatsappMessage);
$(document).on("click", '.whatsapp', function() {
var whatsappMessage = ques + "\r\n\r\n" + a + "\r\n" + b + "\r\n" + c + "\r\n" + d;
if( isMobile.any() ) {
whatsappMessage = window.encodeURIComponent(whatsappMessage);
var whatsapp_url = "whatsapp://send?text=" + whatsappMessage;
window.location.href = whatsapp_url;
} else {
alert("Please share this in mobile device");
}
});

how do i display website comments above the last posted comment

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.

How can I display a profile stored in a database after a SQL query in a Google Spreadsheet Sidebar?

Basically here is what I'm doing:
Storing a person profile in a MYSQL Database
Creating a google spreadsheet add-on with a sidebar
giving to the user the possibility to search profiles through the DB in the add-on
giving to the user the possibility to display the datas of the profile in the Sidebar in the add-on
So Imagine you want to search John but the input you've entered in the searchbar is the letter J. The result of this query will be Jack , Johnatan, Jules, Joe and John as they all have a J. All this names will appear as link for you to click on in order to have more datas displayed (age, picture, fullname, description...). Only problem is that the only way I've managed to achieve is by making a SQL query after each keyup in my HTML input then create X numbers (in this case 5) of hidden classes with the infos, that I can show by clicking on a created link.
So this can easily work for 5 results, but imagine there's 100 of them and you only want to see one of them. Sounds crazy to create 100 hidden divs with all the infos to finally show only one.
here is an example code
code.gs
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('UI_HTML');
SpreadsheetApp.getUi().showSidebar(ui);
}
//My function to search for profiles (returns an array with each lines found)
function searchProfile(entry){
var address = 'sql3.freemysqlhosting.net';
var user = 'user';
var userPwd = 'password';
var db = 'sql12345678910';
var instanceUrl = 'jdbc:mysql://' + address;
var dbUrl = instanceUrl + '/' + db;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.createStatement();
var ret = [];
var res = stmt.executeQuery('SELECT * FROM item WHERE name = "' + entry + '"'
+ ' OR fullname LIKE CONCAT("%", "' + entry + '", "%")'
+ ' OR description LIKE CONCAT("%", "' + entry + '", "%")');
var numCol = res.getMetaData().getColumnCount();
var i = 0;
var j = 0;
while (res.next())
{
j = 0;
if (!ret[i])
ret[i] = [];
while (j < numCol)
{
ret[i][j]= res.getString(j + 1);
j++;
}
i++;
}
return (ret);
}
UI_HTML.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.show {
display: block;
}
.hide {
display: none;
}
</style>
</head>
<body>
<div>
<p>Search Profile</p>
<input type="text" id="searchProfile" onkeyup="searchProfileHTML()" placeholder="Search for ...">
<div id="results" ></div>
</div>
<script>
function searchProfileHTML()
{
var x = document.getElementById("searchProfile").value;
google.script.run
.withSuccessHandler(createLinks)
.searchProfile(x);
function createLinks(result)
{
$('.links').remove();
if (!x)
return (0);
$('#results').append('<ul></ul>');
$('#results ul').addClass('links');
result.forEach(function(el){
//My Link to show/hide my Div
$('.links').append('<li><a id="' + el[0] + '-link" href="#">' + el[0] + '</a><div id="' + el[0] + '" class ="hide" ></div></li>');
//My div with all the infos (hidden by default)
$('#' + el[0]).append(""
+ '<img src="' + el[14] + '" height="100" width="100">'
+ "<div>"
+ "<ul>"
+ "<li>Name: "+ el[0] + "</li>"
+ "<li>Full name: "+ el[1] + "</li>"
+ "<li>Description : "+ el[2] + "</li>"
+ "<li>email: "+ el[3] + "</li>"
+ "</ul>"
+ "</div>");
$('#' + el[0] + '-link').on("click", function(){
$('#' + el[0]).toggleClass("hide show");
})
});
}
}
</script>
Anyone has an idea how I can make this more lite?

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