Select/alter range of values in jquery function - javascript

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;
});

Related

Jquery if keyup else default value

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.

Disable first character in textbox

I have a textbox and it contain a value "Given Name". I want to disable first character of a textbox so that user cannot change the First Charcter in textbox by using backspace or any other means.
For Example: suppose textbox contains the value "Given Name". I want that user cannot change the First character "G" by using backspace or any other means.
<input type="text" id="nameId" onkeydown="validate(this.val)"/>
Below is javascript function:
function validate2(val) {
// have no idea how to do.
}
I have no idea how to do it in Javscript or Jquery.
You could do like follow :
$("#nameId").on("keydown", function(e) {
// if user writes a char at index === 0 that is not an arrow or HOME or END
if (($(this).get(0).selectionStart === 0 && (e.keyCode < 35 || e.keyCode > 40))
// or if user tries to erase first char
|| ($(this).get(0).selectionStart === 1 && $(this).get(0).selectionEnd === 1 && e.keyCode === 8)) {
// don't write the character
return false;
}
});
// prevent right click
$("#nameId").bind("contextmenu", function(e) {
e.preventDefault();
});
JSFIDDLE
Wasn't planning on answering, leaving it with the comment, but after seeing the other answers thought I might have a quick go at it after all:
The html:
<input type="text" id="nameId" value="Given Name" onkeydown="save(this,event)" onkeyup="restore(this,event)" onchange="restore(this,event)"/>
The javascript:
function restore(el,event) {
if(el.value.length == 0){
el.value = el.dataset.value.substr(0,1);
}else{
el.dataset.value = el.value;
}
}
function save(el,event) {
var key = event.which || event.charCode || event.keyCode;
if((key === 8 && el.value.length === 1)
|| (key === 46 && el.selectionStart == 0 && el.value.length === 1)){
event.preventDefault();
}
if(el.value.length > 0){
el.dataset.value = el.value;
}
}
The approach was to not mess around too much with preventing the deletion of the actual character (just the very bare basics) and instead ensure that if somebody deletes the first character to always restore it somehow. It creates code that's easy to comprehend and maintain, yet works quite neatly. A fiddle can be found here as well. Do note though that event.which is not the most cross browser consistent interface, so either use jQuery for that or check in other browsers before using it in production. Edited it in a way that should work cross browser including older browsers.
Here's mine version.
Html
<input type="text" id="nameId" value="Given Name" />
JS
var lastentry = '';
$("#nameId").on("keyup", function(e) {
var targetValue = $(e.currentTarget).attr('value');
var targetValueLength = targetValue.length;
var inputValue = this.value;
if(checkChanges(targetValueLength, targetValue, inputValue))
this.value = targetValue + lastentry;
else
lastentry = this.value.slice(targetValueLength)
});
function checkChanges(targetValueLength, targetValue, inputValue)
{
for(var i = 0; i < targetValueLength ; i++)
{
if(targetValue[i] != inputValue[i])
return true;
}
return false;
}
Demo
You can try this:-
<input type="text" id="nameId" value="Given Name" onkeydown="validate(this.value,event)"/>
<script>
function validate(val,event) {
// have no idea how to do.
if(event.target.selectionStart != undefined && (event.which === 46 ||event.which === 8)){
var startPos = event.target.selectionStart,
endPos = event.target.selectionEnd;
console.log(startPos,endPos);
if(startPos === 0 && startPos != endPos){
var restPart = val.slice(endPos,val.length);
if(restPart){
val = val[0].concat(restPart);
} else{
val = val[0]
}
event.target.value = val;
event.preventDefault();
} else if(startPos === 0 && startPos === endPos && event.which === 46){
event.preventDefault();
} else if(startPos === 1 && event.which === 8){
event.preventDefault();
}
}
}
</script>
Hi use this it do not allow to delete first character ,
$(document).keydown(function(e)
{
var value = $('#nameId').val().length;
if ( e.keyCode == 8 && value < 2)
e.preventDefault();
});

Aplying JQuery mask dynamically

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);

How to use javascript validating two text areas

The below works, how would i go about including a 2nd "txtArea2"? I've tried joining a & (document.getElementById("txtArea2").value == '') but doesnt work. I'm new to js syntax if someone could help.
if(document.getElementById("txtArea1").value == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};
I'm not sure if I understand your question correctly but you probably want to compare them with || (OR) operator, so if txtArea1 or txtArea2 is empty then the validation shall not pass. That means both textareas will be required fields.
if (document.getElementById("txtArea1").value == '' || document.getElementById("txtArea2").value == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};
Double && specifies the AND condition.
if (document.getElementById("txtArea1").value == '' && document.getElementById("txtArea2").value == '')
If you want to treat both separately, you'll have to use two separate if statements as well. (I outsourced the textareas into variables for readability)
var txtarea1 = document.getElementById("txtArea1");
var txtarea2 = document.getElementById("txtArea2");
if(txtarea1.value == '')
{
alert("debug");
txtarea1.style.display = "none";
return false;
};
if(txtarea2.value == '')
{
alert("debug");
txtarea2.style.display = "none";
return false;
};
If you want to do one thing if either of them (1 or 2) is empty, try this:
if(txtarea1.value == '' || txtarea2.value == '')
{
alert("debug");
txtarea1.style.display ="none";
txtarea2.style.display ="none";
return false;
};
var t1 = document.getElementById("txtArea1").value;
var t2 = document.getElementById("txtArea2").value;
if( t1 == '' || t2 == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};

Target closest div of a certain class with javascript

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.

Categories