How can i retrieve a fields name - javascript

I have a simple javascript function to check if a field is not empty:
function notEmpty( field , alert_text ){
if (field.val() === "" ||
field.val() === null ||
field.length === 0) {
if ( alert_text ){
alert ( 'Error: please enter some text - ' + alert_text );
} // end if
field.addClass( 'hightlight' );
field.focus();
return false;
} // end if
else {
field.removeClass('hightlight');
return true;
} // end else
I want to get the name of field to show in the alert without using the alert_text argument. I tried a whole load of things, with no luck, so I've left the function as is and I'm using the alert_text argument to pass the field name. All my form input tags are something like this:
<input type= "text"
name= "artist"
id= 'artistfield'
size= "60"
tabindex= "1" />
So they all have 'name' defined. There must be a way to get it into my alert box but I can't figure it out yet. I'm sure it's easy, I'm just very new to this. Thanks.

You can retrieve the name with this:
field_name = field.attr('name');

You can use jQuery's attr() method to get the name (and almost any other HTML attribute):
function notEmpty(field) {
if (field.val() === "" || field.val() === null || field.length === 0) {
if (field.attr('name')) {
alert('Error: please enter some text - ' + field.attr('name'));
}
field.addClass('hightlight');
field.focus();
return false;
} else {
field.removeClass('hightlight');
return true;
}
}

You can use:
field.attr('name')
To get the name attribute from the field. You could change name for id if you wanted the fields ID for example.

To get the name-attribute of an element you can use the attr-function. It can get the value of any attribute.
Eg: http://jsfiddle.net/mqchen/LjFdC/

Related

Check value of both text boxes if they have values in it or not

My page have multiple textboxes i wanted to make sure if user select value from text box 1 and leaves text box 2 empty then it should alert a popup that you must have to enter values in both textboxes.
i do not want to compare values with each other.(Like both textbox value must be same)
Textbox 1 is Number field and text box 2 is date field.
If any one value is entered then it should not allow user to submit page it should stop processing and redirect to that textbox which is empty.
Now what i have tried so far.
$( "#button_id" ).click(function() {
var n = document.getElementById('text1');
var m = document.getElementById('text2');
if(n.value.trim() != "" || n.value == undefined)
{
if (n.value.trim() != "" && m.value.trim() == "")
{
alert("text1 should have some value");
return false;
}
}
if(m.value.trim() != "" || m.value == undefined)
{
if (m.value.trim() != "" && n.value.trim() == "")
{
alert("text2 should have some values");
return false;
}
}
});
As mention below code i just wanted to check if textbox is disable or not if textbox is disable then do not test for validation else do.
Partial Solution :
var _domArray = [$("#textbox1"),$("#textbox2")]
var chk = $x('textbox2').disabled = false;
$( "buttonid" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" );
this.browserEvent.preventDefault();
this.browserEvent.stopImmediatePropagation();
return false;
}
})
});
Use the required attribute on your <input>s, then you can check in JavaScript with document.querySelector('form.insertSelectorHere').matches(':valid').
Use an array to store the DOM element,Loop through it and check to check if it is empty, If so through an alert.
Also assuming you are using input type number & date
var _domArray = [$("#text1"),$("#text2")]
$( "#button_id" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" )
}
})
});
Using jquery since you have tagged this with jquery
jsfiddle

Form is submitting even after failing Javascript validation?

I have a form called here:
<span class="aligncenter button">Submit</span>
And I have a JavaScript function here:
if (myForm == 'newIncident')
{
var vDemAge = document.forms['newIncident']['demAge'].value;
var vBibNumber = document.forms['newIncident']['bibNumber'].value;
// Run through validations before submitting form
validateTime();
validateDate();
validateAge();
validateGender();
validateLocation();
validateType();
validateDisposition();
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
else
{
document.getElementById(myForm).submit();
}
So I have each of the validations as a separate function that I am calling in sequence when submitting the form. If I comment out the "document.getElementById(myForm).submit();", the validations run as expected. However, if I leave it uncommented, it submits every time even if the validations fail. How can I stop this from happening?
Thanks!
EDIT:
So this is one of the validations I'm running. They're all structured the same way. Somewhere I should be returning a boolean true/false? How exactly would I insert that in this one below?
function validateDisposition()
{
var vIncidentDisposition = document.forms['newIncident']['incidentDisposition'].value;
if (vIncidentDisposition == '')
{
document.forms['newIncident']['incidentDisposition'].className = 'required';
}
else
{
document.forms['newIncident']['incidentDisposition'].className = 'formborder';
}
}
assuming your validation functions return a bool, you should have something like
if( validateTime() && validateDate() && validateAge()... etc ) {
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
I got it working! The boolean idea put me on the right path. Thanks!
I just added a "return true" and "return false" to each of the validations, then used the answer above with the "&&" if to build the logic into the myform "if". If it doesn't pass all of them the else does a "return false". Works like a charm!

Issue with Java script / Jquery validation?

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

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

Radio Button, Text Area and Input check

I have a form with all the input fields as class item. When I click submit, it checks, with the following function if all values are filled in.
$.each($(".items"),function(i,e){
// loop through all the items
if(e.value == "" || !$("input[name='"+e.name+"']:radio:checked").length)
if(error.indexOf(e.title) === -1)
error += e.title + "<br/>";
});
This form comprises of text areas, radio boxes and normal text input fields. It returns all the radio boxes not filled in, as well as all the text inputs not filled in. But then it also returns ALL the text areas, regardless of whether it's filled in or not.
I first thought it was because I specified it to check the value, but it seems the value check does in fact check text areas, so it can't be that.
Could anyone assist me in making it return only empty elements?
$.each( $( '.items' ), function() {
if ( ( this.type === 'checkbox' || this.type === 'radio' ) && !this.checked ) {
// Go
}
else if ( this.value === '' ) {
// Do your stuff
}
});
Unfortunately, it seems there is no other choice but to separate the cases.
$.each($('.items'),function(i,elem){
if( ($(elem).attr('type') == 'radio' || $(elem).attr('type') == 'checkbox') && !$(elem).is(':checked') ) {
// RADIOS AND CHECKBOXES EMPTY
} else if( $(elem).val().length == 0 ) {
// INPUTS TYPE TEXT AND TEXTAREA EMPTY
}
});
So I used a combination of JBRTRND and Florian Margaine's answers as neither wanted to work 100% correctly.
I just put this here incase someone is stuck on the same issue. I in no way take credit for ANY of the help I received from them and I'm really thankful for it.
This is how I fixed it:
$.each($(".items"),function(){
// loop through all the items
// and alert the value
if ( this.type == 'radio' && !$("input[name='"+this.name+"']:radio:checked").length) {
if(error.indexOf(this.title) === -1)
error += this.title + "<br/>";
}
else if ( this.value === '' ) {
if(error.indexOf(this.title) === -1)
error += this.title + "<br/>";
}
});

Categories

Resources