Delete duplicate array element - javascript

I am working on a program that records customer name and status(child/adult), the program allows add, display and delete customer records from array. However, if user enters the same name and status e.g:
Name: james, status: adult
Name: james, status: adult
I want the function to delete just one record,but now it delete both of them, do i have to add break here? Please help.
PS: I can't use any inbuilt JavaScript functions such as slice(),delete(), concat(), join(), pop(), push(), reverse(), shift(), slice(), sort(), splice(), toString(), unshift() or valueOf()
const MAX_CUSTOMERS = 5;
//create new Array
var customerList = new Array();
function addCustomer() //add customer
{
if (customerList.length >= MAX_CUSTOMERS) //check max customers
alert('Sorry, no more than ' + String(MAX_CUSTOMERS) + ' customers are allowed on the trampoline.')
else
{
var newIndex = customerList.length; //add new user
customerList[newIndex] = new Object;
customerList[newIndex].name = prompt('What is the customer\'s name?'); //ask user enter their name
customerList[newIndex].status = prompt('Are you a Child or an Adult?'); //ask user enter their status
while (!(customerList[newIndex].status == 'child' || customerList[newIndex].status == 'adult')) //check user is child or adult
{
customerList[newIndex].status = (prompt('Error! Please Enter \'child\' or \'adult\':'));
}
}
}
function displayAllCustomers() //display customers
{
var message = ''; //create message
for (var i = 0; i < customerList.length; i++) //loop customers
{
message += 'Name:' + customerList[i].name + ', Status: ' + String(customerList[i].status) + '. \n'; //add customer to message
}
if (message == '') //check message
message = 'Sorry, there are no customer to display!';
alert(message); //output message
}
function identifyThenDeleteCustomer() //identify then delete customer
{
var customerName = prompt('Enter the name of the customer to delete:'); //get customer name
var customerStatus = prompt('Enter \'child\' or \'adult\':'); //get customer status
while (!(customerStatus == 'child' || customerStatus == 'adult')) //check customer status
customerStatus = prompt('Error - enter \'child\' or \'adult\':');
deleteCustomer(customerName, customerStatus); //delete customer
}
function deleteCustomer(aName, aStatus) //delete customer
{
var newCustomerList = new Array(); //create new array
for (var i = 0; i < customerList.length; i++) //loop customers
{
var customer = customerList[i];
if ((customer.name != aName) || (customer.status != aStatus)) //check customer
{
var newIndex = newCustomerList.length; //add new user
newCustomerList[newIndex] = customer;
}
}
if (newCustomerList.length < customerList.length) //check deleted
{
alert('The customer has been deleted.');
}
else
{
alert('There are no customer to delete!');
}
customerList = newCustomerList; //update customer list
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta charset="utf-8" />
<title>Coursework 2</title>
<script src="ZouYuncongINSTG018cw2.js" type="text/javascript"></script>
</head>
<body>
<div>
<button type="button" onclick="addCustomer();">Add Customer</button><br>
<button type="button" onclick="displayAllCustomers();">Display All Customers</button><br>
<button type="button" onclick="identifyThenDeleteCustomer();">Identify then Delete Customer</button>
</div>
</body>
</html>

You can make your delete function like this,
function deleteCustomer(aName, aStatus) //delete customer
{
for (var i = 0; i < customerList.length; i++) //loop customers
{
var customer = customerList[i];
if ((customer.name == aName) && (customer.status == aStatus)) //check customer
{
customerList = array.splice(i, 1);//delete from array itself
alert('The customer has been deleted.');
return;//stop
}
}
alert('There are no customer to delete!');
}
It will delete just one.
Since you said you cant use built in functions. In that case you have to copy the elements before and after the one to remove. You can have a control variable marking that you already found the one to delete. So no more deletions will happen.
For example,
function deleteCustomer(aName, aStatus) //delete customer
{
var onedeleted = false;
var newCustomerList = new Array(); //create new array
for (var i = 0; i < customerList.length; i++) //loop customers
{
var customer = customerList[i];
if ((customer.name != aName) || (customer.status != aStatus) || onedeleted) //check customer
{
var newIndex = newCustomerList.length; //add new user
newCustomerList[newIndex] = customer;
}
else
onedeleted = true;
}
if (newCustomerList.length < customerList.length) //check deleted
{
alert('The customer has been deleted.');
}
else
{
alert('There are no customer to delete!');
}
customerList = newCustomerList; //update customer list
}

Related

how to remove data from array in local storage?

How to remove particular data when user click on delete from array stored in local storage ?
the key named title and description in both data are stored in form of array.
this is my script file
let title, description;
function validate() {
title = document.getElementById('title').value;
description = document.getElementById('description').value;
if (title == '') {
alert("Please add title");
} else if (description == '') {
alert("Please add description");
} else {
document.getElementById("myform").reset();
console.log(title);
console.log(description);
store(title, description);
}
}
function store(title, description) {
// load the existing values (default to an empty array if not exist)
let _title = JSON.parse(localStorage.getItem("title") || "[]")
let _description = JSON.parse(localStorage.getItem("description") || "[]")
_title.push(title)
_description.push(description)
localStorage.setItem("title", JSON.stringify(_title))
localStorage.setItem("description", JSON.stringify(_description))
window.location.reload()
}
get_title = JSON.parse(localStorage.getItem("title"))
get_description = JSON.parse(localStorage.getItem("description"))
let table1;
for (i = 0; i < get_title.length; i++) {
if (get_title[i] == null) {
console.log("null")
} else {
table1 += `
<tr>
<th scope="row">${i + 1}</th>
<td id="tit">${get_title[i]}</td>
<td id="descripti">${get_description[i]}</td>
<td>
**
<button type="button"
class="btn btn-sm btn-danger"
onclick="del(${i})">
Delete
</button>
**
</td>
</tr>`
}
}
document.getElementById('table1').innerHTML = table1;
function del(i) {
localStorage.removeItem(`title[${i}]`)
localStorage.removeItem(`description[${i}]`)
window.location.reload()
}
please help me to remove this items.
localStorage and sessionStorage are both key, value storages where both key and value are strings.
You will have to read the arrays
let titles = JSON.parse(localStorage.getItem("title"));
let descs = JSON.parse(localStorage.getItem("descs"));
titles.splice(i, 1);
descs.splice(i, 1);
localStorage.setItem("title", JSON.stringify(titles));
localStorage.setItem("description", JSON.stringify(descs));
I would suggest you store a single array with objects inside like this:
localStorage.setItem('items', JSON.stringify([{ title: 'title1', descirption: 'description1' }]));
Otherwise you risk to have the arrays length out of sync.
Then when you read the array:
let get_items = JSON.parse(localStorage.getItem('items'));
...
get_items[i].title; //reads title
get_items[i].description; //reads description

Button adding user input to the array. Then typing out the data in array to a <div>

I'm fairly new to coding so please ignore any unwritten rules I might be missing.
Any feedback is appreciated.
Basically, I have three text inputs, Name:, Age:, and Password:
If not all fields are filled and error message will occur, but if everything is filled in and the user presses the button I need the information to be saved to an array, and for the information (only Name: & Age:) to be typed out below, along with two other "personas" that are to be added via (Push) method.
However, I'm not getting these different stages to work together. I am receiving different errors each time I change something. As previously stated I am a novice within coding and will take any help I can get.
function buttonclick() {
validate();
addToArray();
}
function validate() {
var name = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return false;
} else {
true;
}
if (password.value == "IHM") {
true;
} else {
alert("Not a valid password")
return false;
}
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let Uname = document.getElementById("NameInput").value;
// Gets age from the input
let Uage = document.getElementById("AgeInput").value;
// Adds antoher name to the array?
persons.push(person1, person2);
// Sorts the array
persons.sort();
/* Is this needed?
const write = () => {
NameInput.forEach()
AgeInput.forEach()
}*
<div>
<input type="text" placeholder="Name" id="NameInput">
</div>
<div>
<input type="number" placeholder="Age" id="AgeInput">
</div>
<div>
<input type="password" placeholder="Password" id="PasswordInput">
</div>
<button onclick="buttonclick()" type="button">Submit</button>
<div id="output"></div>
I see your code in the vsCode, and your array gets the two objects if you check in the console, I add an object of user name and age- from inputs. I hope that im understand.. that my code:
enter code here function buttonclick() {
validate(addToArray);
}
var uname = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
function validate(cb) {
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return false;
} else {
true;
}
if (password.value == "IHM") {
true;
} else {
alert("Not a valid password")
return false;
}
cb();
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let objOfUserInputs = {};
objOfUserInputs.uname = uname.value;
objOfUserInputs.uage = age.value;
// Gets age from the input
let Uage = document.getElementById("AgeInput").value;
// Adds antoher name to the array?
persons.push(person1, person2, objOfUserInputs);
// Sorts the array
persons.sort();
console.log(persons);
}
First step: You don't need to write true in the conditionals, you could just return if you don't need to check the returned value
eg.:
For the first conditional, you don't even need the else part
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return
}
For the second conditional
if (password.value == "IHM"){
return true
} else {
alert ('Wrong password')
}
You could even write it like this, since if the condition is met, the function will return and the alert won't trigger
if (password.value == "IHM"){
return true
}
alert ('Wrong password')
Try it out.
Then you want to append those values to the array (if i understood correctly) and you want them to be displayed, alongside with the others.
I suggest you create a similar object and then push that object to the array, then you can sort it
So, create the object from the user input:
let Uname = document.getElementById("NameInput").value;
let Uage = parseInt(document.getElementById("AgeInput").value);
//You need to use parseInt() if you want that item to be an integer
let person3 = {
Uname: Uname,
Uage: Uage
}
And then push every object to the array
persons.push(person1, person2, person3);
//return the array
return persons
to sort the array, by name i imagine, just using sort would not suffice, as you want to sort on the 'name' property, so you have to pass a function to sort that orders the items by their name.
You can check it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
persons.sort(function (a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
The last step, if i understand correctly, is placing all the items, in the ordered array, inside the output div, so let's keep the write() function.
You have to iterate through each element, and then you need to insert the HTML that you have created inside the 'output' div.
There are a few ways to to this, you can create elements in the js, or you can append the HTML directly to the div.
Let's say you want to place them in an unordered list.
//pass the result from the addToArray() funtion to the write() function
function write(persons){
let output = document.getElementById('output')
//clean output div otherwise everytime it will append new content
output.innerHTML = ""
let ul = document.createElement('ul')
//Iterate
for( let i of persons){
let li = document.createElement('li')
li.innerHTML = `${i.Uname} - ${i.Uage}`
ul.appendChild(li)
}
output.appendChild(ul)
}
and finally the onclick function, you need to make sure that everything is as you want before adding it to the output div, so check if the verify function has returned true(or whatever you prefer), and the create the array and write it to the div
function buttonclick() {
if (validate() === true){
write(addToArray())
}
}
here is it in full
<body>
<div>
<input type="text" placeholder="Name" id="NameInput">
</div>
<div>
<input type="number" placeholder="Age" id="AgeInput">
</div>
<div>
<input type="password" placeholder="Password" id="PasswordInput">
</div>
<button onclick="buttonclick()" type ="button">Submit</button>
<div id="output"></div>
<script>
function buttonclick() {
if (validate() === true){
write(addToArray())
}
}
function validate() {
var name = document.getElementById("NameInput");
var age = document.getElementById("AgeInput");
var password = document.getElementById("PasswordInput");
if (name.value == "" || password.value == "" || age.value == "") {
alert("Field is required");
return
}
if (password.value == "IHM") {
return true
}
alert("Not a valid password")
}
function addToArray() {
let persons = [];
let person1 = {
Uname: "Marcus",
Uage: 34
}
let person2 = {
Uname: "Cihan",
Uage: 35
}
// Gets name from the input
let Uname = document.getElementById("NameInput").value;
// Gets age from the input
let Uage = parseInt(document.getElementById("AgeInput").value);
//Create the object
let person3 = {
Uname: Uname,
Uage: Uage
}
// Adds antoher name to the array?
persons.push(person1, person2, person3);
// Sorts the array
persons.sort(function (a, b) {
var nameA = a.Uname.toUpperCase(); // ignore upper and lowercase
var nameB = b.Uname.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
return persons
}
function write(persons) {
let output = document.getElementById('output')
//clean output div otherwise everytime it will append new content
output.innerHTML = ""
let ul = document.createElement('ul')
//Iterate
for (let i of persons) {
let li = document.createElement('li')
li.innerHTML = `${i.Uname} - ${i.Uage}`
//Append items to ul
ul.appendChild(li)
}
//Append ul to the 'output' div
output.appendChild(ul)
}
</script>
</body>
There are many ways you can accomplish this, i have tried to stay as close as possible to your example so you can understand better, i hope it'll help you, have a good day.

Google Scripts Web App not populating Googlesheet with data

I'm working on a google timeclock app that I got off of Packt. I cannot get it to work. There's an HTML file and a .gs. I think that the javascript in the HTML is not working. It's either that or the doGet function in the .gs code. I really don't know. I've tried chopping it down and isolating the error and I think that it's probably that the HTML isn't running the javascript.
Here's the code for the respective documents.
Code.gs
var ssid = "1BMb3P0G0nqYHfLrDGS113_CJ-pQx0x0QHrihnalaufk";
// Change date format as per your preference.
var DF = "MM/dd/yyyy HH:mm:ss";
var TZ = Session.getScriptTimeZone();
var ss = SpreadsheetApp.openById(ssid);
var TimeSheet = ss.getSheetByName("TimeSheet");
var EmpSheet = ss.getSheetByName("EmployeesList");
var BackupSheet = ss.getSheetByName("Backup");
var MessageSheet = ss.getSheetByName("Message");
/**
* Get employee names from the EmployeesList sheet,
* construct the data as an array and return.
*
*/
function getEmpList(){
var emp = [];
var data = EmpSheet.getDataRange().getValues();
for(var i in data) if(data[i][0]) emp.push(data[i][0]);
return emp;
}
function doGet(){
var template = HtmlService.createTemplateFromFile("Timesheet");
template.message = MessageSheet.getRange("A2").getValue();
template.empList = getEmpList();
var html = template.evaluate();
return html;
}
// Returns employee shift status as an array [status, name].
function getEmpStatus(emp){
var empData = EmpSheet.getDataRange().getValues();
var timeData = TimeSheet.getDataRange().getValues();
// Remove header
timeData.shift();
for(var i in timeData){
if(timeData[i][1] == emp)
return [timeData[i][0],empData[j][1]];
}
// Return null if employee not in shift
return ["",""];
}
function fmtDate_(d, format) {
// Set the default date format, if 'format' not passed.
var fmt = format || "MM/dd/yyyy HH:mm:ss";
var timeZone = Session.getScriptTimeZone();
return Utilities.formatDate(d, timeZone, fmt);
}
function postTime(name, val) {
var time = fmtDate_(new Date());
var data = TimeSheet.getDataRange().getValues();
// If 'shift start' clicked
if (val == "sb") {
// Update start time if clicked again.
for (var i in data) {
if (data[i][1] == name && data[i][0] == "sb") {
data[i][2] = time;
TimeSheet.getRange(1, 1, data.length, data[0].length)
.setValues(data);
return [val, name];
}
};
// Else insert new name and update start time.
TimeSheet.appendRow([val, name, time]);
return [val, name];
}
// If 'break start' clicked.
if(val == "bb"){
for(var i in data){
// Update break start time only if employee is in shift.
if(data[i][0] == "sb" && data[i][1] == name ){
data[i][0] = val;
data[i][3] = time;
TimeSheet.getRange(1, 1, data.length, data[0].length)
.setValues(data);
return [val,name];
}
};
// If 'break start' clicked before 'shift start'.
throw "Please start your shift.";
}
// If 'break end' clicked
if(val == "be"){
for(var i in data){
if(data[i][0] == "bb" && data[i][1] == name ){
data[i][0] = val;
data[i][4] = time;
TimeSheet.getRange(1, 1, data.length, data[0].length)
.setValues(data);
return [val,name];
}
};
// If 'break end' clicked before 'break start'.
throw "Please start your break.";
}
// If shift end clicked
if(val == "se"){
for(var i in data){
if(data[i][1] == name
&& (data[i][0] == "sb"|| data[i][0] == "be") ){
var backup = [];
backup.push(
data[i][1], // Name
data[i][2], // Shift Start
data[i][3], // Break Start
data[i][4], // Break End
time, // Shift end
'=(E2-B2)*24', // Col F formula,
'=(D2-C2)*24', // Col G formula
'=F2-G2' // Col H formula
);
/*
* Copy Timesheet data to Backup sheet.
* Insert a new row before row 2,
* so that the inserted formulas ever work.
*
*/
BackupSheet.insertRowBefore(2);
BackupSheet.getRange(2, 1, 1, backup.length)
.setValues([backup]);
/*
* Tidy timesheet.
* Ensure at least one data row before deleting,
* to avoid error.
*
*/
if(i<2) TimeSheet.appendRow(['']);
// Delete copied row
TimeSheet.deleteRow(Number(i)+1);
return [val,name];
}
};
// If 'shift end' clicked before 'break end'.
if(data[i][0] == "bb")
throw "Please end your break.";
// If 'shift end' clicked without starting shift.
throw "Please start your shift.";
}
}
And the HTML file is this ->
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css" />
<script src= "https://ajax.googleapis.com/ajax/libs /jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<div>
<fieldset style="padding-bottom:25px;">
<legend>Timesheet</legend>
<select id="employee" name="employee">
<? for(var i in empList){ ?>
<option value="<?= empList[i] ?>" > <?= empList[i] ?></option>
<? } ?>
</select>
<br /><br />
<button id="sb" value="sb"><span>Shift Start</span></button>
<button id="bb" value="bb"><span>Break Start</span></button>
<button id="be" value="be"><span>Break End</span></button>
<button id="se" value="se"><span>Shift End</span></button>
</fieldset>
<fieldset>
<div id="message"><?!= message ?></div>
</fieldset>
</div>
<script>
$(function() {
// Disable all buttons.
$('#sb,#bb,#be,#se').prop("disabled", true);
// Set drop-down change event.
$('#employee').change(getStatus);
// Set buttons click event.
$('#sb,#bb,#be,#se').click(postTime);
getStatus();
});
function getStatus(){
// Remove all previous error messages.
$('#error,#success').remove();
// Disable all buttons.
$('#sb,#bb,#be,#se').prop("disabled", true);
// Get employee shift status.
google.script.run
.withSuccessHandler(function(status){
updateStatus(status);
})
.getEmpStatus($("#employee").val());
}
function postTime(){
// Remove all previous error messages.
$('#error,#success').remove();
// Disable all buttons.
$('#sb,#bb,#be,#se').prop("disabled", true);
// Post shift time to sheet.
google.script.run
.withSuccessHandler(function(msg){
updateStatus(msg[0]);
})
.withFailureHandler(function(msg, elm){
showError(msg, elm);
})
.withUserObject(this)
.postTime($("#employee").val(),$(this).val());
}
function updateStatus(status){
// Enable appropriate buttons only.
switch(status){
case "sb": $('#bb,#se').prop("disabled", false); break;
case "bb": $('#be').prop("disabled", false); break;
case "be": $('#se').prop("disabled", false); break;
default: $('#sb').prop("disabled", false);
}
}
function showError(msg, elm) {
var span = $('<span id="error" class="error">' + msg + '</span>');
$(elm).after(span);
}
</script>
</body>
</html>

Why is removeChild() not working in my code? Javascript

So I'm creating a search website where the user enters a part of a name or a full name and then presses a button. And based on the string entered, it displays a hint of names of actors that contain the string or sub-string. The names are stored in a mysql database.
I was able to accomplish all of that by using ajax to interact with php and php to interact with mysql database. However, if the user enters nothing, it's supposed to display nothing.
So I though of just deleting all names when the field text is empty (in other words, I just delete all p elements of a div).
That's where the problem is. Even though I used element.removeChild(), It doesn't delete anything. Instead, even when the string is empty and the user presses the button, it keeps the same info from the previous search. I already searched on similar questions about removeChild(), but none of the answers or hints I found have worked for me.
Here is the javascript and html code below.
var array = [];
var str = "";
var clicked_id = "";
var body = document.getElementsByTagName('BODY')[0];
var actors = document.getElementById('actors');
var roles = document.getElementById('roles');
actors.addEventListener("click", function(){
getData(this.id);
}, false);
roles.addEventListener("click", function(){
getData(this.id);
}, false);
function getData(myid) {
str = document.getElementById('mytext').value;
clicked_id = myid;
var id = "roles";
console.log(clicked_id);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
array = JSON.parse(xmlhttp.responseText);
var element = document.createElement('div');
element.id = "mydiv";
if (str == "" && element.hasChildNodes() != null) {
while (element.hasChildNodes()) {
element.removeChild(element.lastChild);
}
} else {
for (var i = 0; i < array.length; i++) {
var p = document.createElement('p');
p.append(array[i]);
element.append(p);
}
body.append(element);
}
}
};
xmlhttp.open("GET", "controller.php?q="+str , true);
xmlhttp.send();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h2>Search for either all roles or all actors in the database imdb_small</h2>
<hr> Search string <br>
<input type="text" id="mytext"> <br>
<input type="button" value="Actors" id="actors">
<input type="button" value="Roles" id="roles" > <br> <br>
<hr> <br><br>
</body>
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="demon";
//CREATE CONNECTION
$conn=new mysqli($servername,$username,$password,$dbname);
//CHECK CONNECTION
if ($conn->connect_error)
{
die("connection failed:".$conn->connect_error);
}
$sql="delete from category where SUBCATEGORY_ID='".$_GET["id"]."'";
$result=$conn->query($sql);
if ($result===TRUE)
{
echo"RECORD DELETED SUCCESSFULLY";
}
else
{
echo "ERROR:".$sql."<br>".$conn->error;
}
$conn->close();
?>
var array = [];
var str = "";
var clicked_id = "";
var body = document.getElementsByTagName('BODY')[0];
var actors = document.getElementById('actors');
var roles = document.getElementById('roles');
actors.addEventListener("click", function(){
getData(this.id);
}, false);
roles.addEventListener("click", function(){
getData(this.id);
}, false);
function getData(myid) {
str = document.getElementById('mytext').value;
clicked_id = myid;
var id = "roles";
console.log(clicked_id);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
array = JSON.parse(xmlhttp.responseText);
// Check for an existing mydiv first here, before creating a new one
// If it exists then get it and check its child nodes
var element = document.getElementById('#mydiv');
element = element ? element : document.createElement('div');
element.id = "mydiv";
if (str == "" && element.hasChildNodes() != null) {
while (element.hasChildNodes()) {
element.removeChild(element.lastChild);
}
} else {
for (var i = 0; i < array.length; i++) {
var p = document.createElement('p');
p.append(array[i]);
element.append(p);
}
body.append(element);
}
}
};
xmlhttp.open("GET", "controller.php?q="+str , true);
xmlhttp.send();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h2>Search for either all roles or all actors in the database imdb_small</h2>
<hr> Search string <br>
<input type="text" id="mytext"> <br>
<input type="button" value="Actors" id="actors">
<input type="button" value="Roles" id="roles" > <br> <br>
<hr> <br><br>
</body>

Javascript function not being called from onclick

This has me pulling my hair out. Button on site has onclick=method() and it's not calling the method. The method is supposed to grab all the checkboxes, check their checked state and fill the chk[] array with true/false. The WebMethod then takes that array, breaks it down into three smaller arrays and runs checks on the combinations. So far as I can tell, the button never calls the method to begin with.
aspx page:
<fieldset id="Fieldset">
<button onclick="SendForm();">Send</button>
<button onclick="CancelForm();">Cancel</button>
</fieldset>
</form>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
var chk = new [42];
for (i = 0; i < elLength; i++) {
var count = 0;
var type = form1.elements[i].type;
if (type == "checkbox") {
if (form1.elements[i].checked) {
chk[count] = true;
}
else {
chk[count] = false;
}
count++;
}
else {
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>
codebehind method it's calling:
[WebMethod]
public static void SendForm(string email, bool[] chk)
{
bool[] desc = new bool[14];
bool[] loc = new bool[14];
bool[] other = new bool[14];
for (int i = 0; i < 14; i++)
{
int count = i * 3;
desc[i] = chk[count];
loc[i] = chk[count + 1];
other[i] = chk[count + 2];
}
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
else
{
if (IsValidEmailAddress(email))
{
for (int i = 0; i < 14; i++)
{
if (desc[i])
{
if ((loc[i]) && (other[i]))
{
throw new Exception("Invalid, two parameters selected");
}
else if (loc[i])
{
// do stuff
}
else if (other[i])
{
// do stuff
}
else
{
throw new Exception("Invalid, every exemption must have at least one reason selected");
}
}
else
{
throw new Exception("No exemptions have been selected");
}
}
}
else
{
throw new Exception("You must supply a valid email address.");
}
}
}
EDIT!!:
Running the page with the following script instead of the previous script works like a charm. No clue why the previous didn't work.
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
for (i=0;i< elLength;i++) {
var type = form1.elements[i].type;
if (type == "checkbox" && form1.elements[i].checked) {
alert("true!");
}
else {
alert("false!");
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>
Instead of calling your function like
<button onclick="SendForm();">Send</button>
try calling it like this
<button onclick="javascript:return SendForm();">Send</button>
Running the page with the following script instead of the previous script works like a charm. No clue why the previous didn't work.
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
for (i=0;i< elLength;i++) {
var type = form1.elements[i].type;
if (type == "checkbox" && form1.elements[i].checked) {
alert("true!");
}
else {
alert("false!");
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>

Categories