Getting Checkbox Data - javascript

Sorry to ask yet another simple question but program can be hard and like they say never be afraid to ask.
What I am trying to do is get jquery to detect if the checkbox has been click or not then when the user clicks the send button it will then go to PHP to say if it has been checked or not.
I have got form data to process to PHP such as the text fields but the check fields doesn't seem to want to work.
I have tried googling I have find nothing on my end
Here's the code
$(document).ready(function () {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
login_username: $('#login-username').val(),
login_password: $('#login-password').val(),
remember_me: $('#remember_me').find(":checked").val()
}
}
$(":checkbox").click(function(){
$("#remember_me").text(this.value)
})
$('#login_content').hover(function() {
$(this).css("background-color", "transparent");
});
$('#login_content').mouseleave(function() {
$(this).css("background-color", "white");
});
$('.error').hover(function() {
$(this).css("background-color", "transparent");
});
$('.notice').hover(function() {
$(this).css("background-color", "transparent");
});
$('#login_content').mouseleave(function() {
$('.error').css("background-color", "#ffecec");
$('.notice').css("background-color", "#e3f7fc");
});
$(window).load(function(){
$('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded
// run every 7s
setInterval('cycleImages()',4000);
})
function loading(e) {
$('#login_try').show();
}
function hide_loading(e) {
$('#login_try').hide();
}
function success_message(e) {
$('#success_login').html("We're Just Signing You In");
}
function clearfields() {
$('#login-username').val(''); //Clear the user login id field
$('#login_password').val(''); //Clear the user login password field
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'check.php',
type: 'post',
error: function () {
//If your response from the server is a statuscode error. do this!!!
clearfields();
},
beforeSend: function () {
loading(e);
},
data: {
login_username: $('#login-username').val(),
login_password: $('#login-password').val(),
}, // get current values
success: function (data) {
//if your response is a plain text. (e.g incorrect username or password)
hide_loading(e);
if(data.indexOf("<b>Welcome Back</b>") > -1) {
hide_loading(e);
success_message(e);
}
if(data.indexOf("You're Already Signed In!") > -1) {
alert('This operation could not be proceeded');
}
$('#loading').fadeOut();
$('#content').hide();
$('#content').fadeIn(1000).html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function (e) {
if (e.keyCode == 13) {
var username = $('#login-username').val();
check(e);
}
});
$('#submit_login').click(function (e) {
if (e.keyCode != 13) {
check(e);
}
});
});

var isChecked = ($("#check_box_id").is(':checked')) ? 1 : 0;
//send this variable to the php file.

Related

Button for a modal form not displaying or functioning

I've already been on here for a similar question, but moved this interaction in my code and have the same issue... but I believe with a different cause.
I have a page that has an "Email Me" button at the bottom of it:
http://danux.me/
When you click the "Email Me" button, an overlay should appear and with an email form in the middle of it. I had it working on a test page, and then moved all the items over to my index.html and it's not working.
My goal right now is just to get the overlay and form to pop up in the page.
I checked my paths to make sure they were right and I think they are, but I don't know how to parse or inspect php with Google's emulator to see where something might not be working.
I checked my index.html head link to the css, the javascript at the end of my index.html and then in the contact.js, there's a GET link that points down to the php file.
Also, I am unsure in the HTML how to "call"(?) the php or jquery on that button and if that's the issue. It worked before as is and I am assuming that class="contact" is what's making all this work? I don't know. I'd be interested to know how a class triggers a javascript file.
I also got ripped earlier for not having PHP, but I didn't know until today that can't be viewed, so I'll put it below. I'm not sure if it's helpful or not.
jQuery(function ($) {
var contact = {
message: null,
init: function () {
$('#contact-form input.contact, #contact-form a.contact').click(function (e) {
e.preventDefault();
// load the contact form using ajax
$.get("contact/data/contact.php", function(data){
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["15%",],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
});
},
open: function (dialog) {
// dynamically determine height
var h = 280;
if ($('#contact-subject').length) {
h += 26;
}
if ($('#contact-cc').length) {
h += 22;
}
var title = $('#contact-container .contact-title').html();
$('#contact-container .contact-title').html('Loading...');
dialog.overlay.fadeIn(200, function () {
dialog.container.fadeIn(200, function () {
dialog.data.fadeIn(200, function () {
$('#contact-container .contact-content').animate({
height: h
}, function () {
$('#contact-container .contact-title').html(title);
$('#contact-container form').fadeIn(200, function () {
$('#contact-container #contact-name').focus();
$('#contact-container .contact-cc').click(function () {
var cc = $('#contact-container #contact-cc');
cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
});
});
});
});
});
});
},
show: function (dialog) {
$('#contact-container .contact-send').click(function (e) {
e.preventDefault();
// validate form
if (contact.validate()) {
var msg = $('#contact-container .contact-message');
msg.fadeOut(function () {
msg.removeClass('contact-error').empty();
});
$('#contact-container .contact-title').html('Sending...');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: '80px'
}, function () {
$('#contact-container .contact-loading').fadeIn(200, function () {
$.ajax({
url: '/contact/data/contact.php',
data: $('#contact-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#contact-container .contact-loading').fadeOut(200, function () {
$('#contact-container .contact-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
error: contact.error
});
});
});
}
else {
if ($('#contact-container .contact-message:visible').length > 0) {
var msg = $('#contact-container .contact-message div');
msg.fadeOut(200, function () {
msg.empty();
contact.showError();
msg.fadeIn(200);
});
}
else {
$('#contact-container .contact-message').animate({
height: '30px'
}, contact.showError);
}
}
});
},
close: function (dialog) {
$('#contact-container .contact-message').fadeOut();
$('#contact-container .contact-title').html('Goodbye...');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: 40
}, function () {
dialog.data.fadeOut(200, function () {
dialog.container.fadeOut(200, function () {
dialog.overlay.fadeOut(200, function () {
$.modal.close();
});
});
});
});
},
error: function (xhr) {
alert(xhr.statusText);
},
validate: function () {
contact.message = '';
if (!$('#contact-container #contact-name').val()) {
contact.message += 'Name is required. ';
}
var email = $('#contact-container #contact-email').val();
if (!email) {
contact.message += 'Email is required. ';
}
else {
if (!contact.validateEmail(email)) {
contact.message += 'Email is invalid. ';
}
}
if (!$('#contact-container #contact-message').val()) {
contact.message += 'Message is required.';
}
if (contact.message.length > 0) {
return false;
}
else {
return true;
}
},
validateEmail: function (email) {
var at = email.lastIndexOf("#");
// Make sure the at (#) sybmol exists and
// it is not the first or last character
if (at < 1 || (at + 1) === email.length)
return false;
// Make sure there aren't multiple periods together
if (/(\.{2,})/.test(email))
return false;
// Break up the local and domain portions
var local = email.substring(0, at);
var domain = email.substring(at + 1);
// Check lengths
if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
return false;
// Make sure local and domain don't start with or end with a period
if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
return false;
// Check for quoted-string addresses
// Since almost anything is allowed in a quoted-string address,
// we're just going to let them go through
if (!/^"(.+)"$/.test(local)) {
// It's a dot-string address...check for valid characters
if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
return false;
}
// Make sure domain contains only valid characters and at least one period
if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
return false;
return true;
},
showError: function () {
$('#contact-container .contact-message')
.html($('<div class="contact-error"></div>').append(contact.message))
.fadeIn(200);
}
};
contact.init();
});
Is this the functionality you are looking for?
See:
http://www.joecodeman.com/ITServices/Demos/jQuery/ShowDemo_v01a.html
If this is the effect dgbenner is looking for... then it is just a matter of organizing his/her code so it works correctly.
The basic effect dgbenner is trying to achieve is very simple. Therefore, the code just needs to be organized correctly.
This is the basic code / pseudo code:
//1) run the currently selected effect
function runEffect() {
//2) Hide the button`
$( "#eMailButton" ).fadeOut();
//3) Show the email form
$( "#effect" ).show( selectedEffect, options, 500, callback );
//4) Hide the email form and show the button again ( 4 seconds later in this demo...)
// other effects and actions can be coded when the user submits his/her info..)
function callback() {
setTimeout(function() {
$( "#effect:visible" ).removeAttr( "style" ).fadeOut();
$( "#eMailButton" ).fadeIn();
}, 4000 );
};

AJAX Request - Also Clear Placeholder text as well as HTML input field value

I have a select menu that, when a user makes a selection, it fires off an AJAX request to a PHP script to query a database and return a value that matches the selection and inserts this into an associated input field. If there is no matching value returned it clears out the associated input field.
This is all working well, but I've just realised that the default placeholder text appears when there is no matching value as the input field is empty. I need to clear the placeholder text at the same time I clear the input field but haven't figured out a way to do this so far.
Here's the AJAX code that calls the PHP script and updates the input field:
$(document).ready(function() {
$("#smsFromName").change(function() {
var smsFromName = $("#smsFromName").val();
console.log(smsFromName);
$.post('getSMSSender.php', {
senderName: smsFromName
}, function(data) {
data = JSON.parse(data);
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else if (data[0] && data[0].senderMobile) {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
} else {
console.log(data[0].smsFrom);
$("#smsFrom").val("");
}
}).fail(function(xhr) {
$("#smsFrom").html('');
});
});
});
and here's the HTML input field:
<input type="text" class="form-control w48" name="smsFrom" id="smsFrom" placeholder="0412 345 678" value="0417 555 666">
I'm hoping I can simply add some code after:
$("#smsFrom").val("");
to also clear out the placeholder text but I'm stumped as to how to do that?
VanillaJS
You can easily use vannila.js here...
document.getElementById("myText").placeholder = "";
So it would be:
$(document).ready(function() {
$("#smsFromName").change(function() {
var smsFromName = $("#smsFromName").val();
console.log(smsFromName);
$.post('getSMSSender.php', {
senderName: smsFromName
}, function(data) {
data = JSON.parse(data);
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else if (data[0] && data[0].senderMobile) {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
} else {
console.log(data[0].smsFrom);
$("#smsFrom").val("");
document.getElementById("myText").placeholder = "";
}
}).fail(function(xhr) {
$("#smsFrom").html('');
});
});
});
jQuery
You could also easily use jQuery here..
$("#smsFrom").attr('placeholder', '').html("");
So it would result in...
$(document).ready(function() {
$("#smsFromName").change(function() {
var smsFromName = $("#smsFromName").val();
console.log(smsFromName);
$.post('getSMSSender.php', {
senderName: smsFromName
}, function(data) {
data = JSON.parse(data);
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else if (data[0] && data[0].senderMobile) {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
} else {
console.log(data[0].smsFrom);
$("#smsFrom").val("");
$("#smsFrom").attr('placeholder', '').html("");
}
}).fail(function(xhr) {
$("#smsFrom").html('');
});
});
});
Conclusion
Both ways would work. You could use jQuery so it can be of similar type of code, or VanillaJS For Performance. Hope this helped!
If you really need to change the placeholder text, replace your current statement
$("#smsFrom").val("");
width a chained function to change the placeholder text, like such;
$("#smsFrom").attr('placeholder', '').html("");

jQuery - If browser tab is focused, then do AJAX - Not working

I have a code that determines if current browser window or tab is active. If it's active, the title of the tab says "active" and if not it says "blurred"
It is working fine. Here's the code:
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
document.title = 'focus';
}
}
$(this).data("prevType", e.type);
})
The code above is working fine.
Now if I add AJAX to it, it doesn't work.
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
var interval = function () {
$.ajax({
url: "<?php echo base_url('home/get') ?>",
cache: false,
success: function (html) {
$("#text").val(html);
document.title ='focus';
},
});
};
setInterval(interval, <?php echo $int ?>);
}
}
$(this).data("prevType", e.type);
})
It says focused if it's in focus. If I go out of focus, it says "blurred" for less than a second, then says focus again. I don't know why. I want it to say blurred if it's not in focus. Adding the AJAX code doesn't make it work.
Please help. Thanks.
You need to use clearTimeout() in your blur event. My code continuously polls my server for data, but when I go out of the page, it stops polling. Please look at the implementation below. I have done the similar one in my application here:
$(window).blur(function() {
clearTimeout(getJsonTmr);
clearTimeout(updatePreviewTmr);
}).focus(StartTimers);
function StartTimers () {
// Every half a second,
getJsonTmr = setInterval(function () {
$.get("/doodles/update?getJson&DoodleID=" + DoodleOptions.DoodleID, function (data) {
data = JSON.parse(data);
if (!DoodleOptions.isActive)
clearDoodleCanvas();
$.each(data, function (index) {
drawFromStream(data[index]);
});
});
}, 500);
updatePreviewTmr = setInterval(function () {
$.post("/doodles/update?updatePreview", {
"DoodleID": DoodleOptions.DoodleID,
"DoodlePreview": canvas.toDataURL()
});
}, 5000);
}
StartTimers();
You can use the above code as reference and change yours.
A simple reference implementation for you...
function timers() {
tmrAjax = setInterval(function () {
$.get(/* ... */);
}, 1000);
}
timers();
$(window).blur(function () {
clearInterval(tmrAjax);
}).focus(timers);

submit during beforeunload, maybe who knows radically another method solution

Reviewed many similar questions on stackoverflow.com (also on other resources), but found no answers. So I simplified and generalized questions. It seems like the obvious solution:
$(document).ready(function() {
var a = 3;
var b = 5;
// no message when pressed submit button
$('form').submit(function() {
$(window).off('beforeunload');
});
// confirm of the need to save
$(window).on('beforeunload', function(e) {
if (a != b)
if (confirm('You changed data. Save?')) {
$('form').submit();
// alert('Your data is saved. (With alert submit() work only in FireFox!?)');
}
});
});
But not submit work. If you use the alert(), it works only in FireFox. I would like to correct (possibly without delay) cross-browser solution. Maybe who knows radically another method solution.
P.S. On some originality beforeunload described here in the first part: https://stackoverflow.com/a/6065085/1356425, but this is not the solution obvious functional.
Chrome and Firefox blocking submits after the onbeforeunload-event. You have to use
$(window).on('beforeunload', function(e) {
if (a != b)
return 'You\'ve changed the data. Leave page anyway?';
}
});
I used synchronous AJAX (JAX) request and run handler for events onUnload or onBeforeUnload once for the respective browser. This solution has a single and almost cross-browser behavior.
Example (on jsfiddle):
$(document).ready(function() {
var form = $('form');
var textareas = $('textarea');
function array_compare(a_0, a_1) {
if(a_0.length != a_1.length)
return false;
for(i = 0; i < a_0.length; i++)
if(a_0[i] != a_1[i])
return false;
return true;
}
var flag = false; // flag to control the execution of the unloadHandler() once
var a_open = []; // array with data before unload
$('textarea').each(function(index) {
a_open.push($(this).val());
});
function unloadHandler() {
if (flag)
return;
var a_close = []; // array with data during unload
$('textarea').each(function(index) {
a_close.push($(this).val());
});
if (!array_compare(a_open, a_close)) {
if (confirm('You changed the data, but not saved them. Save?')) {
$.ajax({
type: 'POST',
url: '/echo/json/',
async: false,
data: form.serialize()/* {
json: JSON.stringify({
text: 'My test text.'
}),
delay: 3
} */,
success: function(data) {
if (data) {
console.log(data);
alert('All data is saved!');
}
}
});
}
}
flag = true;
}
// For FireFox, Chrome
$(window).on('beforeunload', function () {
unloadHandler();
});
// For Opera, Konqueror
$(window).unload(function() {
unloadHandler();
});
// Without message when pressed submit button
$('form').submit(function() {
$(window).off('beforeunload');
$(window).off('unload');
});
});
Best way to submit data on unload is to store it in localstorage and send it next time when any other page under same origin is requested.
function sendBeacon(data) {
data?dataArr.push(data):'';
for (var i = 0, len = dataArr.length; i < len; i++) {
$.getScript(dataArr[i], (function (index) {
dataArr.splice(index, 1) //Updata dataArray on data submission
}(i)))
}
}
$(window).on('beforeunload', function () {
localStorage.setItem('dataArr', JSON.stringify(dataArr));
})
var dataArr = JSON.parse(localStorage.getItem('dataArr'));
if (!dataArr) {
dataArr = []; // Create Empty Array
} else {
sendBeacon(dataArr); //Submit stored data
}

Why does this JavaScript freeze IE6?

When you click, "Add to Bag" on this page, it freezes IE6 every time. How can I figure out why it is freezing? Does anyone have a more direct answer?
totallytrollbeads {dot} com {slash} Safety0.html
function update() {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/cgi-bin/ajax_cart_count.cgi',
timeout: 2000,
success: function (data) {
// If bag is empty, it's see through.
if (data.cart_count == 0) {
$(".shopping_bag").css("opacity", ".2");
}
// If bag is not empty, it's not see through.
else {
$(".shopping_bag").css("opacity", "1");
}
$("#bag_total").html(data.grand_total);
$("#bag_count").html(data.cart_count);
window.setTimeout(update, 15000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#bag_total").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
})
}
$(document).ready(update);
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// $(".add_to_cart_form").click(function () {
// $('.bypass_add_to_cart_form').ajaxForm({ success: myBox });
// });
function loading() {
$("#loadingContent").show();
}
function myBox(resptext, statustext) {
$("#loadingContent").hide();
Boxy.ask(resptext, ["View Bag", "Continue Shopping"], function (val) {
if (val == "View Bag") {
document.location.href = "/cgi-bin/store.cgi?action=view_cart";
}
if (val == "Continue Shopping" && product_detail == 1) {
history.go(-1);
}
}, {
title: "Add to Bag"
});
$('.bypass_add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
update();
return false;
}
/*
This tells the ajax-style add to cart that
it's on a product detail page so if the
user clicks "Continue Shopping" it takes
them back on step in their history.
*/
$('.search_view').click(function () {
product_detail = 0;
});
$('.product_view').click(function () {
product_detail = 1;
});
It's not easy to debug a thing that freezes immediately from the outside. But it's always a good idea to cleanup the whole, remove things that are not essential, check the functionality and then do the next step.
For example this:
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
// preparethe form when the DOM is ready
$(document).ready(function () {
// bind form using ajaxForm
$('.add_to_cart_form').ajaxForm({
beforeSubmit: loading,
success: myBox
});
});
It's not hard to see that have this part twice there.
Put a little more accuracy into your application instead of copy&paste.

Categories

Resources