I have the following code whereby it validates an array and if the array is empty, it should submit a form called deleteUnitManagement. Else it should show a modal with the array values in it. Here the errorFunction is a modal.
$("#deleteUnitButton").click(function() {
if ($("#deleteUnit").val().trim().length == 0) { //If unit field is empty
$("#deleteUnit").css("border-color", "red");
er("Please select a Unit name");
errorFunction("Error in Processing", "Please select a Unit name");
return false;
} else if ($("#deleteUnit").val() == "Not Applicable") {
er("This is a default unit name selection. Cannot delete");
errorFunction("Error in Processing", "This is a default unit name selection. Cannot delete");
return false;
} else { //The following Ajax is checking if there is an existing user present with the unit that selected to delete. If there is then it will ask to change those users unit to some other units before do this deleting operation
var unitNum = $("#deleteUnit").val();
var isThereUser = false;
$.ajax({
type: "POST",
url: "unitCheck.php",
data: {
unitNum: unitNum
},
success: function(result) {
var returnedData = JSON.parse(result);
var length = returnedData.length;
var users = "";
if (length != 0) {
isThereUser = true;
for (i = 0; i < length; i++) {
if (i == 0) {
users = users + returnedData[i];
} else {
users = users + ", " + returnedData[i];
}
}
errorFunction("Error in Processing", "There are " + length + " user(s) (" + users + ") assigned to this floor. Please change their units first before deleting this unit");
} else {
$("#deleteUnit").css("border-color", "");
$("#deleteUnitManagement").submit();
}
}
});
return false;
}
});
Following is the codes in unitCheck.php
$unitNum = $_POST['unitNum'];
$userNames = [];
$query = "SELECT userName FROM users WHERE userUnit=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $query)){
echo "Selecting user names from users table query failed";
}else{
mysqli_stmt_bind_param($stmt,"s", $unitNum);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
while($rows = mysqli_fetch_array($result)){
$name = $rows['userName'];
array_push($userNames, $name);
}
echo json_encode($userNames);
The code is working fine for conditions whereby array is not empty. It will pop up modal window with all the array values. But if the array is empty, it is not submitting the form. Does anyone know why?
Edit 1
Simplified code with no Ajax and included all HTML elements. You can comment out returnedData variable lines to enable and disable empty and non empty condition. Over here also if the array is not empty, it is alerting elements in that array. But once it is empty, the form is not submitting and showing echoing message deleted
$("#deleteUnitButton").click(function() {
var returnedData = [];
// var returnedData = ["sdfs", "sdfdssf"];
var length = returnedData.length;
var users = "";
if (length != 0) {
isThereUser = true;
for (i = 0; i < length; i++) {
if (i == 0) {
users = users + returnedData[i];
} else {
users = users + ", " + returnedData[i];
}
}
alert(users);
} else {
$("#deleteUnit").css("border-color", "");
$("#deleteUnitManagement").submit();
}
return false;
});
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<div class="col-sm-3">
<div class="card">
<div class="card-body">
<div style="padding:20px;">
<h3 class="text-center"><img src="" id="">Delete Unit</h3>
</div>
<form method="post" id="deleteUnitManagement" name="deleteUnitManagement">
<button type="submit" id="deleteUnitButton" name="deleteUnitButton" class="btn btn-danger">Delete Unit</button>
</form>
<?php
if(isset($_POST['deleteUnitButton'])){
echo 'deleted';
}
?>
</div>
</div>
</div>
Related
What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>
thanks for being so supportive to the topics asked. I have a built a 'User Approval' system wherein the admin gets list of registered users and approves them by using checkboxes for each and 'Check all' that selects all users. Table has pagination of 10 users at once. My issue here is when I 'check all' on the second page with 10 users, the table automatically selects and displays the first 10 users also i.e. the first page with 10 users. How can I stop the page to second list only when "check all" is implemented on second list of 10 candidates. I am confused on where it has gone wrong and getting no clue . Any help or advice will be appreciated and helpful. Here is the code for javascript that I have used,
<script type="text/javascript">
var select_all = document.getElementById("select_all"); //select all checkbox
var checkboxes = document.getElementsByClassName("checkbox"); //checkbox items
//select all checkboxes
select_all.addEventListener("change", function(e){
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = select_all.checked;
}
});
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
//uncheck "select all", if one of the listed checkbox item is unchecked
if(this.checked == false){
select_all.checked = false;
}
//check "select all" if all checkbox items are checked
if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
select_all.checked = true;
}
});
}
</script>
And the php+html for the table header "Check all"
<input type="checkbox" id="select_all" name="all_check[]" <?php echo $disabled ;?> class="checkbox" value= "<?php //echo $row['id']; ?>"> </th>
And my pagination class,
<?php
class pagination
{
var $page = 1; // Current Page
var $perPage = 10; // Items on each page, defaulted to 10
var $showFirstAndLast = false; // if you would like the first and last page options.
function generate($array, $perPage = 10)
{
// Assign the items per page variable
if (!empty($perPage))
$this->perPage = $perPage;
// Assign the page variable
if (!empty($_GET['page'])) {
$this->page = $_GET['page']; // using the get method
} else {
$this->page = 1; // if we don't have a page number then assume we are on the first page
}
// Take the length of the array
$this->length = count($array);
// Get the number of pages
$this->pages = ceil($this->length / $this->perPage);
// Calculate the starting point
$this->start = ceil(($this->page - 1) * $this->perPage);
// Return the part of the array we have requested
return array_slice($array, $this->start, $this->perPage);
}
function links()
{
// Initiate the links array
$plinks = array();
$links = array();
$slinks = array();
// Concatenate the get variables to add to the page numbering string
if (count($_GET)) {
$queryURL = '';
foreach ($_GET as $key => $value) {
if ($key != 'page') {
$queryURL .= '&'.$key.'='.$value;
}
}
}
// If we have more then one pages
if (($this->pages) > 1)
{
// Assign the 'previous page' link into the array if we are not on the first page
if ($this->page != 1) {
if ($this->showFirstAndLast) {
$plinks[] = ' «« First ';
}
$plinks[] = ' « Prev ';
}
// Assign all the page numbers & links to the array
for ($j = 1; $j < ($this->pages + 1); $j++) {
if ($this->page == $j) {
$links[] = ' <a style="font-weight: bold;">'.$j.'</a> '; // If we are on the same page as the current item
} else {
$links[] = ' '.$j.' '; // add the link to the array
}
}
// Assign the 'next page' if we are not on the last page
if ($this->page < $this->pages) {
$slinks[] = ' Next » ';
if ($this->showFirstAndLast) {
$slinks[] = ' Last »» ';
}
}
// Push the array into a string using any some glue
return implode(' ', $plinks).implode($this->implodeBy, $links).implode(' ', $slinks);
}
return;
}
}
?>
This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>
I'm trying to create a script to keep a history track of three for a random number generator. (this is all for practice to take more advance approach) but I for some reason cannot get jQuery to Append a new html table/row after the code starts executing from a different JS file. however everything seems to go according to plan besides the part when I am trying to add the row into the table. I have a jsfiddle here:
http://jsfiddle.net/e3ey2a3s/2/
Here is my code however:
convert.js (the generator)
var min, max, setDol = false,
pArry = [];
function chooseRandom() {
min = prompt('whats the max value?', 'max');
max = prompt('whats the min value?', 'min');
return convertType(min, max);
}
function convertType(min, max) {
if (typeof min === 'string' || typeof max === 'string') {
document.getElementById('convert').innerHTML = "converting strings to numbers..."
parseInt(min);
parseInt(max);
}
return getRandom(min, max);
}
function getRandom(min, max) {
if (isNaN(min) || isNaN(max)) {
borked();
} else {
return amtFixed(Math.random() * (max - min) + min);
}
}
function amtFixed(amt) {
if (amt >= 0 && amt <= 10) {
document.getElementById('text').innerHTML = "Our number is " + amt + " which is between 0 and 10";
} else if (amt >= 11 && amt <= 20) {
document.getElementById("text").innerHTML = "Our number is " + amt + " which is between 11 and 20";
} else {
document.getElementById("text").innerHTML = "Our number is " + amt + " which is greater than 20. huh.";
}
var fixed = Number(amt).toFixed(2);
return convertFix(fixed);
};
function convertFix(fixed) {
if (typeof fixed === 'string') {
fixed = (fixed / 1);
document.getElementById("fixed").innerHTML = typeof fixed + " " + fixed + " converted down to two decimals.";
setDol = confirm("Convert our amount to a dollar amount?");
} else {
console.log('Failed to convert...');
}
return success(fixed);
};
function borked() {
var broke = false;
alert("You must not of entered a proper number... That sucks :/");
var broke = confirm("Do you want to retry?");
if (broke) {
return chooseRandom();
} else {
return document.getElementById("text").innerHTML = "I r broked :(";
}
}
function success(num) {
var amtHist = [];
if (setDol) {
$("#price").append('$' + num + ' Set fixed to a dollar amount!');
pArry.push(num);
return buildHistory(pArry);
} else {
$("#price").empty().append("Our fixed value is: " + num);
pArry.push(num);
return buildHistory(pArry);
}
}
After this script finishes up success() send the finished array over to my data.js function buildHistory() which looks like this:
buildHistory = function(arr) {
var t, i, _this = this,
numEls = 0,
a = arr;
var objLen = holdObj.History.length;
table = $('table.history');
//Let's do our loops to check and set history data
//We need to get our history data so we can make sure not to re print old data.
for (t = 0; t <= objLen; t++) {
for (i = 0; i < a.length; i++) {
x = objLen[t];
if ($.inArray(x, a) === -1) {
//Alright now we build onto the history table
$('table.history').append('<tr><td>' + a[i] + '</td></tr>');
var cell = table.find('td');
cell.addClass('hist' + numEls);
numEls++;
holdObj.History.push(a[i]);
} else {
break;
}
}
}
// Let's remove the oldest value once the table exceeds 3 or 4.
if (objLen > 3 && numEls > 3) {
var tmp = table.find('hist_3');
table.remove(tmp);
holdObj.History.pop();
}
}
This is all still in the makes so nothing is really finalized here, I am probably just overlooking a simple solution.
Here is my HTML:
<html>
<head>
<script type="text/javascript" src="../source/libs/jQuery-1.8.3.min.js"></script>
<title>Index</title>
</head>
<body>
<p>This is just some filler content lol.</p>
<p>Let's run some scripts! Click the buttons!</p>
<div class="math">
<p id="convert"></p>
<p id="text"></p>
<p id="fixed"></p>
<p id="price"></p>
<table id="history">
<tr>
<th>History</th>
</tr>
<tr>
<td id="hist"> Value #1</td>
</tr>
</table>
</div>
<button class="scrBtn">Click to start Script</button>
<div id="date"></div>
<button class="dateBtn">Get Date</button>
<div class="person">
<div class="pTitle">
<div class="pBody">
<div class="fName">Name: </div>
<div class="age">Age: </div>
<div class="height">Height: </div>
<div class="eyecolor">Eye Color: </div>
<div class="sex">Sex: </div>
This is where our person should go.
</div>
</div>
</div>
<a href="view/Form/personForm.html">
<button class="pBtn">Get Info</button>
</a>
<div class="bRowLeft">test
</div>
<div class="tRowLeft">test
</div>
</body>
<script type="text/javascript" src="../source/model/data.js"></script>
<script type="text/javascript" src="../source/model/convert.js"></script>
<script type="text/javascript" src="../source/model/button.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</html>
Sorry for such a long post but I am trying to explore as much as I can.
(The code is activated via jQuery with button.js)
$(document).ready(function() {
$('.scrBtn').click(function() {
chooseRandom();
});
});
Thanks again, let me know if anymore information is needed.
$('table.history') - you dont have a <table class="history"> element.
Try this:
table = $("#history");
and same where you append.
I have an html form in with a drop down menu and a series of checkboxes. The dropdown has two options. Each option is supposed to check several of the checkboxes using javascript with an onchange event within the "select" tag. This works 100%, but it fails when I trigger it with more javascript.
I have narrowed it down to the part where is resets all the checkboxes to be unchecked. It is then supposed to select the boxes it needs based on the drop down, but because it fails to uncheck them all, they all remain checked.
Here is the code:
select box:
<select name='myrp_autogroups' id='myrp_autogroups' onchange='myrp_group_selector();'>
<option></option>
<?php
$presets = get_option("myrp_presets");
for ($i = 0; $i < count($presets); $i++) {
$preset = $presets[$i];
echo "<option value='";
for ($b = 0; $b < count($preset[1]); $b++) {
$checkbox = $preset[1][$b];
echo $checkbox . ",";
}
echo "'";
echo ">" . $preset[0] . "</option>";
}
update_option("myrp_presets", $presets);
?>
</select>
<input type="button" value="change" onclick="change_group();">
<script type='text/javascript'>
window.onload = change_group();
</script>
Javascript:
function myrp_group_selector()
{
// reset everything.
$mrjQ(".myrp_checkboxes").each(function() {
var name = this.id.split("myrp_c_");
if(name.length == 2) {
document.getElementById("myrp_value_" + name[1]).disabled=true;
document.getElementById("myrp_value_" + name[1]).value="";
this.checked=false;
}
});
if(document.getElementById("myrp_average_top") != null)
{
document.getElementById("myrp_average_top").checked=false;
document.getElementById("myrp_average_value_top").value="";
}
if(document.getElementById("myrp_average_bottom") != null)
{
document.getElementById("myrp_average_value_bottom").value="";
document.getElementById("myrp_average_bottom").checked=false;
}
var checkThese = document.getElementById("myrp_autogroups")[document.getElementById("myrp_autogroups").selectedIndex].value;
var checkArray = checkThese.split(",");
var average = "avg";
// check the new stuff
for(var i in checkArray)
{
if(checkArray[i] == average)
{
if(document.getElementById("myrp_average_top") != null)
{
document.getElementById("myrp_average_top").checked=true;
}
if(document.getElementById("myrp_average_bottom") != null)
{
document.getElementById("myrp_average_bottom").checked=true;
}
}
else
{
document.getElementById("myrp_c_"+checkArray[i]).checked=true;
document.getElementById("myrp_value_"+checkArray[i]).disabled=false;
}
}
}
function change_group() {
select = document.getElementById('myrp_autogroups');
if(select.value != '2,3,4,5,6,'){
select.value = '2,3,4,5,6,';
select.onchange();
}
}
I have narrowed it down to this section, keep in mind it functions perfectly if i manually select an option from the dropdown and doesn't work when triggered by java:
// reset everything.
$mrjQ(".myrp_checkboxes").each(function() {
var name = this.id.split("myrp_c_");
if(name.length == 2) {
document.getElementById("myrp_value_" + name[1]).disabled=true;
document.getElementById("myrp_value_" + name[1]).value="";
this.checked=false;
}
});
the wrong is :
window.onload = change_group() ;
it should be
window.onload = change_group;