i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
<head>
<script src="inc/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="inc/facebox.js" type="text/javascript"></script>
<body>
<a href="addevent.php" rel="facebox" >link</a>
</body>
addevent.php
<head>
<script src="inc/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="inc/facebox.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i<elemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i < len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i<formNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i < max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
</script>
<script type="text/javascript">
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i < lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") > -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j < labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
</script>
</head>
<form name="eventAgendaForm" id="eventAgendaForm" >
<ul class="checklist cl3">
<li ><label for="c1">
<input id="checkId" name="checkName" value="1" type="checkbox" >
</label></li></ul>
<input class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" />
</form>
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.
Related
I am trying to make a text box that when you type in it, it pulls up suggestions underneath that come from a recordset. For some reason when you type in the field, I only get the first letter. It think it has to do with the json_encode part. When I changed the array to be just text: "Brainpop","Google", etc. it worked fine. Any thoughts? This is the coding I based it off of:
https://www.w3schools.com/howto/howto_js_autocomplete.asp
<script type="application/javascript">
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}</script>
<script>
//now put it into the javascript
var software_list = <?php echo json_encode($types2, JSON_UNESCAPED_SLASHES), "\n"; ?>;
</script>
<?php
$query1 = "SELECT software_name from software";
$result = mysqli_query($sdpc_i, $query1);
$types = array();
while ($row = $result->fetch_assoc()) {
$types[] = '"'.$row['software_name'].'"';
}
$types2 = implode(",",$types);
?>
<div class="autocomplete"><input type="text" name="software_name" id="myInput" class="form-control col-md-8" value="" required></div><script>
autocomplete(document.getElementById("myInput"), software_list);
</script>
</div>
The following code in Single.php file is not working as expected. $post->ID and is_user_logged_in() are getting null values. If all works fine i can have the post id as array in local storage.
<script>
window.onload = function() {
var logged_in='<?php echo is_user_logged_in() ?>';
if (logged_in==false || logged_in==0) {
var myArray = JSON.parse(localStorage.getItem('articles') )|| [];
var article_postid='<?php echo $post->ID ?>';
//check already read? if not push into array
index = is_exist.call(myArray, article_postid);
if(!index){
myArray.push(article_postid);
localStorage.setItem('articles', JSON.stringify(myArray));
}
}
}
var is_exist = function(article_postid) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = article_postid !== article_postid;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(article_postid) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === article_postid) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, article_postid) > -1;
};
</script>
Please try this code.
Add this code to your activated theme's functions.php file and check.
function add_js_code_to_footer(){
if( is_singular( 'post' ) ){
global $post;
?>
<script>
window.onload = function() {
var logged_in='<?php echo is_user_logged_in() ?>';
if (logged_in==false || logged_in==0) {
var myArray = JSON.parse(localStorage.getItem('articles') )|| [];
var article_postid='<?php echo $post->ID ?>';
//check already read? if not push into array
index = is_exist.call(myArray, article_postid);
if(!index){
myArray.push(article_postid);
localStorage.setItem('articles', JSON.stringify(myArray));
}
}
}
var is_exist = function(article_postid) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = article_postid !== article_postid;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(article_postid) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === article_postid) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, article_postid) > -1;
};
</script>
<?php
}
}
add_action("wp_footer","add_js_code_to_footer");
Ok. I need help with this. For some reason the onreadystatechange is fired multiple times. I really need to get this figured out tonight. It's the last task I have left and I don't know what to do or what's causing it. Please help.
I'm using AJAX (ndhr) to send over JSON 'Y-m-d h:i:s' to PHP to use the strtotime() function to return 'm-d-Y' back through AJAX. The JSON and PHP work great, but when the onreadystatechange is fired it does it multiple times. Almost like the readyState == 4 more times than it does.
var divs_d = ["d_2009", "d_2010", "d_2011"];
function ajax_get_json(cdiv,ocdv,ed){
var hr = new XMLHttpRequest();
hr.open("GET", "/json/sample.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
cdiv.innerHTML = "";
var data = JSON.parse(hr.responseText);
var cad = data.comm_archive;
var rndate;
var nda = new Array();
var ndac = 0;
var ec = 0;
for (ni = 0; ni < cad.length; ni++) {
if (cad[ni].year == ocdv) {
ec = ec + 1;
ed.innerHTML = '<h4>' + ocdv + ' (' + ec + ' entries)</h4>';
var ndhr = new XMLHttpRequest();
var url = "/inc/strtotime.php";
var vars = "ndate=" + cad[ni].publish_date;
ndhr.open("POST", url, true);
ndhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ndhr.onreadystatechange = function () {
if (ndhr.readyState == 4 && ndhr.status == 200) {
nda[ndac] = ndhr.responseText;
ndac = ndac + 1;
}
}
ndhr.send(vars);
}
}
nda.sort(function (a, b) { return b - a });
for (ndai = 0; ndai < ndac; ndai++) {
cdiv.innerHTML += '<h4>' + nda[ndai] + '</h4>';
}
}
}
hr.send(null);
}
function optionCchange() {
var ocdv = document.getElementById("optionCdate").value;
var ed = document.getElementById("ediv");
for (i = 0; i < divs_d.length; i++) {
var cdiv = document.getElementById(divs_d[i]);
if (divs_d[i] == "d_" + ocdv) {
cdiv.className = "bddiv show";
ajax_get_json(cdiv,ocdv,ed);
} else {
cdiv.className = "bddiv hide";
}
}
}
In your ndhr.onreadystatechange function ndhr represents the last ndhr created in the loop not the calling one, to reference the calling object use this.
ndhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
nda[ndac] = this.responseText;
ndac = ndac + 1;
}
}
The the last for(ndai = 0; ndai < ndac; ndai++) is behaving as you expect because of the asynchronous nature of ajax, by the time that code is executed the ajax requests have not finished yet. You'll have to execute this code in the on ready change state callback. Just use a counter to check if all the ajax requests have finished then execute the code.
If you need run the code once, you don't have to be anxious about how many times readystate 4 was fired. Simply use a boolean variable to check if the block of code has been executed.
Here's a pseudocode example of my idea.
executed = false;
if (readystate && (executed == false))
{
blablabla;
executed = true;
}
else
{
sry your code has been executed;
}
I am writing a tag system based on http://jsfiddle.net/joevallender/QyqYW/1/ but when i try to add new tag by typing in textarea, it works fine but when i click on any tag, previous new text will be removed.
HTML
<textarea id="tags"></textarea>
<div id="tagButtons"></div>
Javascript
var tags = [
'JavaScript',
'jQuery',
'HTML5',
'CSS3'
];
var selectedTags = [];
for(var i = 0; i < tags.length; i++) {
var el = $('<span>').text(tags[i]);
$('#tagButtons').append(el);
}
$('#tagButtons span').click(function(){
var val = $(this).text();
var index = selectedTags.indexOf(val);
if(index > -1) {
var removed = selectedTags.splice(index,1);
$(this).removeClass('selected');
} else {
selectedTags.push(val);
$(this).addClass('selected');
}
$('#tags').val(selectedTags.join(', '));
});
Your problem is in this line
$('#tags').val(selectedTags.join(', '));
It's overwriting what was in the textarea before.
EDIT:
Try it :
http://jsfiddle.net/QyqYW/92/
var tags = [
'JavaScript',
'jQuery',
'HTML5',
'CSS3',
'PHP'
],
keys = "";
var selectedTags = [];
for(var i = 0; i < tags.length; i++) {
var el = $('<span>').text(tags[i]);
$('#tagButtons').append(el);
}
//changed click event to "on" event..
//it seems that click doesn't bind to dynamically added elements
$('#tagButtons').on("click" , "span" , function(){
//Checks if you've forgot to type "," and then adds your tag
if(keys != ""){
selectedTags.push(keys);
$('#debug').prepend($('<div>').html('Added: ' + keys));
var newEl = $('<span class="selected">').text(keys);
$('#tagButtons').append(newEl);
$('#tags').focus().val(selectedTags.join(', ') + ", ");
keys = "";
}
var val = $(this).text();
var index = selectedTags.indexOf(val);
if(index > -1) {
var removed = selectedTags.splice(index,1);
$(this).removeClass('selected');
$('#debug').prepend($('<div>').html('Removed: ' + removed));
$('#tags').focus().val(selectedTags.join(', ') + ", ");
} else {
selectedTags.push(val);
$(this).addClass('selected');
$('#debug').prepend($('<div>').html('Added: ' + val));
$('#tags').focus().val(selectedTags.join(', ') + ", ");
}
});
//adds tag after you type ","..
//if you forgot to, look above the first line in the on event
$("#tags").keydown(function(evt){
if(evt.which == 188){
selectedTags.push(keys);
$('#debug').prepend($('<div>').html('Added: ' + keys));
var newEl = $('<span class="selected">').text(keys);
$('#tagButtons').append(newEl);
$('#tags').val(selectedTags.join(', '));
keys = "";
} else if(evt.which ==8){
//for after adding tag you can't use Backspace to delete it.
//remove tag from butotns
if(keys == ""){
evt.preventDefault();
} else {
keys += String.fromCharCode(evt.which).toLowerCase();
}
});
I continued working on the jsfiddle on your original question
add and remove multiple tag by onclick to textarea
see http://jsfiddle.net/joevallender/QyqYW/14/
To be honest I think you should just put the tags into a seperate div or input. They should be stored seperately in a db anyway.
$(this).text();
Abowe, will only return value which was rendered oryginaly into DOM from html. Whatever you type into textarea is not there yet, you have to hook on ('#tags').on('keyup' function () {});
and store what was typed in order to include it to textarea later.
I am trying to develop a select box so that I can change the selected option dynamically
e.g.
selectbox option display message
---------------------------------------------
field 1 text
field 2 integer
field 3 bool
There are three select boxes. The first select box provide three options.
when select box 1 is selected, the other select boxes will have only 2 options (excluding the selected one)
When select box 2 is selected, the other select boxes will have only 1 option (excluding the selected two)
When a select box's value changes, the appropriate message is displayed.
All of the text that will be displayed is read in from a database as an array in the following format:
name text
id integer
address text
Then I create a select box with the three option
When I set select box 1's value as name, the text message is displayed, and so on.
How should I implement this? (I hope you get my idea) Thank you again for your help.
Thank you
I'd suggest something akin to the following:
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset');
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};
JS Fiddle demo.
Edited to add the messages, as requested in comments (which I overlooked in the actual question...):
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset'),
msgs = ['text','integer','boolean'];
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
hideMessage(elem);
};
function displayMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = msgs[i];
span.style.display = 'block';
}
}
};
function hideMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = '';
span.style.display = 'none';
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};
sel1.onfocus = function() {
displayMessage(this);
};
sel2.onfocus = function() {
displayMessage(this);
};
sel3.onfocus = function() {
displayMessage(this);
};
sel1.onblur = function() {
hideMessage(this);
sel2.onblur = function() {
hideMessage(this);
};};
sel3.onblur = function() {
hideMessage(this);
};
JS Fiddle demo.
Take a look at this plugin, maybe it can help you.
For the data than you can put a php foreach for the <option> element on the select.