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;
Related
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>
I have a problem to remove the line-through in the js tree. For example now my tree nodes is 199 test Rujuk Kod:100-1-1. I have added the line-through in the 199 test Rujuk Kod:100-1-1. But I just want add in the 199 test, Rujuk Kod:100-1-1 don't want add line-through. Hope someone can help me solve this problem. Thanks.
Below is my coding:
<?php
$folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management");
$folders_arr = array();
while($row = mysqli_fetch_assoc($folderData)){
$parentid = $row['parentid'];
$siri_pindaan = $row['siri_pindaan'];
$effective_date = $row['effective_date'];
$filing_code_refer = $row['filing_code_refer'];
$filing_code_link = $row['filing_code_link'];
if ($filing_code_refer != NULL) {
$refer_to_code = "Rujuk Kod:";
}
if ($filing_code_refer == NULL) {
$refer_to_code = " ";
}
if ($filing_code_link != NULL) {
$link_to_code = "Berhubung Kod:";
}
if ($filing_code_link == NULL) {
$link_to_code = " ";
}
if($parentid == '0') $parentid = "#";
$selected = false;$opened = false;
if($row['id'] == 2){
$selected = true;$opened = true;
}
$folders_arr[] = array(
"id" => $row['id'],
"parent" => $parentid,
"text" => $row['name'] . ' ' ."<span id='open' style='font-size:9px;'>".$refer_to_code .$row['filing_code_refer']."</span>" .' '. "<span id='open' style='font-size:9px;'>".$link_to_code .$row['filing_code_link']."</span>" .' '. "<span id='open' style='font-size:9px;'>".$row['description_update']."</span>",
"category" => $row['category'],
"filing_code_refer" => $row['filing_code_refer'],
// "status" => $row['status'], // status 0 is inactive, status 1 is active
"data" => array("status" => $row['status'],"add_underline"=>$row['add_underline']) ,
"state" => array("selected" => $selected,"opened"=>$opened)
);
}
?>
<script>
var colorNodes = function(nodelist) {
var getStrike = function(status) {
if (status === "0") {
return "line-through";
} else {
return "";
}
};
var getUnderline = function(add_underline) {
if (add_underline === "1") {
return " underline;text-underline-position: under;";
} else {
return "";
}
};
var tree = $('#folder_jstree').jstree(true);
nodelist.forEach(function(n) {
tree.get_node(n.id).a_attr.style = "color:" + getColor(parseInt(n.text.substr(0, 3), 10))+ ";"+"text-decoration:" + getStrike(n.data.status) + getUnderline(n.data.add_underline);
tree.redraw_node(n.id); //Redraw tree
colorNodes(n.children); //Update leaf nodes
});
};
</script>
This is my jsfiddle: https://jsfiddle.net/mLr5w2pd/1/
My expected result is like below the picture:
Updated
Below is show the content in the js tree.
<!-- Initialize jsTree -->
<div id="folder_jstree" title=""></div>
<!-- Store folder list in JSON format -->
<textarea style="" id='txt_folderjsondata'><?= json_encode($folders_arr) ?></textarea>
Updated 2
add below css to make the span inside the jstree-anchor as inline-block, then it will not have 'line-through'
.jstree-anchor span {
display: inline-block;
}
check the fiddle https://jsfiddle.net/mL407ya1/
and if you notice you have line-through in last, that is because of space in below code line #2 (text)-
{
"id":"753","parent":"#",
"text":"199 test <span id='open' style='font-size:9px;'>Rujuk Kod:190-1-1<\/span> <span id='open' style='font-size:9px;'> <\/span> <span id='open' style='font-size:9px;'> <\/span>",
"category":"jtm",
"filing_code_refer":"190-1-1",
"data":{"status":"0","add_underline":"0"},
"state":{"selected":false,"opened":false}
}
if you can remove the space between <span> and </span> it will work as expected.
UPDATE
if you can't remove the spaces from source, in code you can remove the space using regex. while you are parsing string to json array, remove the extra space before parsing. try below
let txtVal = $('#txt_folderjsondata').val();
txtVal = txtVal.replace(/> </g, '><');
var folder_jsondata = JSON.parse(txtVal);
Try the below fiddle.
https://jsfiddle.net/mL407ya1/1/
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;
}
}
?>
How can I refresh second select option when first select option is changed?
I am generating the array here for patient_code2:
//GENERATE NUMBERS FOR CYCLE
function patsient(selector) {
var i;
for (i = 1; i <= 99; i++) {
var text = '0' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 2, 2));
}
}
patsient(document.getElementById("patient_code2"));
I am generating the array for patient_code here:
function myFunction(selector) {
var i;
for (i = 1; i <= 999; i++) {
var text = '00' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 3, 3));
}
}
//usage:
myFunction(document.getElementById("patient_code"));
Here I am inserting the last value from database to the field:
//INSERT THE VALUE FROM DATABASE
var tsykkel_id = '<?php foreach ($tsykkel_id as $row){echo $row['patsiendi_tsykkel'];}?>';
$('#patient_code2')[0].options[parseInt(tsykkel_id)].selected = true;
$(document).ready().on('change', '#patient_code2', function () {
var index = $('option:selected', $(this)).index();
$('option', $(this)).each(function (i, x) {
if (i < index) { $(this).remove(); }
});
});
HTML
<select name="patient_code" data-placeholder="" id="patient_code" class="chosen-select form-control" tabindex="2">
</select>
<label class="control-label">Tsükkel:</label>
<select name="patient_code2" data-placeholder="" id="patient_code2" class="chosen-select form-control" tabindex="2">
</select>
So lets say that person chooses 002 from the first then the second should start from 01 again.
try this then. Code is tested.
$(document).ready().on('change','#patient_code2',function(){
var index = $('option:selected',$(this)).index();
$('option',$(this)).each(function(i,x){
if(i<index){$(this).remove();}
});
$('select#patient_code').prop('selectedIndex', 0);
});
fiddle : http://jsfiddle.net/roullie666/69j94ro6/2/
You can just start printing after the match has been found. I am writing both ways since you asked?
For javascript version use roullie's no point duplicating.
<?php
$flag = false;
foreach ($tsykkel_id as $row) {
if ($selected) {
$flag = true;
}
if ($flag) {
$row['patsiendi_tsykkel'];
}
}?>
My question is to get onMouseover,onMouseout,onMousedown,onClick on a table row. For which i am calling javascript userdefined functions.
onMouseover --- Background color should change.
onMouseout --- Reset to original color
onClick --- First column checkbox/radio button should be set and background color should change
onMousedown --- background color should change.
My code in html is:-
<tr onMouseOver="hover(this)" onMouseOut="hover_out(this)" onMouseDown="get_first_state(this)" onClick="checkit(this)" >
and the methods in javascripts are:-
var first_state = false;
var oldcol = '#ffffff';
var oldcol_cellarray = new Array();
function hover(element) {
if (! element) element = this;
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.style.fontWeight != 'bold') {
for (var i = 0; i<element.cells.length; i++) {
if (element.cells[i].className != "no_hover") {
oldcol_cellarray[i] = element.cells[i].style.backgroundColor;
element.cells[i].style.backgroundColor='#e6f6f6';
}
}
}
}
// -----------------------------------------------------------------------------------------------
function hover_out(element) {
if (! element) element = this;
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.style.fontWeight != 'bold') {
for (var i = 0; i<element.cells.length; i++) {
if (element.cells[i].className != "no_hover") {
if (typeof oldcol_cellarray != undefined) {
element.cells[i].style.backgroundColor=oldcol_cellarray[i];
} else {
element.cells[i].style.backgroundColor='#ffffff';
}
//var oldcol_cellarray = new Array();
}
}
}
}
// -----------------------------------------------------------------------------------------------
function get_first_state(element) {
while (element.tagName != 'TR') {
element = element.parentNode;
}
first_state = element.cells[0].firstChild.checked;
}
// -----------------------------------------------------------------------------------------------
function checkit (element) {
while (element.tagName != 'TR') {
element = element.parentNode;
}
if (element.cells[0].firstChild.type == 'radio') {
var typ = 0;
} else if (element.cells[0].firstChild.type == 'checkbox') {
typ = 1;
}
if (element.cells[0].firstChild.checked == true && typ == 1) {
if (element.cells[0].firstChild.checked == first_state) {
element.cells[0].firstChild.checked = false;
}
set_rowstyle(element, element.cells[0].firstChild.checked);
} else {
if (typ == 0 || element.cells[0].firstChild.checked == first_state) {
element.cells[0].firstChild.checked = true;
}
set_rowstyle(element, element.cells[0].firstChild.checked);
}
if (typ == 0) {
var table = element.parentNode;
if (table.tagName != "TABLE") {
table = table.parentNode;
}
if (table.tagName == "TABLE") {
table=table.tBodies[0].rows;
//var table = document.getElementById("js_tb").tBodies[0].rows;
for (var i = 1; i< table.length; i++) {
if (table[i].cells[0].firstChild.checked == true && table[i] != element) {
table[i].cells[0].firstChild.checked = false;
}
if (table[i].cells[0].firstChild.checked == false) {
set_rowstyle(table[i], false);
}
}
}
}
}
function set_rowstyle(r, on) {
if (on == true) {
for (var i =0; i < r.cells.length; i++) {
r.style.fontWeight = 'bold';
r.cells[i].style.backgroundColor = '#f2f2c2';
}
} else {
for ( i =0; i < r.cells.length; i++) {
r.style.fontWeight = 'normal';
r.cells[i].style.backgroundColor = '#ffffff';
}
}
}
It is working as expected in IE.
But coming to firefox i am surprised on seeing the output after so much of coding.
In Firefox:--
onMouseOver is working as expected. color change of that particular row.
onClick -- Setting the background color permenantly..eventhough i do onmouseover on different rows. the clicked previous row color is not reset to white. -- not as expected
onclick on 2 rows..the background of both the rows is set..Only the latest row color should be set. other rows that are selected before should be set back..not as expected i.e if i click on all the rows..background color of everything is changed...
Eventhough i click on the row. First column i.e radio button or checkbox is not set..
Please help me to solve this issue in firefox. Do let me know where my code needs to be changed...
Thanks in advance!!
Sorry for making everything inline, but this should work in all browsers:
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
Here is a complete page you can test out:
<html>
<head>
<style type="text/css">
tr.click{
background:yellow;
}
tr.hover{
background:green;
}
</style>
</head>
<body>
<table border="1">
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
<tr onmouseover="this.className += ' hover'" onmouseout="this.className = this.className.replace(/(^|\s)hover(\s|$)/,' ');" onclick="if(this.getElementsByTagName('input')[0].checked){this.className = this.className.replace(/(^|\s)click(\s|$)/,' ');this.getElementsByTagName('input')[0].checked = false;}else{this.className += ' click';this.getElementsByTagName('input')[0].checked = true;}">
<td>
<input type="checkbox" readonly="readonly"/> click me
</td>
</tr>
</table>
</body>
</html>
I would strongly advise moving everything to an external JS file and using some sort of initialization function to assign the event listeners, instead of writing them all inline like me.
I hope this helps in some way.
There may be a particular reason you haven't, but have you considered using a library such as JQuery to tackle this? What you're trying to achieve here could be done very easily and simply with JQuery's CSS-like selectors and .parent/.parents.
As MartyIX says, I would start by using console.log and/or breakpoints in Firebug / Chrome to check exactly which code blocks are being executed. Using the javascript debugging tools can be a little daunting at first until you get how each of the options (step into, step over) work, but they do allow you to check that the code is working as you think it is very easily.
One thing I notice in checkit() - be careful with where you declare variables. I'm not an expert with javascripts variable scoping, but to me it looks like the typ variable only exists within the if block. I would declare "var typ" before the if block and use a third value or second variable to check whether any checkbox or radio is found (what happens if no checkbox and no radio is found?)