JQuery Check if input is empty not checking onload? - javascript

I am using this code to check if an inputbox is empty or not and it works fine but it only checks check a key is press not when the page loads.
It's does what it should but I also want it to check the status when the page loads.
Here is the current code:
$('#myID').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});

Try the following:
$(function() {
var element = $('#myID');
var toggleClasses = function() {
if (element.val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
};
element.on('keyup keydown keypress change paste', function() {
toggleClasses(); // Still toggles the classes on any of the above events
});
toggleClasses(); // and also on document ready
});

The simplest way to do is trigger any of the keyup,keydown etc event on page load. It will then automatically call your specific handler
$(document).ready(function(){
$("#myID").trigger('keyup');
});

try checking the value on a doc ready:
$(function() {
if ($('#myID').val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
EDIT: just as an update to this answer, a nicer approach might be to use toggle class, set up in doc ready then trigger the event to run on page load.
function check() {
var $status = $('#status');
if ($(this).val()) {
$status.toggleClass('required_ok').toggleClass('ok');
} else {
$status.toggleClass('required_ok').toggleClass('not_ok');
}
}
$(function () {
$('#myID').on('keyup keydown keypress change paste', check);
$('#myID').trigger('change');
});

Well then why dont just check the field after the page is loaded?
$(document).ready(function(){
if ($('#myID').val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});

$(document).ready(function(){
var checkVal = $("myID").val();
if(checkVal==''){
$('#status').removeClass('required_ok').addClass('ok');
}
else{
$('#status').addClass('required_ok').removeClass('not_ok');
}
});

Related

Need to simulate keypress jquery

I have a function that uses the value of a textbox (prodinput) to hide/show links in a dropdown list. It works when a user types in a string manually but when I want to auto-populate the value by passing a url parameter I'll need to trigger a keyup or keydown to get it to call the function.
Here is the function that does the search (located in the core.js):
prodinput.on('keyup, keydown',function() {
var search = $(this).val().toLowerCase();
$('.support-product .browse-products a').each(function() {
if($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
});
Here is the function I'm using to trigger the function above (located on the page I'm trying to run it on.
$(function(){
$target = $('.browse-products .display');
$target.val($trimmed);
$('.browse-products').addClass('active');
$target.focus();
var e = jQuery.Event( "keydown" );
$target.trigger(e);
});
I've tried using:
$target.keyup();
and as shown above:
var e = jQuery.Event( "keydown" );
$target.trigger(e);
I'm wondering if it's a problem with the order in which things load on the page.
I'd put your keyup code in a named function.
$(function () {
myFunction();
prodinput.on('keyup, keydown', function () {
myFunction();
})
};
var myFunction = function () {
var search = $('#prodinput').val().toLowerCase();
$('.support-product .browse-products a').each(function () {
if ($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
};
Assuming you don't need to support ancient browsers you can just listen for the input event which covers keypress and change events. Then after attaching the listener simply trigger the event:
$(function() {
$("#prodinput").on('input', function() {//alternatively you could use change and keyup
var search = $(this).val().toLowerCase();
$('.support-product .browse-products a').each(function() {
if ($(this).text().toLowerCase().search(search) > -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
}).trigger("input");//trigger the event now
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="search" id="prodinput" value="peanuts" />
<div class="support-product">
<ul class="browse-products">
<li>jam</li>
<li>elephants</li>
<li>peanuts</li>
</ul>
</div>

Why is my ajax element immediately losing focus?

I'm trying to add an autocomplete option to the title field in Wordpress - the titles of one of my custom document types will often (but not always) have a standard name.
I've hooked into Wordpress to add a div with an id of suggestions below title, and add a javascript onKeyUp event to title telling it to make an ajax request to a page that suggests names based on what's typed so far. This is all working fine.
Currently, however, I'm only able to select the suggestions via a mouseclick (which then uses val to update the value of #title. I'd also like users to be able to use the arrow keys to select a suggestion, a la Google.
I'm working on building this by giving each suggestion focus (each line is a li element with a dynamically generated tabindex.)
This works for a split second - the expected element gets the focus - but then it immediately loses it, going back to the body. Why is this happening?
Code for gethint.php:
<?php
$sofar = stripslashes($_GET['sofar']); // This is important as otherwise the url gets confused and won't work on anything with an apostrophe in it.
$common_file_names = array(
"Here's suggestion 1",
"This is suggestion 2",
"Suggestion 3");
if(strlen($_GET['sofar'])>1) { //Ignores single letters
echo '<ul id="autocomplete">';
$tabindex=0;
foreach ($common_file_names as $suggestion) {
if(false !== stripos($suggestion, $sofar)) : ?>
<li
tabindex="<?=$tabindex?>"
onClick="acceptSuggestion('<?=addslashes($suggestion)?>')"
onBlur="console.log('Lost focus!'); console.log(document.activeElement);";
><?=$suggestion?></li>
<?php $tabindex++; endif;
}
echo '</ul>';
}
?>
JS Code:
$.ajaxSetup({ cache: false });
window.onload = function () {
$( "<div id='suggestions'></div>" ).insertAfter( "#title" );
$(document).on('keydown', '#title', function (){
var hint_slash = this.value;
showHint(hint_slash);
checkKey(event);
});
$(document).on('focus', '#acf-field-extranet_client_area', function (){
clearSuggestions();
});
$(document).on('focus', '#acf-field-extranet_document_type', function (){
clearSuggestions();
});
$(document).on('focus', '#acf-date_picker', function (){
clearSuggestions();
});
$(document).on('focus', '#acf-file-value', function (){
clearSuggestions();
});
console.log("Scripts loaded successfully");
}
function showHint(str) { //If the user has typed 2 or more characters, this function looks for possible matches among common document names to speed up data entry.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("suggestions").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/gethint.php?sofar=" + str, true);
xmlhttp.send();
}
function acceptSuggestion(str) {
$('#title').val(str); //Puts the clicked suggestion into the title box.
clearSuggestions();
}
function clearSuggestions() {
showHint(""); //Clears suggestions.
}
function checkKey(event) {
console.log('Key press: ' + event.keyCode);
if(40 == event.keyCode) {
event.preventDefault(); // Stops scrolling.
var autocomplete = $("#autocomplete");
$(autocomplete.children('li:nth-child(' + 2 + ')')).focus() ;
console.log(document.activeElement);
}
}
This is just test code currently, hence always setting focus to the 3rd child element.
I wouldn't try focus on the suggestions. You'll have to add the keychecking code to every suggestion in this case, because the input will lose focus. Instead, create a CSS class for the "focused" suggestion, remove the class on key up/down and add it to the previous/next suggestion...
$input.keyup(function(e) {
if(e.which == 38) {
// up key
var active = $('.suggestions li.active');
if(active.length) {
active.removeClass('active');
active.prev().addClass('active');
} else {
$('.suggestions li:last').addClass('active');
}
} else if(e.which == 40) {
// down key
var active = $('.suggestions li.active');
if(active.length) {
active.removeClass('active');
active.next().addClass('active');
} else {
$('.suggestions li:first').addClass('active');
}
}
});
Building on #evilunix's answer, I realised that each keystroke was resetting the #suggestions div, which meant that it could never hold focus (or keep an appended class etc).
So, wrote a new function called checkKey:
function checkKey(e) {
if(e.which == 38) {
// up key
e.preventDefault(); //Stops scrolling and cursor movement.
var active = $('#suggestions li.active');
if(active.length) {
active.removeClass('active');
active.prev().addClass('active');
} else {
$('#suggestions li:last').addClass('active');
}
} else if(e.which == 40) {
// down key
e.preventDefault(); //Stops scrolling and cursor movement.
var active = $('#suggestions li.active');
if(active.length) {
active.removeClass('active');
active.next().addClass('active');
} else {
$('#suggestions li:first').addClass('active');
}
} else if(e.which == 13) {
//Return key
e.preventDefault(); //Stops form submission.
acceptSuggestion(document.getElementsByClassName('active')[0].innerHTML);
} else {
console.log(e.which);
showHint($('#title').val());
}
}
and changed #title's onKeydown event to:
$(document).on('keydown', '#title', function (){
checkKey(event);
});
Now #suggestions only refreshes if the keystroke is not an up arrow, down arrow or return, and on a return runs acceptSuggestion on whichever li has the active class.

code not working without an alert() in javascript

my problem is the following code is not working without an alert().I am using a two level select/deselct all box. but the code is working for one level only. It is not being able to deselect the 'select all' checkbox on unchecking a single checkbox or vice-versa without the alert..
alert('17');
$('input.DataCheckAll').click(function() {
if ($('input.DataCheckAll').length == $('input.DataCheckAll:checked').length) {
$('input.CheckAll').prop('checked', true);
} else {
$('input.CheckAll').prop('checked', false);
}
});
if ($('input.CheckAll').length > 0) {
$('input.CheckAll').attr('checked', false);
$('input.CheckAll').click(function() {
if (this.checked) {
$('input.DataCheckAll').each(function() {
this.checked = true;
});
} else {
$('input.DataCheckAll').each(function() {
this.checked = false;
});
}
});
}
It's highly likely that you just need to wrap it in $(function() { /* code */ });. At present, your code is being stopped by the alert, which lets the document load in the background so by the time you close the alert, the page is ready for everything you're trying to do.
By just telling it to wait until the page has finished loading, you shouldn't need the alert any more.
$(function() {
// code
});
is exactly the same as
$(document).ready(function() {
// code
});
The code is probably running before the dom is ready, Try this:
$(function(){ //by passing jQuery a function instead of a selector
// it will call the function when the dom is ready
$('input.DataCheckAll').click(function() {
if ($('input.DataCheckAll').length == $('input.DataCheckAll:checked').length) {
$('input.CheckAll').prop('checked', true);
} else {
$('input.CheckAll').prop('checked', false);
}
});
if ($('input.CheckAll').length > 0) {
$('input.CheckAll').attr('checked', false);
$('input.CheckAll').click(function() {
if (this.checked) {
$('input.DataCheckAll').each(function() {
this.checked = true;
});
} else {
$('input.DataCheckAll').each(function() {
this.checked = false;
});
}
});
}
});
You should execute your jquery script after DOM is ready, so wrap it inside $(function(){});
NOTE - Also, you need not to iterate $('input.DataCheckAll') using .each(), to check / uncheck. You can simply use $('input.DataCheckAll').prop('checked',true);
$(function(){
$('input.DataCheckAll').click(function() {
if ($('input.DataCheckAll').length == $('input.DataCheckAll:checked').length) {
$('input.CheckAll').prop('checked', true);
} else {
$('input.CheckAll').prop('checked', false);
}
});
if ($('input.CheckAll').length > 0) {
$('input.CheckAll').attr('checked', false);
$('input.CheckAll').click(function() {
/*if (this.checked) {
$('input.DataCheckAll').each(function() {
this.checked = true;
});
} else {
$('input.DataCheckAll').each(function() {
this.checked = false;
});
}*/
// to select / deselect all data check boxes
$('input.DataCheckAll').prop('checked',this.checked);
});
}
});

jQuery: Check if button is clicked

I have two buttons in a form and want to check which one was clicked.
Everything works fine with radioButtons:
if($("input[#name='class']:checked").val() == 'A')
On simple submit button everything crash.
Thanks!
$('#submit1, #submit2').click(function () {
if (this.id == 'submit1') {
alert('Submit 1 clicked');
}
else if (this.id == 'submit2') {
alert('Submit 2 clicked');
}
});
You can use this:
$("#id").click(function()
{
$(this).data('clicked', true);
});
Now check it via an if statement:
if($("#id").data('clicked'))
{
// code here
}
For more information you can visit the jQuery website on the .data() function.
jQuery(':button').click(function () {
if (this.id == 'button1') {
alert('Button 1 was clicked');
}
else if (this.id == 'button2') {
alert('Button 2 was clicked');
}
});
EDIT:- This will work for all buttons.
$('input[type="button"]').click(function (e) {
if (e.target) {
alert(e.target.id + ' clicked');
}
});
you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.
$('#btn1, #btn2').click(function() {
let clickedButton = $(this).attr('id');
console.log(clickedButton);
});
try something like :
var focusout = false;
$("#Button1").click(function () {
if (focusout == true) {
focusout = false;
return;
}
else {
GetInfo();
}
});
$("#Text1").focusout(function () {
focusout = true;
GetInfo();
});

jQuery trigger event when click outside the element

$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});

Categories

Resources