Why doesn't this JavaScript evaluation work? - javascript

I only want to execure a ceratin code IF three input fields do not have empty values. So why doesn't this code work:
if($("#field1").val() != "" && $("#field2").val() != "" && $("#field3").val() != "")

Make sure the input fields are named properly? They should have the id attribute for them set.

Do all three inputs have ids matching your selectors? You may also want to check that the type of the values is not undefined like so:
if(typeof($('#field1').val())!='undefined' ...

Related

JavaScript issue on checking if both numeric values exists

Hopefully I get this format right. I know this is a newbie question and probably pretty obvious but I am confused on how to check these fields. I have two input fields on a JSP file:
<input id="CMDScheduleNumber" type="number" class="textsmall" maxlength="5"
onKeyPress="return numbersonly(this, event)"/>
<input id="CMDContractYear" type="number" class="textsmall" maxlength="4"
onKeyPress="return numbersonly(this, event)"/>
I have a function in a script called "searchEFT" that is checking if either the schedule number or contract year is populated then both must be populated.
<script type="text/javascript">
//function for onchange
$(document).ready(function () {
$("#searchEFT").click(function () {
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber");
var Cmd_Contract_Year = document.getElementById("CMDContractYear");
var Cmd_Status = document.getElementById("CMDSchedStatus");
var Cmd_Creation_Date = ocument.getElementById("CMDCreationDate");
if (Cmd_Sched_Number == "") {
If(Cmd_Contract_Year !== "")
alert("Schedule Number and EFT Contract Year must be both populated");
return;
}
else if (Cmd_Sched_Number == "") {
alert("Schedule Number and EFT Contract year must be both populated");
return;
}
When I tried to do a debugger if the Cmd_Sched_Number field the value is shown as "" but the valueasnumber is shown as 'NaN'. So when I do a check, should I check it was "" or check it as numeric with isNaN and/or IsNull?
Thanks for the help
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber");
Gets the Element.
Use .value to get value from the Element
Something like:
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber").value;
Also, since you have jQuery already, consider using it.
Like:
var Cmd_Sched_Number = $("CMDScheduleNumber").val();
Custom code validations are really a mess. How many conditions you can check? There are a lot of open source libraries and they do the job pretty much well.
I would recommend you to use validate.js. Its very simple and easy to use. It sets the rules on the fields and validate according to them.
Probably you will have to do little more efforts right now to shift your code, but it will be very easy then.
As Aragorn correctly pointed out, make sure you're getting the values, not the Jquery objects or DOM elements.
function isPopulated(val) {
return !(val === '' || isNaN(val));
}
//and then in your click event handler...:
if((isPopulated(Cmd_Sched_Number) || isPopulated(Cmd_Contract_Year)) && !(isPopulated(Cmd_Sched_Number) && isPopulated(Cmd_Contract_Year))) {
//Handle the case where one is populated and the other isn't, assuming you want to treat any non-numbers as not populated.
}
This is if you want a common block for any scenario of one populated and the other not, it will be evaluated like an XOR.
The reason my isPopulated function checks for both an empty string and isNaN is that isNaN('') will evaluated false.
If you don't care whether the entered value is actually numeric or not, then you would maybe want to check value.length > 0, for example.

Multiple Selectors on If Statement

So, I'm trying to make sure a button is disabled to prevent a user from saving data from form field entries whenever two conditions are met:
The checkbox is checked
There's nothing inside the form field in question ( #read_return_response_rate_ids )
This is what I have to that end:
$('body').on("change","#tab3 #read_return_response_rate_ids", function(){
if ($(this).is('')) && ($('input:checkbox').is(':checked')) {
$('.create_read_btn').attr('disabled', 'disabled');
} else {
$('.create_read_btn').removeAttr('disabled');
}
});
The error it's giving me in the console is totally useless towards debugging purposes.
Uncaught SyntaxError: Unexpected token /
It's my thought that this is where the problem exists:
if ($(this).is('')) && ($('input:checkbox').is(':checked'))
Basically, I don't think I can have multiple selectors as I have them structured, but I don't know. Does anyone have any thoughts on why this is returning an error? I confirmed that this code block is where the error originates by selectively commenting out other blocks of code and whittling it down to this one.
There are syntax errors (parenthesis chars note required):
Change:
if ($(this).is('')) && ($('input:checkbox').is(':checked')) {
by
if ($(this).is('') && $('input:checkbox').is(':checked')) {
The argument to .is() must be a selector or jQuery collection; it tests whether the specified element matches the selector or is the same set of objects. If you want to test whether an input field is empty, you need to use .val() to get the value.
if ($(this).val() == '' && $('input:checkbox').is(':checked')) {

Input text validation jquery

I'm using Jquery Framework, I'm trying to validate input data, which is not equal to null or empty string. My approach is to validate data in a single line as I'm maintaining cookies storage. My question is, how can I validate input text that value its not an empty string, similarly I checked radio buttons and check boxes that are checked. How can I validate input[type='text'] with same condition input[value !=''] in a single line.
Here's my code:
_strFormElements = "input[type='text']," +
"input[type='checkbox']:checked," +
"input[type='radio']:checked," +
"input[type='image']," +
"input[type='file']," +
"select," +
"textarea";
I then checking as follow, but I want to check and validate before theses checks as my init method creates empty feilds before this.
if (elem.is('input:text') || elem.is('input:hidden') || elem.is('input:image') ||
elem.is('input:file') || elem.is('textarea')) {
elem.val(value);
}
My Try:
I've tried input[type='text' value != ''] but I'm unable to check this in a single line.

How to highlight searchtext records in javascript?

Name Role
applicationame role id
application1 appadministrator 1490
application developer 1498
application2 tester 1460
I need the result like if entered 'app' as searchtext need to highlight all rows ,because all rows are having app.if entereted 'application' as searchtext then need to highlight 2nd row only. because exact macth.like that i need to check all columns i.e aplication,role etc.
no need of hide the unmacthed rows.need to highlight matching only if not macth just display as it is.
if user entered '14' as searchtext need to highlight all rows.if he entered 1490 need to highlight 1strow and display remaining rows as it is.please help me to achieve this.
My fidler: http://jsfiddle.net/kUxNj/4/
Please modify my fidler according this.
You should replace this:
if ($(this).find('td:first-child').text().toUpperCase() === text.toUpperCase() ||
$(this).find("td:eq(1)").text().toUpperCase() === text.toUpperCase()
)
With this:
if ($(this).find('td:first-child').text().toUpperCase().indexOf(text.toUpperCase()) != -1 ||
$(this).find("td:eq(1)").text().toUpperCase().indexOf(text.toUpperCase()) != -1
)
How it works: your code looks whether the given text is equal to one of the rows, but my code checks whether one of the rows contains the given text, using the indexOf() method.
And to avoid hiding of non-matching elements, remove the following code:
if(grid.find('td.result').length >0){
grid.find('td').not('.result').parent('tr').hide();
}
Updated fiddle: http://jsfiddle.net/kUxNj/7/
Using the match() method instead of the equality check:
if ($(this).find('td:first-child').text().toUpperCase().match( text.toUpperCase()) ||
$(this).find("td:eq(1)").text().toUpperCase().match( text.toUpperCase()))
{
$(this).children('td').addClass('result');
}
I also removed the hide() and show() calls as they are redundant to highlighting rows like you ask.
Updated fiddle: http://jsfiddle.net/kUxNj/9/

Fetching content from a form, should I check for undefined or null or?

If I do this:
var text = $("#some-input-box").val();
// check for null/empty string
if(text == null || text = undefined || text.length == 0 ) {
}
I want check for all cases if the value returned is null or empty string etc.
What should I be checking for here?
Is it a good idea to make a generic function that returns true/false if the text is empty or null or undefined ?
you can try out validation plugins like
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Or
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
You should check for any invalid data, to make sure the user doesn't put something in that breaks some other functionality.
Maybe the validation plugin?
http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Categories