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.
Related
I have some input filed into a form. I am trying to check the empty and null of those value.
My js code as:
$(function(){
$('#submit').click(function(){
var cid = $('#CTID').val();
var sid = $('#sbj').val();
var d = $('#bdate').val();
var t = $('#time').val();
var dt = d+' '+t;
var path = '/admin/exam_schedule';
if (cid ==''||cid==null || sid==''||cid==null || d==''||d==null || t==''||t==null) {
alert('Input all data fields');
}
else{
var url='/admin/insert_exam_schedule';
$.post(url,{c:cid,s:sid,d:dt},function(data){
alert(data);
window.location.href= path
});
}
});
});
But the problem of this code are: When I give space into the input field then it takes the space as input.But, I want to validate all of the possible way, so that I can take real data as input.
val() will only return null for a select element, everything else should return '', therefore, if you aren't using a select element then str != '' or str.length > 0 should be sufficient.
If you are using a select element then you check whethre the value is assigned first e.g. str && str != '' or str && str.length > 0 (or alternatively you default null to '' for consistency).
If you want to exclude whitespace-only strings then use trim() during validation.
var cid = $('#CTID').val();
var sid = $('#sbj').val();
var d = $('#bdate').val();
var t = $('#time').val();
var dt = d+' '+t;
if (cid.trim() == '' || sid.trim() == '' || d.trim() == '' || t.trim() == '') {
// data invalid
}
else {
// data valid
}
Try,
var condition = $('#CTID,#sbj,#bdate,#time').map(function(){
return $.trim(this.value);
}).get().join('') === '';
if(condition){ alert('Input all data fields'); }
DEMO
Improvised version,
var condition = false;
$('#CTID,#sbj,#bdate,#time').each(function(){
if($.trim(this.value) === "") {
condition = true;
return false;
}
})
if(condition){ alert('Input all data fields'); }
Full code would be,
$('#submit').click(function(e){
e.preventDefalut();
var condition = $('#CTID,#sbj,#bdate,#time').map(function(){
return $.trim(this.value);
}).get().join('') === '';
if(condition){ alert('Input all data fields'); }
else {
var url='/admin/insert_exam_schedule';
$.post(url,{c:cid,s:sid,d:dt},function(data){
alert(data);
window.location.href= path
});
}
});
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);
I'm trying to do some extremely simple form validation, my current problem is that my window.onload function doesn't call in the function I specify.
When I watch the flow of logic with firebug it just skips to the end of the code.
Here is an example of my code:
window.onload = init;
function init() {
var regForm = document.getElementById("registerform");
regForm.onsubmit = validatepostcode();
}
function validatepostcode() {
var postCode = document.getElementById("postcode");
var postCodeStr = postCode.charAt(0);
var state = document.getElementById("state");
var result = true;
if (postCodeStr == 3 || 8 && state == "Vic") {
result = true;
} else if (postCodeStr == (1 || 2) && state == "NSW") {
result = true;
} else if (postCodeStr == (4 || 9) && state == "QLD") {
result = true;
} else if (postCodeStr == 0 && state == "NT" || state == "ACT") {
result = true;
} else if (postCodeStr == 6 && state == "WA") {
result = true;
} else if (postCodeStr == 5 && state == "SA") {
result = true;
} else if (postCodeStr == 7 && state == "TAS") {
result = true;
} else
result = false;
if (result = false) {
alert("Your postcode does not match your state")
}
}
Five problems:
In init, you have this:
regForm.onsubmit = validatepostcode();
That calls validatepostcode and puts its return value in onsubmit. You probably meant to put the function itself it, not its return value in. Remove the parentheses:
regForm.onsubmit = validatepostcode;
In validatepostcode, you're fetching elements like this:
var postCode = document.getElementById("postcode");
…but then try to use them as values, like this:
var postCodeStr = postCode.charAt(0);
But an element and the current value of that element are not the same thing. More likely, you meant to retrieve the value on the first line:
var postCode = document.getElementById("postcode").value;
Same goes for state.
In validatepostcode, you have lines like this:
} else if (postCodeStr == (1 || 2) && state == "NSW") {
Specifically, 1 || 2 won't work like that. It will look at them like booleans and say, “one or two? well, they're both truthy…true it is!” and you'll essentially be doing
} else if (postCodeStr == true && state == "NSW") {
(Actually, it uses 1, not true, since the first operand was truthy, but that's not the important point here.)
Instead of using that abbreviated notation, you'll have to write it out longhand:
} else if ((postCodeStr == 1 || postCodeStr == 2) && state == "NSW") {
You mixed up = and == here:
if(result=false){
= will set result to false and leave the condition always false. Change it to == to test equality:
if(result==false){
You probably meant to return result at the end to prevent the form from being submitted when there is a validation error. With the other changes applied, you'd get an alert if there was a validation error, but it'd go on submitting anyway. As such, add a return result at the end of the validatepostcode function.
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.
I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...