In my below jQuery code, I can't get correct length of inputString element, element's length changing on lookup function and I can't use global variable.
$('#ckekeKala').live("click" ,function(){
var len=$('#inputString').text().length;
alert(len);
});
function lookup(inputString) {
if(inputString.length != 0) {
$('[id^="lbl"]').attr("disabled", true);
}
});
}
} // lookup
HTML code:
<input style='width: 128px;' name='nameKala' id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
Extra braces in lookup function
function lookup(inputString) {
if(inputString.length != 0) {
$('[id^="lbl"]').attr("disabled", true);
}
}); <--- Remove this
} <--- Remove this
} // lookup
Just a thought, you could really easy this whole process up like so:
HTML
<input id="inputString" name="nameKala" type="text" style="width:128px" />
Script
// keep in mind, that depending on ur use and jQuery version, .live can be replaced with .bind or .on
$("#inputString").live("keyup", function(e) {
if ($(this).length > 0) {
$('[id^="lbl"]').attr("disabled", true);
};
})
.live("blur", function(e) {
// do fill work
});
$('#ckekeKala').live("click" ,function(){
var len=$('#inputString').val().length;
alert(len);
});
Example
Beside any syntax error that you can see in other answer and post. It would have been easy if you have put more code. But assuming that all other code that you haven't mention are correct and fixing this syntax error of
});
I think your lookup does not have access outside jQuery block. so what you can do is change it to make like this
lookup = function(inputString) {
if (inputString.length != 0) {
$('[id^="lbl"]').attr("disabled", true);
}
}
Related
I want to execute a function when any of the text field is focused.
Something like this, BUT purely in Javascript - NOT IN JQUERY
$("input").focus(function() {
alert("Hello World");
});
I am trying:
document.getElementById("text1").onfocus = alert(1);
But this only shows the alert after loading page, nothing else.
Thanks
Get elements by tag name & loop("Iterate") on them for attaching focus.
http://www.w3schools.com/jsref/met_doc_getelementsbytagname.asp
var x=document.getElementsByTagName("input");
EDIT : Put this at the end of page
<script>
var x=document.getElementsByTagName("input");
for(i=0;i<x.length;i++)
{
x[i].addEventListener('focus',function(){
alert("focus");
});
}
</script>
Yet another way with document.querySelectorAll for new browser
var inputs = document.querySelectorAll('input');
and then in loop for example use addEventListener
for(var i=0,len=inputs.length;i<len;i++){
inputs[i].addEventListener('focus',function(){
//handle event
})
}
If you like some aspects of jQuery, but do not want to include the entire library in your project, you can check out You Might Not Need jQuery. You can set the minimum version of IE that you support, in the settings at the top of the page.
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function(){
handler.call(el);
});
}
}
function addEventListeners(selector, type, handler) {
var elements = document.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++) {
addEventListener(elements[i], type, handler);
}
}
addEventListeners('input', 'focus', function(e) {
if (this.value !== this.placeholder) {
this.value = this.placeholder;
} else {
this.value = '';
}
});
input {
display: block;
}
<input type="text" placeholder="One" />
<input type="text" placeholder="Two" />
<input type="text" placeholder="Three" />
I know I am probably late to this, but I just wanted to add my 2 cents, as I see a lot of Stackoverflow answers like this still using JQuery and many people have moved on from JQuery, and might want another option
You could either use the focusin event or capture the focus in the Capturing phase from the top down, in either JQuery or JS, If It works in JS, it should work in the other, as I dont use JQ
let form = document.forms.myForm;
form.addEventListener('focus', (event) => {
console.log('Focused!');
console.log(event.target);
}, true);
//Work around focusin
form.addEventListener('focusin', (event) => {
console.log('Focused In!');
console.log(event.target);
});
This one supports input elements that are loaded asynchronously too.
document.addEventListener("focusin", inputBoxListener)
function inputBoxListener(event) {
if (event.target.tagName === "INPUT") {
console.log("focused on input")
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Element/focusin_event
I am new to jQuery and I can't see where my code is wrong. I am trying to get an element with the id of custom-logo-video to change its innerHTML with an if statement (if it is "" or blank etc). However it is not working. What am I doing wrong?
$(document).ready(function(){
var a = $("#custom-logo-video");
if (!a.trim()) {
// is empty or whitespace
a.innerHTML("easy");
} else {
a.innerHTML("hard");
}
});
you can try:
$(document).ready(function () {
var a = $('#custom-logo-video').html();
if (!$.trim(a)) {
// is empty or whitespace
$('#custom-logo-video').html("easy");
} else {
$('#custom-logo-video').html("hard");
}
});
A few issues with the code
var a = $(#custom-logo-video);
selection requires quotes around it
var a = $('#custom-logo-video');
When you use jquery to select, you have a jQuery object so innerHTML won't work, you want to use either .html() or .text() to get the inner text. Here is how I fixed it.
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.html()) {
// is empty or whitespace
a.html("easy");
}else{
a.html("hard");
}
});
You can read more here: https://learn.jquery.com/using-jquery-core/selecting-elements/
You're using innerHTML which isn't necessary since you're using jQuery. .html() will suffice.
Try this:
$(document).ready(function(){
var a = $("#custom-logo-video");
if ( !a.html().trim() ) {
// is empty or whitespace
a.html('easy');
}
else {
a.html('hard');
}
});
EDIT: fixed typos and logic in code.
Try this as well,
$(document).ready(function () {
var a = $('#custom-logo-video').html();
(a !== null && a.trim().length > 0) ? a.html('hard') : a.html('easy');
});
Try this:
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.trim()) {
// is empty or whitespace
a.text("easy");
} else {
a.text("hard");
}
});
Try this code:
$(document).ready(function(){
var a = $("#custom-logo-video");
// To check if the node is empty or not I am
// calling jQuery api is(':empty')
if (a.is(':empty')) {
// is empty or whitespace
// To replace the innerHTML of a node you call a .html() jQuery api
a.html("easy");
} else {
a.html("hard");
}
});
Working Example
I have one textbox and one button and on button I have written below code. problem is suppose first I have entered in textbox 10 than its worked but when another time I enter 10 than also it prints value is not in array. so pls help me whats the issue...
jQuery(document).ready(function()
{
jQuery("#mybutton").live('click',function ()
{
var sel_fam_rel=jQuery("#my_textbox").val();
var ids = [];
code =sel_fam_rel;
if($.inArray(code,ids) >= 0)
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
This line:
if($.inArray(code,ids) >= 0)
should be changed to:
if($.inArray(code,ids) != -1)
and put your ids var outside of click.
Try the snippet below.
var ids = [];
jQuery("button").on('click', function() {
var sel_fam_rel = jQuery("#my_textbox").val();
code = sel_fam_rel;
if ($.inArray(code, ids) != -1) {
alert("Value is in array");
} else {
alert("Value is not in array");
ids.push(code);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='my_textbox'>
<button>check</button>
Create your array var ids=[];global outside button event, as whenever you click button it is creating new empty array. It will fix your problem.
A few changes are needed:
var ids = []; // `ids` needs to be in the global scope to work as you want it,
// or you could use a different method like localstorage
jQuery(document).ready(function()
{
jQuery("#mybutton").on('click',function () // use `on` not `live` which is deprecated
{
var sel_fam_rel=jQuery("#my_textbox").val();
code =sel_fam_rel;
if($.inArray(code,ids) != -1) // inArray() returns -1 if the value is not in the array, you can use it the way you have it, IMO (purely subjective), using `!=-1` is preferable as it's more clear what the code in intend to do
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my_textbox" value="10"/><br>
<input type="button" id="mybutton" value="Click me"/>
use below code . take your ids out side of click event . as per your code each time when you click button ids reset .
var ids = []; // declare as global variable
jQuery(document).ready(function()
{
jQuery("#mybutton").live('click',function ()
{
var sel_fam_rel=jQuery("#my_textbox").val();
code =sel_fam_rel;
if($.inArray(code,ids) >= 0)
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
I made a fiddle to your problem, Use indexOf
http://jsfiddle.net/go8o34fq/
jQuery-
var array=["A","B","C","D"];
$('button').click(function(){
var code=$('input').val();
if(array.indexOf(code)==-1)
{
array.push(code);
console.log("if "+array)
}
else
{
console.log("else "+array)
}
});
Just a bit requirement if your need is case-sensitive then use- code.toUpperCase()
I am trying to get checked options from a table which are set inline. There is a search function, which sets $(element).css('display','none') on objects in which there is no match with the search. Anyways, this piece of code will only return inline, no matter what the elements are set to. Even if I manually set all of them to display: none in the table itself, the alert will return inline for every single object in the table. Is there any solution to this?
JS code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).css('display') === 'inline') {
array.push($(this).val());
}
});
}
Fundamentally, css("display") does work, so something else is going on.
I suspect one of two things:
The checkboxes that you're making display: none are never checked, and so you don't see them in your each loop.
You're not making the checkboxes display: none, but instead doing that to some ancestor element of them. In that case, $(this).is(":visible") is what you're looking for.
Here's an example of #2: Live Copy | Live Source
<div id="ancestor">
<input type="checkbox" checked>
</div>
<script>
$("#ancestor").css("display", "none");
console.log("display property is now: " +
$("input:checkbox:checked").css("display"));
console.log("visible tells us what's going on: " +
$("input:checkbox:checked").is(":visible"));
</script>
...which outputs:
display property is now: inline-block
visible tells us what's going on: false
Applying that to your code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).is(':visible')) {
// Change is here -----------------^^^^^^^^^^^^^^
array.push($(this).val());
}
});
}
Side note: Every time you call $(), jQuery has to do some work. When you find yourself calling it repeatedly in the same scope, probably best to do that work once:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
var $this = $(this); // <=== Once
i++;
alert($this.css('display'));
if ($this.val() !== 0 && $this.is(':visible')) {
// Other change is here -------^^^^^^^^^^^^^^
array.push($this.val());
}
});
}
try following:
$("input:checkbox:checked").each(function(i,o){
console.log($(this).css("display"));
});
working fiddle here: http://jsfiddle.net/BcfvR/2/
I am having the following JQuery function that is working properly:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").removeClass("green");
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setAxisNameX('');
myChart.setAxisNameY('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setSize(470, 235);
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
$("#dailyUnlikes").html(response);
}});
return false;
});
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
});
but I want to create a condition: if one of the following two date inputs:
var since = $('#dateoptions input[name="since_date"]').val();
var until = $('#dateoptions input[name="until_date"]').val();
is empty I want to receive an alert and the .one() function to be executed only when the conditions are met. For example when I click on one of the button without the date inputs in place I want to receive an alert like alert("One of the date or both missing") for example and after I choose the dates and press the button again to execute the .one() function like in the above example. I hope I make myself clear enough. I know that I can use something like:
if (until == "" || since == "") {
alert("One of the date or both missing")
} else {}
but my tries so far was no success. Probably I didn't place the condition where it should... Also it is possible also with an alert the inputs to be focused, highlighted or something similar?
EDIT:
Here's a fiddle with it:
http://jsfiddle.net/DanielaVaduva/ueA7R/6/
I replace the ajax call with something else without to modify the flow.
Try checking your values with:
if (until.trim().length === 0 || since.trim().length === 0) {
//TODO here
}
I suggest you that check your name attribute in your inputs and check that it's the same that you use when you are retrieving the values of the inputs.
If it still not working, try some 'debugging' like:
console.log(since);
And check if it is getting your value properly.
UPDATE
I don't know if you wanted this (demo). If your dates are empty, it will not work. AJAX call will not work on JsFiddle, because you are using a .serialize() and it sends the information via URL, as a GET type and you need to send it as POST. It doesn't matter. If you already prepared your server to recieve a GET method, it will work.
Also, I must add that if you want to change color ONLY if the AJAX was success, you must add your change color function as I used on the demo and if you want to check your date every time you want to send information to server, change .one() function into .on() function and remove the function after the AJAX success with:
$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');
(More info about removing a function here);
I hope this will help you atleast on the way you want to do. Leave a comment if it is not what you wanted.
I'm not sure if I understood the issue exactly but.. you can check this >>
Fiddle Demo
HTML
Add IDs to the date fields like
<input id="until" type="date" name="until_date" value="Until date">
<input id="since" type="date" name="since_date" value="Since date">
And just for highlighting the required dates >>
CSS
.req{
border:2px red solid;
}
.required{
color:red;
font-size: 0.8em;
font-style:italic;
}
jQuery
$(function () {
//removing the highlighting class on change
$('#until').change(function() {
$(this).removeClass('req').next('.required').remove();
});
$('#since').change(function() {
$(this).removeClass('req').next('.required').remove();
});
$('#accmenu').change(function() {
var dSince= $('#since').val();
var dUntil= $('#until').val();
if(dSince=='' || dUntil==''){
alert('You MUST select Both dates!');
$(this).val(0); // Set the menu to the default
//Adding the Highlight and focus
if(dSince==''){
$('#since').addClass('req').after('<span class="required">- required *</span>').focus();}
if(dUntil==''){
$('#until').addClass('req').after('<span class="required">- required *</span>').focus();}
}else{
$(".insightsgraphs div").hide();
$(".insightsoptions input").removeClass("green");
$("#newLikes").one('click', function () {
$("#dailyNewLikes").html('</p>Test daily new likes</p>');
return false;
});
$("#unlikes").one('click', function () {
$("#dailyUnlikes").html('</p>Test daily unlikes</p>');
return false;
});
} //End of the if statement
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
});
Thus whenever an option from the accmenu gets selected, it will check for the values of the two DATEs, if both or any is blank, it won't execute the function.