Issue with Java script / Jquery validation? - javascript

I have one select box and one text box are there. I need to the validation like if both are selected I need alert like "Either select a name or pick the name", If I did not select both i need alert like "Please select a name or pick the name", If I select one of them I need alert like "Thank you for selecting the name". I did it by java script but I did not get the result. Can it be done by using java script / Jquery? Any suggestions
<body>
pick name:
<select id="ddlView">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</br>
select name:
<input type= "text" name="raju" id="raju"></input>
<input type="button" onclick="Validate()" value="select" />
<script type="text/javascript">
function Validate()
{
var name = document.getElementById("raju");
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0 && (name==null || name== ' '))
{
alert("Please select a name or pick the name");
}
else if( (!(strUser==0)) &&(! (name==null || name== ' ')))
{
alert("Either select a name or pick the name");
}
else
{
alert("Thank you for selecting the name");
}
}
</script>
</body>

Here is your same validation using JQuery as you also mentioned:
function Validate()
{
var name = $("#raju").val();
var selected_name = $('#ddlView :selected').val();
if(selected_name == 0 && name == "")
{
alert("Please select a name or pick the name");
}
else if( !(selected_name == 0) && name != "")
{
alert("Either select a name or pick the name");
}
else
{
alert("Thank you for selecting the name");
}
}
Fiddle

Your problem is that you get the input, not the value.
Replace var name = document.getElementById("raju"); with var name = document.getElementById("raju").value;
Also, you compare the name with null and blank space. You must compare it with empty string. (name == '')

When you saw on my Jsfiddle code, I don't use oonclick attribute but a event listener on javascript (realy better for your html)..
document.getElementById("myBtn").onclick= function ()
One second poitn you have forget tu retrieve .value of you name input (so already return [HTML DOM object] and not null or a value.
var name = document.getElementById("raju").value;

Since your post was in pure JavaScript, I've decided to answer accordingly. As mentioned, you shouldn't check an empty string for " " but rather '' or "". Furthermore, you shouldn't even need to do that, since you can simply check if (str) { // string exists }. For your name variable, you're referring to an HTML element and not it's string value. So, all in all (a few errors), nothing majorly wrong here.
I've abstracted this process a tiny bit to give you an idea of how to validate many similar fields without a whole lot of repetitive code.
Note: You should find a way to replace your inline event handlers with unobtrusive handlers. Example:
document.getElementById('someButton').onclick = Validate;
That being said, here's a few suggestions:
var emptyString = function(str) {
if (str) {
return false;
}
return true;
};
var emptySelect = function(sel) {
if (parseInt(sel) !== 0) {
return false;
}
return true;
};
function Validate() {
var name = document.getElementById("raju").value;
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
switch (true) {
case (!emptySelect(strUser) && !emptyString(name)):
alert('Either select a name or pick a name.');
break;
case (emptySelect(strUser) && emptyString(name)):
alert('Please select a name or pick a name.');
break;
default:
// Possibly some default validation
alert('Thanks for picking a name');
break;
}
}

Related

$('#id_gender') vs var gender = $('#id_gender')

The user is to select gender.
HTML
<form ...>
<select id="id_gender" name="gender" onchange="hideMaidenName(this.value)">
<option value="M">Male</option>
<option value="F">Female</option>
<option value="U" selected="selected">To be defined</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js">
If gender is male, we warn the user that they must clear maiden name by hand. Then they may continue. But in this case we automatically change gender to 'U'.
Could you help me understand the situation.
In the console I have checked what I'd like to transmit into the production code.
In the console:
var gender = $('#id_gender')
gender
[<select id=​"id_gender" name=​"gender" onchange=​"hideMaidenName(this.value)​">​…​</select>​]
gender.val()
"U"
But when I use this code in production, I get exception that gender is not a function. I can make the code execute like this:
Working code:
var maiden_name = $('#id_maiden_name');
function hideMaidenName(gender) {
if ($('#id_gender').val() == 'M') {
if (maiden_name.val() != "") {
$('#id_gender').val('U')
alert("Clear maiden name!");
return;
}
}
}
</script>
And further goes my failure.
Not working code:
var gender = $('#id_gender');
var maiden_name = $('#id_maiden_name');
var maiden_name_row = $('#id_maiden_name_row')
function hideMaidenName(gender) {
if (gender.val() == 'M') {
if (maiden_name.val() != "") {
gender.val('U')
alert("Claear maiden name!");
return;
}
maiden_name_row.hide()
}
else {
maiden_name_row.show()
}
}
Half working code (reduced functionality as I failed to change the value of gender back to 'U':
var gender = $('#id_gender');
var maiden_name = $('#id_maiden_name');
function hideMaidenName(gender) {
if (gender == 'M') {
if (maiden_name.val() != "") {
alert("Claear maiden name!");
return;
}
}
}
The questions are:
What is the difference between $('#id_gender') and var gender = $('#id_gender'). I mean why the former is working perfectly whereas the latter throws an exception.
Why in the half working code gender == 'M' works perfectly? Gender seems to be an element whose value I'm going to check. But here we have value itself stored in gender.
I have the working code, but I look for the gender element twice.
How should I prevent double finding if possible?
You pass as argument to the function hideMaidenName the value of the selected option on change(this is the string for example 'M'). I changed it to pass the DOM element(select), by passing this as argument. You also have to wrap the gender and use it as jquery object for example $(gender) otherwise you get the error .val() is not a function:
var gender = $('#id_gender');
var maiden_name = $('#id_maiden_name');
var maiden_name_row = $('#id_maiden_name_row')
function hideMaidenName(gender) {
//here you have to use gender as jquery object
if ($(gender).val() == 'M') {
if (maiden_name.val() != "") {
gender.val('U')
alert("Claear maiden name!");
return;
}
maiden_name_row.hide()
} else {
maiden_name_row.show()
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="id_gender" name="gender" onchange="hideMaidenName(this)">
<option value="M">Male</option>
<option value="F">Female</option>
<option value="U" selected="selected">To be defined</option>
</select>
Instead of setting the value of the select field you could just set the option with the value U as selected manually.
$('select#id_gender option[value="U"]').prop('selected', true)
EDIT:
var gender = $('#id_gender');
var maiden_name = $('#id_maiden_name');
function hideMaidenName(gender) {
if (gender == 'M') {
if (maiden_name.val() != "") {
//selecting option with value "U"
$('select#id_gender option[value="U"]').prop('selected', true)
return;
}
}
}
EDIT2:
There is no difference. The difference is that you write the element into a variable to you don't need to search the DOM multiple times.
Ill try to answer the other questions later.

Using Javascript to select a value from a Html Select box

Hey guys I am using JavaScript to select a specific value(option) from the html select form tag, but whenever I call my JavaScript function I get a single message repeating for all the choices I want to select.
Ex: If I choose to select 'Rabbit' from the list of options and then display a message saying 'Rabbit chosen'; the message will display for each option/value selected.
Here is my JavaScript Code:
var element = document.getElementById('choices').value;
function SelectElement() {
if (element = 'Rabbit') {
alert("Rabbit Selected");
}
else if (element = 'Wall') {
alert("Wall Selected");
}
else if (element = 'Arrow') {
alert("Arrow Selected");
}
}
Here is my html code:
<form>
<select id="choices" >
<option>Rabbit</option>
<option>Wall</option>
<option>Arrow</option>
</select>
<input type="button" value="Submit" onclick="SelectElement()"/>
</form>
Can you smart guys please help me????
A. You should fetch the value each time before calling the function and then check it otherwise your element variable won't refresh at all.
B. To compare two values you should use ==, = is an assignment operator.
function SelectElement() {
var element = document.getElementById('choices').value;
if (element == 'Rabbit') {
alert("Rabbit Selected");
}
}
(As your question is not much clear) if you just want to alert the selected value for every option clicked, just do:
function SelectElement() {
var element = document.getElementById('choices').value;
alert(element+" Selected");
}
This is basic string concatenation.
There is a something called selected == true or false in a "select" tag.
You could write in HTML :
<form>
<select id="choices">
<option id="Rabbit">Rabbit</option>
<option id="Wall">Wall</option>
<option id="Arrow">Arrow</option>
</select>
</form>
<button onclick="TakeElement()">Click</button>
You could write in javascript:
var ra = document.getElementById('Rabbit');
var wa = document.getElementById('Wall');
var ar = document.getElementById('Arrow');
function TakeElement() {
if (ra.selected == true) {
alert("Rabbit is selected");
}
if (wa.selected == true) {
alert("Wall is selected");
}
if (ar.selected == true) {
alert("Arrow is selected");
}
}
I think you must replace element ='rabbit' with element =='rabbit'
== is comparison operator
and = is assignment operator

Return false if no value is selected (other than heading) from select box

I have a HTML form having select box. On selection of first drop down, next drop down should be auto filled using AJAX.
On Download Records (id="getCsv") button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code
var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();
var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();
var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();
var subject_name = $("#sel_sub1 option:selected").text();
if (teacher_name == "") {
alert('Please Select Teacher Name.');
return false;
} else if(class_name == "") {
alert('Please Select Class Name.');
return false;
} else if(division_name == "") {
alert('Please Select Division Name.');
return false;
} else if(subject_name == "") {
alert('Please Select Subject Name.');
return false;
} else if(unittest_name == "") {
alert('Please Select Unit Test Name.');
return false;
} else {
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;
var formData = JSON.stringify(myObject);
$('#getCsv').attr('href','csv_generator.php?data=' + formData);
}
The problem is that when I click Download Records, even though the first select box is empty directly alert box for second select box pops up. I tried to solve this problem using the below, but no luck.
if ($("#sel_teacher").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
return false;
}
Can anybody please help me with this? Any help is appreciated.
selectedIndex is a property, use prop:
$("#sel_teacher").prop("selectedIndex")
Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
}
// test other values here...
It might be because of the default value that you have given for the first text-box.Just change the value to "" onclick or on blur on that text-box.
Or you can simply handle this matter via HTML5 attribute required and adding onchange() Event Listener .
<select name="sel_teacher" onchange="get_value();" id="sel_teacher" required>
<option>--Select Teacher Name--</option>
</select>
<script>
function get_value() {
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
} else {
// write code when teacher_name is selected
}
}
</script>

compressing validation tactics

The following validation code was handed to me and it just looks so repetative. How could I learn from his example on how to reduce the duplicate processes that occur for each input field that is being validated below....? I want to be more efficient with JavaScript, not repeat the same functions over and over again just because a form adds on a new input element...
function isRequired(){
firstNameRequired();
lastNameRequired();
stateRequired();
gradYearRequired();
relationshipRequired();
birthdayRequired();
}
function firstNameRequired(){
var firstName = document.forms['subscribeForm']['First Name'].value;
if (firstName == null || firstName ==''){
alert('Please enter your first name.');
document.subscribeForm.elements['First Name'].style.backgroundColor='yellow';
return false;
}
}
function lastNameRequired(){
var lastName = document.forms['subscribeForm']['Last Name'].value;
if (lastName == null || lastName ==''){
alert('Please enter your last name.');
document.subscribeForm.elements['Last Name'].style.backgroundColor='yellow';
return false;
}
}
function stateRequired(){
var state = document.forms['subscribeForm']['State'].value;
if (state == null || state ==''){
alert('Please enter your state of residence.');
document.subscribeForm.elements['State'].style.backgroundColor='yellow';
return false;
}
}
function gradYearRequired(){
var gradYear = document.forms['subscribeForm']['Graduation Year'].value;
if (gradYear == null || gradYear ==''){
alert('Please enter your graduation year.');
document.subscribeForm.elements['Graduation Year'].style.backgroundColor='yellow';
return false;
}
}
function relationshipRequired(){
var relationship = document.forms['subscribeForm']['ABC Link Relationship'].value;
if(relationship == null || relationship == ''){
alert('Please enter your relationship to ABC.');
document.subscribeForm.elements['ABC Link Relationship'].style.backgroundColor='yellow';
return false;
}
}
function birthdayRequired(){
var birthDay = document.forms['subscribeForm']['Birthdate'].value;
if(birthDay == null || birthDay == ''){
alert('Please enter your birthday.');
document.subscribeForm.elements['Birthdate'].style.backgroundColor='yellow';
return false;
}
}
...
<input type="submit" class="submitBtn" value="" onclick="isRequired()" />
Also, I have the flexibility to work in jQuery if need be.
Detect what parts in your code are repetitive and what parts do change from field to field. For example, you could create a function that takes two parameters: the field name and its label.
function validateRequiredField(name, label)
{
var value = document.forms['subscribeForm'][name].value;
if (value == null || value == '') {
alert('Please enter your ' + label);
document.forms['subscribeForm'][name].style.backgroundColor = 'yellow';
return false;
}
}
Then you can just call this function passing the name and the label as parameter:
validateRequiredField('First Name', 'first name');
validateRequiredField('ABC Link Relationship', 'relationship to ABC');
// ...
Keep in mind that these validations should be done also in server side, because someone can just disable JavaScript and send your form skipping your client side validation functions.
Because the only data being passed is the object and the alert message, instead of a whole custom function, use a single function with object and message params.
function isRequired(){
required(document.forms['subscribeForm']['First Name'],'first name');
required(document.forms['subscribeForm']['Last Name'],'last name');
required(document.forms['subscribeForm']['State'],'state of residence');
required(document.forms['subscribeForm']['Graduation Year'],'graduation year');
required(document.forms['subscribeForm']['ABC Link Relationship'],'relationship to ABC');
required(document.forms['subscribeForm']['Birthday'],'birthday');
}
function required(object,message){
if (!obj) {
alert('Please enter your '+message);
obj.style.backgroundColor='yellow';
return false;
}
return true;
}
First of all I would recommend to use IDs to read out the form fields:
<input type="text" id="firstname" />
This allows you to use jQuery('#firstname') to select this input field.
Second, here's how I'd go about the task of making the code smaller:
What are you trying to do here?
You always read some value from the form (depending on an ID of sorts).
Then you check if that value is null.
If the value is not set you want to display an error message (depending on the ID again).
And you also want to mark the field that was missing and then return false.
So I'd code a function that does exactly that:
// function having a parameter for the ID and the custom error message
function checkFormField(fieldID, errorMsg) {
// read value from field using jquery
value = $(fieldID).value();
// check for null or empty
if (value == null || value == '') {
// display custom error message
alert(errorMsg);
// change color of field using jQuery
$(fieldID).css('background', 'yellow');
return false;
}
}
Now you can reuse this function for every field you want to check. The new isRequired method would look like this:
function isRequired(){
checkFormField('#firstname', 'Please enter your first name.');
checkFormField('#lastname', 'Please enter your last name.');
// and so on...
}
Note that this example would require name attributes that can be used as identifiers (no spaces)
<input name="first_name" type="text" />
<input name="last_name" type="text" />
js:
function validateRequired(slug, field){
// test for passing condition
if (field.value !== null && field.value !== '') {
return true;
}
else {
alert('Please enter your ' + field.str);
}
return false;
}
/**
* Validate a form using a ruleset object
*
*/
function validateFields(ruleset, form){
var field = {};
var errors = 0;
// Loop though the ruleset
for(var index in ruleset) {
//
if (ruleset.hasOwnProperty(index)) {
field = ruleset[index];
// check if input exists
if (form[index]){
field.value = form[index].value
}
if (ruleset[index].required) {
if (!validateRequired(field)){
errors++;
field.invalid = true;
}
}
// you could add more rules here...
}
}
return errors === 0;
}
var valid = validateFields({
first_name : {
required : true,
str: 'first name'
},
last_name : {
required : true,
str: 'last name'
}
// ...
}, document.forms['subscribeForm']);

Wrapper Function not working properly (Javascript)

I have two functions: One the validates the information in name fields of a form, and another that takes the information in those fields and prints them out in an alert box. Separately these functions work fine. I have to call them both, so I created a wrapper function. The function runs, but it refreshes instead of focusing. The weird thing is, if I check the first field, everything is fine, including the .focus();, but when I try to validate the second field, .focus(); doesn't work and the page refreshes. Any help would be appreciated. (I tried to revise my first question to add this, but when I went to save it, nothing happend.)
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
}
function validate() {
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25) {
alert("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25) {
alert("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0) {
alert("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
function concatinate() {
var first = document.getElementById('firstname').value;
var last = document.getElementById('lastname').value;
var title = document.getElementById('title').value;
var fullname = title + " " + first + " " + last;
var printFull = "Welcome, " + fullname;
alert(printFull);
}
<form name="name" form id="name" method="post" onsubmit="return main();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
In your form, you have an erroneous attribute "form" in your <form>, "select" in the middle of the <select> tag, and "input" in the <input> tags. I'm not sure what they are there for, or whether they are causing you trouble, but you should get rid of them nonetheless.
Also, your problem is this line:
document.getElementsByName('lastname').focus();
document.getElementsByName() returns an array, and there is no focus() method on an array. This was causing your issue with validating the last name.
Change it to match your other focus() calls:
document.getElementById('lastname').focus();
I also removed the temporary variable in your main() method:
function main(form) {
if (validate()) {
concatinate();
return true;
}
return false;
}
Working Demo: http://jsfiddle.net/cFsp5/4/
Your main function must return false if validation doesn't pass. Otherwise, it will return undefined, and the form will submit anyway (which is what you describe). So a simple fix would be:
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
return false;
}
http://jsfiddle.net/LhXy4/

Categories

Resources