The function I have only responded to a button click but not the image click. Can anyone tell me what would I need to modify in the function so that it responds to both button & image clicks?
function clickMe(a,b) {
$("#q"+b+" input[type='button']").click(function(event) {
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(b !== $(".qc").length) {
$("h1").html(a);
$("#q"+b).hide(250, function() {
$("#q"+b).next().fadeIn(250);
});
} else {
$("h1").html(a);
$("#q"+b).hide(250, function() {
$("#q"+b).next().fadeIn(250, function() {
loading(0);
});
});
}
});
}
You are probably expecting this $("#q"+b+" input[type='button'], #q"+b+" input[type='image']")
function clickMe(a,b) {
$("#q"+b+" input[type='button'], #q"+b+" input[type='image']").click(function(event) {
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(b !== $(".qc").length) {
$("h1").html(a);
$("#q"+b).hide(250, function() {
$("#q"+b).next().fadeIn(250);
});
} else {
$("h1").html(a);
$("#q"+b).hide(250, function() {
$("#q"+b).next().fadeIn(250, function() {
loading(0);
});
});
}
});
}
I hope this solves your problem. If not then no worries :) just update/add your html in the test case bellow:
https://codebrace.com/editor/b02f036fa
Related
I have written this function to validate that all form fields and check boxes in a form are filled out. The script automatically disables the submit button and then watches for the moment at which it can be re-enabled. My debugger statements are landing me in all of the proper places, but for some reason, the DOM element is not being updated. I'm sure I am just making a stupid mistake, but can't seem to find a solution. Thank you in advance for any help!
Specifically looking at this section:
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
Here is the whole script below.
$(document).ready(function() {
validateInput();
$('.validate').keyup(function(event){
validateInput();
});
$('[type=checkbox]').click(function(event){
validateInput();
});
function validateInput() {
var valid = 0;
var checkBox = $('[type=checkbox]');
var inputFields = $('input.validate');
var inputLength = inputFields.length + checkBox.length;
inputFields.each(function() {
if($(this).val() !== '') {
valid++ ;
}
});
checkBox.each(function() {
if($(this).prop('checked')) {
valid++ ;
}
});
if(valid === inputLength) {
updateBtnStatus('enable')
} else {
updateBtnStatus('disable')
}
}
function updateBtnStatus(status) {
var btn = $('input[type="submit"]');
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
}
});
I am trying to target anchor tags and trigger an ajax request. Using jQuery this is very easy:
$(document.body).on('click', "a", function (event) {
'use strict';
if ($(this).is('.a-btn')) {
event.preventDefault();
} else if ($(this).is('.no-sp')) {
//
} else {
address = $(this).attr("href")
event.preventDefault();
App.Ajax.Page(address + '/');
}
});
However using native javascript, I would imagine using event.target would do the trick.
But this does not work, because the event always targets whatever element is inside the anchor tag:
App.Ajax.Navigate = function () {
'use strict';
document.body.addEventListener('click', function (e) {
e.preventDefault();
console.log(e.currentTarget);
if (e.target.tagName === 'a') {
var element, link;
element = e.target;
link = element.href;
if (App.HTML.hasClass(element, 'a-btn')) {
e.preventDefault();
} else if (App.HTML.hasClass(element, 'no-sp')) {
return;
} else {
e.preventDefault();
App.Ajax.Page(link);
}
}
}, true);
window.onpopstate = function (event) {
App.Page.type = event.state.type;
App.Page.Replace(event.state.content, event.state.type, App.Empty, false);
};
};
I want to use native javascript to do what jquery does in the first code snippet, is it possible?
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
https://developer.mozilla.org/ru/docs/Web/API/Element/closest - 2 polifills here
event.target.closest("a")
Don't forget about polifill for most browsers.
(function(e){
if (!e.matches) {
e.matches = e.mozMatchesSelector || e.msMatchesSelector || e.oMatchesSelector || e.webkitMatchesSelector;
}
if (!e.closest) {
e.closest = function (css) {
for (var node = this; node; node = node.parentElement) {
if (node.matches(css)) {
return node;
}
}
return null;
}
}
})(Element.prototype);
I am new to jQuery and I have the following lines of jQuery. My intention is 'on submit' to check if the input text values are filled and check to see if the radio buttons are checked or selected and make the text red if they aren't but i am not sure on how to combine the two.
Right now it is kind of buggy because it submits IF the text is filled and it ignores the radio buttons BUT it makes the text red before it submits. so it is working just not how I would like it to.
jQuery
$('#form3096').submit(function (e) {
if (!$('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
$('.social-heading').css('color','red');
}
});
$('#form3096').submit(function(e) {
if ($('input:radio', this).is(':checked')) {
// everything's fine...
} else {
$('.radio-options').css('color','red');
}
});
Call e.preventDefault() to prevent the normal form submission.
$('#form3096').submit(function (e) {
if (!$('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
$('.social-heading').css('color','red');
e.preventDefault();
}
});
$('#form3096').submit(function(e) {
if ($('input:radio', this).is(':checked')) {
// everything's fine...
} else {
$('.radio-options').css('color','red');
e.preventDefault();
}
});
I like to separate my validations into single units and combine them at the end. It makes it easier to read, maintain and test.
$('#form3096').submit(function (e) {
var isFieldPopulated, isRadioChecked;
isFieldPopulated = $('#check-sm input:text').filter(function () {
return $.trim(this.value) !== "";
}).length > 0;
if (!isFieldPopulated) {
$('.social-heading').css('color','red');
}
isRadioChecked = $('input:radio', this).is(':checked');
if (!isRadioChecked) {
$('.radio-options').css('color','red');
}
return isFieldPopulated && isRadioChecked;
});
you can try this
$('#form3096').submit(function (e) {
var len = $('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length;
if (!len) {
$('.social-heading').css('color','red');
e.preventDefault();
}
if(!$('input:radio', this).is(':checked')){
$('.radio-options').css('color','red');
e.preventDefault();
}
});
$('#form3096').submit(function (e) {
if (!$.trim($('#check-sm input:text').val()) {
$('.social-heading').css('color','red');
return false;
}
if ($('input:radio', this).is(':checked')) {
// everything's fine...
return true;
} else {
$('.radio-options').css('color','red');
return false;
}
});
How do I get a pretty simple true/false-statement if the mouse is over a div event = true else event = false
var test = $("#main-nav").on("mouseenter", function (e) {
e.preventDefault();
console.log(e.preventDefault());
return true;
});
if (test === true) {
//do something
} else {
//something different
}
If I understand your question correctly:
if($("#main-nav").is(":hover")) {
//do something
}else{
//something different
}
In pseudo code:
if the cursor is over #main-nav
do something
if it's not
do something else
If you want test to always be set:
var test = false;
$("#main-nav").on("mouseenter", function(e){
e.preventDefault();
test = true;
}).on("mouseleave", function(e){
e.preventDefault();
test = false;
});
This way,
if(test === true) {
//do something
}else{
//something different
}
will always work.
You can have a boolean (true/false) variable that will constantly update by doing this:
var hovering;
$("#main-nav").mouseenter(function(){
hovering = true;
});
$("#main-nav").mouseleave(function(){
hovering = false;
});
So whenever it is called it will tell you if the mouse is within your div:
if (hovering){
// mouse within div
} else {
// mouse not within div
}
If you necessarily need is as a variable:
var test = false;
$("#main-nav").on("mouseenter", function (e) {
test = true;
});
$("#main-nav").on("mouseout", function (e) {
test = false;
});
//....
if (test === true) {
//do something
} else {
//something different
}
I have some code which was written by someone else, which is supposed to open a popup if a zipcode is not in the correct format and stop the page from being submitted. It works correctly in IE and chrome. But in firefox i get the popup, click ok, and then the page submits. Can someone look over the code and let me know what's being done incorrectly? Code pasted at the end of this message.
Thank you
<script type="text/javascript">
$(init);
function init() {
$('form').validate({
error_messages: {
},
failure: function (errors) {
//alert(errors);
$(".errMsg").show();
return false;
},
success: function () {
//alert('passed');
//return true;
}
});
$('#<%= btnAdd.ClientID %>').click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
}
function clearText(mybox, mymsg) {
if (document.forms['form1'].elements[mybox].value == mymsg) {
document.forms['form1'].elements[mybox].value = '';
document.forms['form1'].elements[mybox].style.color = '#000000';
}
}
function resetText(mybox, mymsg) {
if (document.forms['form1'].elements[mybox].value == '') {
document.forms['form1'].elements[mybox].value = mymsg;
document.forms['form1'].elements[mybox].style.color = '#C0C0C0';
}
}
function beginZipValidation() {
//alert('begin validation');
var zip = $('#<%= Zip.ClientID %>').val().replace(/ /g, '').toUpperCase();
var cID = $("#<%= ddlCountry.ClientID %> option:selected").val();
if (!zipCodeValidation(true, cID, zip)) {
return false;
}
//alert('true');
return true;
}
function zipCodeValidation(shouldValidateEmpty, countryID, zc) {
//alert('zipCodeValidation');
if (zc == '' || zc == 'POSTALCODE') {
if (!shouldValidateEmpty) {
return true;
}
}
else {
switch (countryID) {
case '226':
if (/^\d{5}(-\d{4})?$/.test(zc))
return true;
break;
case '38':
if (/^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\ ?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/.test(zc))
return true;
break;
case '225':
if (/^(GIR 0AA|[A-PR-UWYZ]([0-9][0-9A-HJKPS-UW]?|[A-HK-Y][0-9][0-9ABEHMNPRV-Y]?)[0-9][ABD-HJLNP-UW-Z]{2})$/.test(zc))
return true;
break;
case '13':
if (/^(((2|8|9)\d{2})|((02|08|09)\d{2})|([1-9]\d{3}))$/.test(zc))
return true;
break;
}
}
alert('The postal code provided does not fit the format for the selected country. Please adjust and try again.');
if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }
event.preventDefault();
return false;
}
It might be as simple as the selector being wrong:
Try changing this:
$('#<%= btnAdd.ClientID %>').click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
Instead be a bit more verbose like:
var myButtonId = "<%= btnAdd.ClientID %>"; // Now you know what this evaluates to client-side
var btnSelector = "#" + myButtonId;
$(btnSelector).click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
Are you using the standard tools like Firebug or Chrome Developer tools to debug? If so, throw a few console.log("myButtonId: " + myButtonId); statements in there!