I'm struggling with how to correctly apply .closest
A series of inputs are being used to record the score of a set of tennis.
If a user inputs a 7-6 or 6-7 combination, a hidden div appears so they can record the tiebreak.
I only want the hidden tiebreak div that's closest to the current inputs to appear.
Here's what i have so far:
$(document).ready(function() {
var div = $('.tiebreakfield');
$('.score1, .score2').keyup(function() {
var value1 = parseInt($(".score1").val());
var value2 = parseInt($(".score2").val());
if ((value1 == 6 || value1 == 7) && (value2 == 6 || value2 == 7) && (value1 !== value2)) {
div.fadeIn();
} else {
div.fadeOut();
}
});
});
$(document).ready(function() {
var div = $('.tiebreakfield');
$('.score3, .score4').keyup(function() {
var value1 = parseInt($(".score3").val());
var value2 = parseInt($(".score4").val());
if ((value1 == 6 || value1 == 7) && (value2 == 6 || value2 == 7) && (value1 !== value2)) {
div.fadeIn();
} else {
div.fadeOut();
}
});
});
The code above shows all hidden divs if the 7-6 combo is inputted.
Here's an example...http://jsfiddle.net/jQHDR/
You dont need 2 ready().
Element with class .tiebreakfield is not a div.
If i good understanded you problem then I think that this is an example of a code that you needs:
$('.score1, .score2').keyup(function() {
var element = $(this).parent().siblings(".tiebreakfield");
var value1 = parseInt($(".score1").val());
var value2 = parseInt($(".score2").val());
if ((value1 == 6 || value1 == 7) && (value2 == 6 || value2 == 7) && (value1 !== value2)) {
element .fadeIn();
} else {
element .fadeOut();
}
});
Demo:
http://jsfiddle.net/vTQr6/
The reason it didnt work was because you werent referring to the correct p.tiebreakfield. You could either go to .score from the input and next() will take you to p :
$(this).parent(".score").next("p");
or you could go to the super parent (parent of parent) and iterate back to the p :
$(this).closest("div").find(".tiebreakfield");
And you could largely reduce your code to a smaller way like this :
//find all text boxes which have a class that start with "score"; this will apply to score-n inputs
$('input[class^="score"]').keyup(function () {
//find the nearest p.tiebreakfield
var div = $(this).closest("div").find(".tiebreakfield");
//get an array of inputs
var inputs = $(this).parent().find("input[type=text]");
//first value of text box group
var value1 = parseInt(inputs[0].value);
//second value of text box group
var value2 = parseInt(inputs[1].value);
//your condition checking
var isShow = ["6,7", "7,6"].indexOf(value1 + "," + value2) !== -1;
if (isShow) {
//your actions
div.fadeIn();
} else {
//your actions again
div.fadeOut();
}
});
Demo : http://jsfiddle.net/hungerpain/jQHDR/4/
Things I changed in your code :
Removed the extra DOM ready events.
Joined up all the event handlers and used the starts with selector of jQuery.
set up div variable inside the event
got an array of inputs in and around keyup triggered input. (To generalise the score inputs) so that it can be used for getting values later.
Insted of the complex if..else loop i made the condition checking using indexOf. It will return -1 if the condition isn't satisfied.
Related
I have a textbox whose value comes from database but if a user changes the value then this value needs to be used in a calculation.
$('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
var Cost = $(this).val();
}
});
and
var cost = $('input.ecost1').val();
I need if keyup function for user enter value (first code example) else default database value (second code example). How can I write this if/else condition?
i need
if ($('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
var Cost = $(this).val();
}
}); )
else {
var cost = $('input.ecost1').val();
}
i know in if() code is wrong but above logic how to corrected
If I understand correctly, this is what is required.
var valueFromDB = getValueFromDB(); //Your function for calling database
var Cost = 0;
$('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
Cost = $(this).val();
}
else{
Cost = valueFromDB;
}
});
if-else in javascript works like this:
if(expression) {
//do this if expression is true
} else {
//do this if expression is false
}
Is it that you want?
var Cost = $('input.ecost1').val();
$('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
Cost = $(this).val();
}
}
You do not need to include the else if you provide a default value before you evaluate your input:
UPDATE as per comments below.
var Cost = 123; // default value;
$('#ecost input.ecost').keyup(function(){
if (!isNaN(this.value) && this.value.length != 0) {
Cost = this.value;
}
});
Thank you for the answers, I have this problem also and I edit #onerror answer. It works well
var search = $("#teacher_year_filter").val();
$("#teacher_year_filter").on("keyup", function() {
if (!isNaN(this.value) && this.value.length != 0) {
search = this.value
}
var table_1 = table1.column(3).search(search).draw();
});
var table_2 = table1.column(3).search(search).draw();
It will filter the default value in the input, and once we type (keyup), then it will filter using the current input.
I have a text field and when the user types the first char I have to apply one of two masks.
The rules are:
if the user types '#' the mask to be applied is '#9999999999'.
If the user types a number the mask to be applied is '999.999.999-99'.
The JavaScript that I generated is
(function () {
var oldVal;
$('#id').on('keypress paste textInput input', function () {
var val = this.value;
if ((val != oldVal) && (val.length == 1)) {
oldVal = val;
if(oldVal == '#'){
$('#id').mask('999999999');
$('#id').val(oldVal)
}else{
$('#id').mask('999.999.999-99');
$('#id').val(oldVal)
}
}else if(val.length == 0) {
$('#id').unmask();
}
});
}());
Fortunately the mask is correctly applied. The problem is that the first char is being lost.
Example:
When I type 012.345.678-99 the field gets _12.345.678-99.
Similarly when I type #2001120001 the field gets _2001120001.
What I'm doing wrong?
Thank you!
I'm not sure if this is what you were looking for, but...
The plugin tries to apply the mask on every keypress. Altering the mask a little bit (and the translation, because "#" is considered to be a digit placeholder) lets the plugin handle the whole input line and mask it.
if (oldVal == '#') {
$('#id').mask('#999999999', {"translation": {"#": null}});
$('#id').val(oldVal);
} else {
$('#id').mask('999.999.999-99');
$('#id').val(oldVal);
}
It works in this fiddle. http://jsfiddle.net/FfR8j/2/
Again, not sure if that's what you were looking for.
I used following code to mask Australian contact number field. Masking rules will be updated as the user enter first two or four digits:
// contactNumberOptions
var contactNumberOptions = {onKeyPress: function(cep, e, field, options){
var masks = ['00 0000 0000', '0000 000 000', '0000 0000'];
var prefix2 = cep.substring(0, 2);
var prefix3 = cep.substring(0, 5);
var prefix4 = cep.substring(0, 4);
mask = masks[2];
if( prefix2 == '02' || prefix2 == '03' || prefix2 == '07' || prefix2 == '08'){
mask = masks[0];
} else if( prefix2 == '04'){
mask = masks[1];
} else if( prefix4 == '1800' || prefix4 == '1900' || prefix4 == '1902'){
mask = masks[1];
} else {
mask = masks[2];
}
jQuery('input[name=contact-number]').mask(mask, options);
}};
jQuery('input[name=contact-number]').mask('0000 0000', contactNumberOptions);
Here is the code
$('#printlocs').on('change', function() {
var selctloc = $('#printlocs').find('option:selected');
$('#loc1').prop('disabled', selctloc.val() == '0');
$('#loc2').prop('disabled', selctloc.val() == '0');
$('#loc3').prop('disabled', selctloc.val() == '0');
$('#loc4').prop('disabled', selctloc.val() == '0');
});
I want to make it so the string with #loc1 is disabled only when equal to '0', #loc2 is disabled with '0' or '1' and so on, but I can't figure it out. I've tried putting different areas in brackets, using ||, but nothing is working.
Just check for those values ?
$('#printlocs').on('change', function() {
$('#loc1').prop('disabled', (this.value == '0'));
$('#loc2').prop('disabled', (this.value == '0' || this.value == '1'));
$('#loc3').prop('disabled', (this.value == '0' || this.value == '2' || this.value == '3'));
$('#loc4').prop('disabled', (this.value == '4')); // 4 only ?
});
FIDDLE
You do of course need a select element with options that has these values
If I understood when you want to disable your options correctly, you could use the fact that the prop function also takes a function as it's second argument so you could make use of it as well as the starts with selector to simplify your code.
For instance:
var val = Number(selctloc.val());
$('[id^=prop]').prop('disabled', function () {
//get the number of the element out of the id
var num = Number(this.id.substring(3));
//disable if the value is smaller than the number
return val < num;
});
I have an input field that the user will fill in and I want to automatically capitalize the first letter of each word as they're typing. However, if they manually delete a capital letter and replace it with a lower case, I want that to remain (basically capitalizing the letters is what we recommend, but not required). I'm having trouble implementing something that will leave the letters they manually typed alone and not change them.
Here is the code I have along with a Jsfiddle link to it.
<input class="capitalize" />
and JS:
lastClick = 0;
$(document).ready(function() {
$(".capitalize").keyup(function() {
var key = event.keyCode || event.charCode;
if (!(lastClick == 8 || lastClick == 46)) {
//checks if last click was delete or backspace
str = $(this).val();
//Replace first letter of each word with upper-case version.
$(this).val(str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}));
}
lastClick = key;
});
});
I haven't allowed for preserving the user's manual corrections, but as it is you can see in the jsfiddle that the input jumps around and doesn't work correctly. Can anyone help me or recommend a best way to do this? Thank you.
$(document).ready(function() {
var last;
$(".capitalize").on('keyup', function(event) {
var key = event.keyCode || event.which,
pos = this.value.length,
value = this.value;
if (pos == 1 || last == 32 && (last !== 8 || last !== 46)) {
this.value = value.substring(0, pos - 1) +
value.substring(pos - 1).toUpperCase();
}
last = key;
});
});
http://jsfiddle.net/userdude/tsUnH/1
$(document).ready(function() {
$(".capitalize")
.keyup(function(event) {
var key = event.keyCode || event.charCode;
// store the key which was just pressed
$(this).data('last-key', key);
})
.keypress(function(event) {
var key = event.keyCode || event.charCode;
var lastKey = $(this).data('last-key') ? $(this).data('last-key') : 0; // we store the previous action
var $this = $(this); // local reference to the text input
var str = $this.val(); // local copy of what our value is
var pos = str.length;
if(null !== String.fromCharCode(event.which).match(/[a-z]/g)) {
if ((pos == 0 || str.substr(pos - 1) == " ") && (!(lastKey == 8 || lastKey == 46))) {
event.preventDefault();
$this.val($this.val() + String.fromCharCode(event.which).toUpperCase());
}
}
// store the key which was just pressed
$(this).data('last-key', key);
});
});
I have updated your fiddle http://jsfiddle.net/nB4cj/4/ which will show this working.
This isn't a jQuery only question as it has to do with events and order of operation. Consider the following code, which is based on jQuery multiSelect plugin (please post citation if you can find it):
Fiddle with it here
var debug = $('#debug');
var updateLog = function (msg){
debug.prepend(msg + '\n');
};
var title = $('#title').focus();
var container = $('#container');
title.keydown(function(e){
// up or down arrows
if (e.keyCode == 40 || e.keyCode == 38) {
var labels = container.find('label');
var idx_old = labels.index(labels.filter('.hover'));
var idx_new = -1;
if (idx_old < 0) {
container.find('label:first').addClass('hover');
} else if (e.keyCode == 40 && idx_old < labels.length - 1) {
idx_new = idx_old + 1;
} else if (e.keyCode == 38 && idx_old > 0) {
idx_new = idx_old - 1;
}
if (idx_new >= 0) {
jQuery(labels.get(idx_old)).removeClass('hover');
jQuery(labels.get(idx_new)).addClass('hover');
}
return false;
}
// space/return buttons
if (e.keyCode == 13 || e.keyCode == 32) {
var input_obj = container.find('label.hover input:checkbox');
input_obj.click();
return false;
}
});
// When the input is triggered with mouse
container
.find('input:checkbox')
.click(function(){
var cb = $(this);
var class = "checked";
if (cb.prop(class)){
cb.parent('label').addClass(class);
} else {
cb.parent('label').removeClass(class);
}
updateLog( cb.closest('label').text().split(/[\s\n]+/).join(' ') + ': '
+ this.checked + ' , '
+ cb.prop(class));
title.focus();
})
;
Notice the difference in the checkbox value for when you click directly on the checkbox, versus when you select the checkbox with the space/enter key. I believe this is because it's calling click during the keydown event, so the value of the checkbox is not yet changed; whereas if you actually click the input, the mouseup event occurs before the click (?), so the setting is applied.
The multiselect plugin does not call the click event, it has almost duplicate code. I'm curious if it would be better to pass a parameter to the click event (or use a global) to detect if it issued by the keyboard or mouse, or if it is better to just do what the plugin did and have the code inside the keydown function.
Obviously, if the log were after the click() runs, the keydown would return trues, but there are things that happen inside of click that are based on the input's checked status.
Changed it to use the change event instead of the click event for the checkboxes
http://jsfiddle.net/QJsPc/4/