how to create checkbox events that call jQuery functions on other pages? - php

I'm wanting a checkbox in theme.php to trigger a function in front.php
that changes a css file from default with a white background to blue with a blue background.
Unchecking the checkbox reverts it back to default.
I've tried various different methods from having the script in theme.php to moving it to front.php using all the different jQuery functions including load, change, click, post, using if/else, appending to the header tags in front.php...
nothing works.
in theme.php
<div class="main-content">
<input type="checkbox" id="front"/>
<label for="front">FrontEnd</label>
</div>
and in front.php
const frontEnd = document.querySelector("#front");
frontEnd.addEventListener('change', function(e) {
if(frontEnd.checked){
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "css/blue.css";
document.getElementsByTagName("head")[0].appendChild(link);
}else{
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "css/default.css";
document.getElementsByTagName("head")[0].appendChild(link);
}
});
any tips on what I may be missing?
cheers.

$(document).ready(function($){
$('#test').click(function(){
$("#main-div").toggleClass('class-yellow');
});
// $('#test').prop('checked', true); //Checks it
// $('#test').prop('checked', false); //Unchecks it
});
.class-yellow {
background:yellow;
width:200px;
padding:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='main-div'>
<label for="test">adding style when click</label>
<input type="checkbox" id='test'>
</div>

Related

How to freeze the checkbox after clicking checkbox? I try it but it not working

I try to freeze checkbox but it not working. I mention the name of the checkbox as is_top_property. Kindly help me. Here the code
<div class="panel">
<div class="panel-title"><strong>{{__("Top Property")}}</strong></div>
<div class="panel-body">
<div class="form-group">
<input type="checkbox" name="is_top_property" onclick="check();" #if($row->is_top_property) checked #endif value="1"> {{__("Enable Top Property")}}
<script>
public function check(){
if($("is_top_property").is(":checked")){
alert("Thanks for selecting");
$('is_top_property').attr('disabled',true);
}
}
</script>
</div>
</div>
</div>
This is how to code your example in jQuery proper:
Use the correct selector - here $("[name=is_top_property]") but you could also add a class and use $(".is_top_property")
do not use inline event handling
We need a timeout to check the box before alerting
I added code to visually disable the label too
$(function() {
$("[name=is_top_property]").on("change", function() {
const checked = this.checked;
if (checked) setTimeout(function() { alert("Thanks for selecting") }, 10); // give time to show the checkmark
$(this)
.prop('disabled', checked)
.parent('label').toggleClass("disabled", checked)
});
});
.disabled {
color: grey
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="checkbox" name="is_top_property" value="1"> Enable Top Property</label>
Check() function not required there, just need to find the check box in dom element and disable when it checked.
$(document).ready(function() {
$("#is_top_property").click(function(){
if($(this).prop("checked") == true){
$(this).attr('disabled',true);
}
});
}

Show loader during PHP processing after an HTML form submission

I have an HTML form like the one shown below, which after submitting is processed by PHP:
<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="POST" enctype="multipart/form-data" id="decisions_form">
<!-- ... -->
<div style="text-align:center;">
<input type="submit" name="submit" value="Submit Decisions" id="decisions_button">
</div>
</form>
PHP does some processing, which could take a few seconds. After processing is complete, I refresh the page as below (probably not best practice, I don't know):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// PHP...
}
echo ('<meta http-equiv="refresh" content="0.1;">');
?>
I would like to show a full-screen "loader/spinner", which would be activated after submitting and during PHP processing. Normally, If I understand it correctly, this loader/spinner should be interrupted by the refresh page command -- which is what I want
Looking for such loaders was unsuccessful, if not totally confusing for a inexperienced person like me.
It would be ideal if I could avoid JS and do it in a pure HTML/CSS fashion (is it even possible?).
I am not aware of a mechanism to do it in pure HTML. There are probably other and more sophisticated ways to do it than what I show below, but this worked well for me. Every time you place a call to the server, the ajax start function executes and delays 1 second (change the delay however you want) and then displays the waiting gif. When the ajaxStop function is called upon completion of the server call and stops the wait gif and enables the buttons. Note this should be the first tag in your html file after the css definitions.
Javascript code
<script defer>
$( document ).ready(function() {
// gif on 1 second timer delay before displaying, so user does not have it appear to quickly if the delay is short.
var loadingTimer;
$(document).ajaxStart(function() {
$(':button').prop('disabled', true); // disable all the buttons
loadingTimer = setTimeout("$('#process-wait').show()", 1000); // show the waiting gif
});
$(document).ajaxStop(function() {
clearTimeout(loadingTimer);
$("#process-wait").hide(); // hide the waiting gif
$(':button').prop('disabled', false); // enable all the buttons
});
});
</script>
Here is the css you need to go along with that. You can make it as big as you want, by adjusting the height and width values. Pick your own gif image simply set the url parameter to the directory path and name of the gif file.
#process-wait {
background: transparent url(images/process-wait.gif);
background-repeat: no-repeat;
height: 150px;
width: 150px;
z-index: 99999;
display:none;
position: absolute;
top: 50%;
left: 50%;
margin-left: 10px;
margin-top: 0px;
transform: translate(-50%, -50%);
Here's a complete example:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
header("Content-Type: application/json");
echo json_encode($_SERVER);
exit;
}
?>
<!doctype html>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
<div hidden class="spinner-border text-primary" role="status">
<span class="sr-only">Loading...</span>
</div>
<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="POST" enctype="multipart/form-data" id="decisions_form">
<input type="text" name="dummy" value="dummy value">
<!-- ... -->
<div style="text-align:center;">
<input type="submit" name="submit" value="Submit Decisions" id="decisions_button">
</div>
</form>
<div class="complete" hidden>
Submission received<br>
<button class="reset">Reset</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
<script>
window.addEventListener('load', () => {
const decisionsForm = document.querySelector('#decisions_form');
const spinner = document.querySelector('.spinner-border');
const complete = document.querySelector('.complete');
const resetButton = document.querySelector('.reset');
// Show spinner, hide form
function formSending() {
spinner.removeAttribute('hidden');
decisionsForm.style.display = 'none';
}
// Hide spinner, show complete message
function formSent() {
complete.removeAttribute("hidden");
spinner.setAttribute("hidden", true);
}
// Show form, hide everything else
function reset() {
decisionsForm.style.display = 'block';
spinner.setAttribute("hidden", true);
complete.setAttribute("hidden", true);
}
// Send form data in the background
async function submitDecisionsForm(event) {
// Display spinner
formSending();
// Collect data to send
// event.target = the form
// event.target.action the action property on <form action="">
// the POST body gets set by reading the data from the form object (event.target)
const response = await fetch(event.target.action, {method: "POST", body: new FormData(event.target)});
// Submit is complete.. show the complete message and reset button
formSent();
// Format the response if you want to use it later
const responseJson = await response.json(); // or response.text() depending on what send back from the server
// Output to browser's dev console for debugging
console.log(text);
}
// Capture submit event
decisionsForm.addEventListener("submit", (event) => {
// Stop form from submitting immediately by default
event.preventDefault();
// Send form data in the background
submitDecisionsForm(event);
});
// demo: reset the form when clicking the reset button
resetButton.addEventListener('click', reset);
});
</script>
See comments in the code for explanation of parts.

<input type="text" lose focus after 1'st key press in chrome

I'm having a textbox which is "observed" by a jquery for several actions, all code being a part of a "search-as-you-type" form.
Well, everything works flawlessly on Mozilla but in Chrome, the textbox is losing focus after 1'st hit, so I have to click again in textbox to continue search. Any clue ? My experience is leading me to a bug
<div class="search-container">
<input type="text" placeholder="Search.." name="searchb" >
</div>
<script>
$('input[name="searchb"]').on('input propertychange
paste',function(){
if ($(this).val().length > 2){
document.cookie = "psearch="+this.value+";"+"path=/";
window.open("main.php?psearch="+this.value, "iframe_a");
}
});
</script>
Your search input is losing focus because the new opened window will gain focus.
Moreover, with your current code, a new window is opened each time an input with a length more than two characters is detected.
There are many solutions, here are two of them. I didn't put them into code snippets because they will not work correctly.
AJAX
You can get the generated HTML of main.php thanks to an AJAX request:
HTML
<div class="search-container">
<input type="text" placeholder="Search.." name="searchb" >
</div>
<div id="searchb-result"></div>
Javascript
$('input[name="searchb"]').on('input propertychange paste', function() {
// Empties the result container.
$('#searchb-result').empty();
if ($(this).val().length > 2) {
document.cookie = `psearch=${this.value};path=/`;
// Gets the HTML by AJAX and adds it to the result container.
$.get('main.php', `psearch=${this.value}`, (html) => {
$('#searchb-result').html(html);
});
}
});
<iframe>
You can load your URL in a <iframe> tag.
HTML
<div class="search-container">
<input type="text" placeholder="Search.." name="searchb" >
</div>
<iframe style="display:none;"></iframe>
Javascript
$('input[name="searchb"]').on('input propertychange paste', function() {
// Hides the <iframe> by default.
$('iframe').hide();
if ($(this).val().length > 2) {
document.cookie = `psearch=${this.value};path=/`;
// Updates the <iframe> source when an input is detected.
$('iframe')
.attr('src', `main.php?psearch=${this.value}`)
.show();
}
});
I rewrote the entire section without jquery , clean and a with bit of 4'th grade approach, but it works. The lost focus was the problem.
<div class="search-container">
<input type="text" placeholder="Search.." name="searchb" id="search" autofocus="autofocus">
</div>
<script>
window.name = 'parent';
search.onchange = search.oninput = search.onpaste = function() {
var sv = search.value;
if (sv.length > 3){
var search_window = window.open("main.php?psearch="+sv, "iframe_a");
parent.focus();
}
else {
document.cookie = "psearch=";"path=/";
var search_window = window.open("main.php?psearch=", "iframe_a");
parent.focus();
}
}
</script>

Mini AJAX File Upload multiple upload blocks on same page

I am using the following plugin: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/
The problem I have is that I have multiple upload instances on the same page (for example 1-header image 2-footer image)
But only the first input actually works, the other one does not and I don't get an error client or server side..
If I Google to try find an alternative I get millions of "multiple uploads at the same time" which is not what im looking for.
here is the page code:
<form id='upload' method='post' action='URLtoServerside' enctype='multipart/form-data'>
<div id='drop'>
Drop Here
<a>Browse</a>
<input type='file' name='upl' multiple />
</div>
<input style='visibility:hidden' id='".$var2['id']."' value='page_session_weo' />
<ul style='display:none'>
<!-- The file uploads will be shown here -->
</ul>
</form>
<form id='upload' method='post' action='URLtoServerside' enctype='multipart/form-data'>
<div id='drop'>
Drop Here
<a>Browse</a>
<input type='file' name='upl' multiple />
</div>
<input style='visibility:hidden' id='".$var2['id']."' value='page_session_weo' />
<ul style='display:none'>
<!-- The file uploads will be shown here -->
</ul>
</form>
PHP Code:
$allowed = array('png');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'images/'.$name.'.png')){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
Can someone please either tell me how to get this to work with multiple uploads on the same page, or recommend an alternative.
(I do require drag and drop as well as 'browse' functionality)
<input type="button" name="button" value="添加附件" onclick="addInput()">
<span id="upload"></span>
js
<script type="text/javascript">
var attachname = "attach";
var i=1;
function addInput(){
if(i>0){
var attach = attachname + i ;
if(createInput(attach))
i=i+1;
}
}
function createInput(nm){
var aElement=document.createElement("input");
aElement.name=nm;
aElement.id=nm;
aElement.type="file";
aElement.size="50";
if(document.getElementById("upload").appendChild(aElement) == null)
return false;
return true;
}
I just came with this problem.
My solution:
I duplicate the script.js from miniupload with script2.js or whatever.
In that script, the only thing I did was changing name from upload to upload_files and drop to drop_files.
Like this:
var ul = $('#upload_files ul');
$('#drop_files a').click(function(){
// Simulate a click on the file input button
// to show the file browser dialog
$(this).parent().find('input').click();
});
// Initialize the jQuery File Upload plugin
$('#upload_files').fileupload({
(...)
My HTML:
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop" style="text-align:center ;align-content:center">
Add images
<a>Select</a>
<input type="file" name="upl" multiple />
</div>
<ul>
<!-- The img uploads will be shown here -->
</ul>
</form>
<form id="upload_files" method="post" enctype="multipart/form-data">
<div id="drop_files" style="text-align:center ;align-content:center">
Add files
<a>Select</a>
<input type="file" name="upl_file" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>
And then modify the css too.
the original css is like this:
#upload{
font-family:'PT Sans Narrow', sans-serif;
background-color:#373a3d;
background-image:-webkit-linear-gradient(top, #373a3d, #313437);
background-image:-moz-linear-gradient(top, #373a3d, #313437);
background-image:linear-gradient(top, #373a3d, #313437);
width:250px;
padding:30px;
border-radius:3px;
margin:20px 20px 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
I added code to reflect upload_files
#upload_files{
font-family:'PT Sans Narrow', sans-serif;
background-color:#373a3d;
background-image:-webkit-linear-gradient(top, #373a3d, #313437);
background-image:-moz-linear-gradient(top, #373a3d, #313437);
background-image:linear-gradient(top, #373a3d, #313437);
width:250px;
padding:30px;
border-radius:3px;
margin:20px 20px 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
Its not a "clean" solution, but it works :)
I was having this issue for a long time, until I figured I would fix it. Here's what I did.
In the form, I added classes to the #upload and #drop elements. I renamed them to #upload1, #upload2 and #drop1, #drop2
<form id="upload1" class="upload" method="post" action="upload.php" enctype="multipart/form-data">
<div id="drop1" class="drop">
...
On the JS side (script.js), I wrapped the whole thing in a proper jQuery init and I added a jQuery each at the top and wrapped the entire main area in this:
(function($){
$('.upload').each(function (_key, _value) {
var $this = $(this);
var ul = $this.find('ul');
$this.find('#drop a').click(function(){
...
});
})(jQuery);
I also replaced all instances of #upload with $this and all instances of #drop with $this.find('.drop')
Basically, you're replacing the ids with class names, and adjusting your script accordingly, and wrap it all in a big each loop.
PS. I also like to add a complete callback to my script file so I can do things after everything.
complete:function() {
},
Please let me know if this works for you.
UPDATE:
Modified the code to work dynamically:
(function($){
$(document).ready(function(){
$(document).on('click','.drop a', function(){
var $drop = $(this);
var $this = $drop.closest('.upload');
var ul = $this.find('ul');
$this.parent().find('input').click();
//console.log($this.find('.drop'));
});
window.init_file_upload = function($element) {
// Initialize the jQuery File Upload plugin
$($element).fileupload({
//var $this = $(this);
// This element will accept file drag/drop uploading
dropZone: $element.find('.drop'),
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function (e, data) {
ul = $element.find('ul');
//console.log('adsf');
$('.ajaxform button.submit').attr('disabled','disabled');
var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"'+
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span><i class="fa fa-check-circle-o"></i> OK</span></li>');
// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<i>' + formatFileSize(data.files[0].size) + '</i>');
// Add the HTML to the UL element
ul[0].innerHTML = '';
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
},
complete:function(e, data) {
// console.log(e,data);
var _data = $.parseJSON(e.responseText);
// console.log(_data);
postAjax(_data);
$('.ajaxform button.submit').removeAttr('disabled');
},
fail:function(e, data){
// Something has gone wrong!
data.context.addClass('error');
}
});
}
$('.upload').each(function() {
window.init_file_upload($(this));
});
// Simulate a click on the file input button
// to show the file browser dialog
// Prevent the default action when a file is dropped on the window
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
// Helper function that formats the file sizes
function formatFileSize(bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
});
})(jQuery);

disabiling Ckeditor with javascript

I have a ckeditor in my page which is created by the code below:
$ckeditor = new CKEditor();
$ckeditor->basePath = 'ckeditor/' ;
CKFinder::SetupCKEditor( $ckeditor, 'ckfinder/' ) ;
$config['height'] = '300';
$config['width'] = '700';
$initialValue = $initial['content'];
$ckeditor->editor('content', $initialValue, $config);
I want to disable this ckeditor based on the selection of a selectbox in the same page.
do you guys have any clue on this.
Thanks in advance.
Here it is, Just Copy & Paste: Version 3.6 or Newer
<html>
<head>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
var editor;
// The instanceReady event is fired, when an instance of CKEditor has finished
// its initialization.
CKEDITOR.on( 'instanceReady', function( ev ) {
editor = ev.editor;
// Show this "on" button.
document.getElementById( 'readOnlyOn' ).style.display = '';
// Event fired when the readOnly property changes.
editor.on( 'readOnly', function() {
document.getElementById( 'readOnlyOn' ).style.display = this.readOnly ? 'none' : '';
document.getElementById( 'readOnlyOff' ).style.display = this.readOnly ? '' : 'none';
});
});
function toggleReadOnly( isReadOnly ) {
// Change the read-only state of the editor.
// http://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-setReadOnly
editor.setReadOnly( isReadOnly );
}
</script>
</head>
<body>
<p>
<textarea class="ckeditor" id="editor1" name="editor1"></textarea>
</p>
<p>
<input id="readOnlyOn" onclick="toggleReadOnly();" type="button" value="Make it read-only" style="display:none">
<input id="readOnlyOff" onclick="toggleReadOnly( false );" type="button" value="Make it editable again" style="display:none">
</p>
</body>
</html>
Assuming you have included jQuery adapter following code should make it readonly. You can take the jQuery adapter from the example if not yet included.
<div class="wrapper">
<form id="myfrm" name="myfrm" class="myfrm" action="" method="post">
<textarea id="myeditor" name="myeditor"></textarea>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</div>​
and the js
$(document).ready(function(e) {
var myeditor = $('#myeditor');
myeditor.ckeditor();
myeditor.ckeditorGet().config.resize_enabled = false;
myeditor.ckeditorGet().config.height = 200;
myeditor.ckeditorGet().config.readOnly = true;
});
To enable or disable a ckeditor based on your selection of a select box you'd have to make a change event like this
$(document).ready(function(){
//put ckeditor initialization (the above) here.
$('#myselect').change(function(){
var x = $(this);
if(x.val()=='enable'){
myeditor.removeAttr('disabled');
}else if(x.val()=='disable'){
myeditor.attr('disabled','disabled');
}
myeditor.ckeditorGet().destroy();
myeditor.ckeditor();
});
});
What we are doing above is setting the original element to have attribute disabled="disabled" and reloading ckeditor after destroying the current instance. Check the JSFiddle Example 2.
JSFiddle Example
JSFiddle Example 2 to reflect OP's query
I did this the other day you want to use .setReadOnly (true) on the CKEDITOR instance and then use .setReadOnly (false) to re-enable it.

Categories