HTML Input element (field.validate) is always undefined - javascript

I'm having two text boxes defined with an onblur event. On pressing tab, whenever the onblur event is get called field.validate is always undefined.
At the same time, when I'm trying to print field.name or field.getAttribute("validate") it does return the proper value.
<input width="100%" type="text" name="NV_active" id="NV_active" value="5" onblur="return doValidate(this);" validate=" return validateValueField(document.getElementById('NV_active'), 'Active' );">
<input width="100%" type="text" name="NV_throttled" id="NV_throttled" value="15" onblur="return doValidate(this);" validate=" return validateValueField(document.getElementById('NV_throttled'), 'Throttled' );">
function doValidate(field) {
console.log("field.validate- " + field.validate); //always printing undefined
console.log("getAttr- " + field.getAttribute("validate")); //return validateValueField(document.getElementById('NV_active'), 'Active' );
if (field.validate != null) {
var f = new Function(field.validate);
return f();
}
return true;
}
function validateValueField(field, displayName)
{
if ((field.name == 'NV_activePollingInterval') || (field.name == 'NV_throttledPollingInterval') )
{
//some validation code and error alert message
}
}
I am not able to figure it out why it's always undefined.

Using field.getAttribute('attr') you retrieve the value of the DOM element's attribute.
Using field.attr you retrieve the property attr of the DOM element and they are not always the same thing.
I recommend you to check this SO question: getAttribute() versus Element object properties? and the accepted answer, it should help you.

Related

ASP.NET UserControl javascript is not loading HTML to its variable

I have created UserControl that I wish to use on multiple pages. This control contains classic javascript but for some reason it will not load element to a variable. Client IDs look ok.
This is button that activates javascript:
<input type="submit" name="ctl00$ContentPlaceHolder1$ContactList$btn_NewContact" value="Potvrdit" onclick="javascript:return CheckContactName();" id="ContentPlaceHolder1_ContactList_btn_NewContact" class="MyButton" style="color:white;" />
This is the textbox:
<input name="ctl00$ContentPlaceHolder1$ContactList$con_fullname" type="text" id="ContentPlaceHolder1_ContactList_con_fullname" class="MyTextBox" />
This is Javascript function:
function CheckContactName() {
name = document.getElementById("ContentPlaceHolder1_ContactList_con_fullname");
if (name.value == '' | name.value == null) {
return false;
}
UploadContact();
return true;
}
Now, when I debug this in a console the name.value is undefined. The name variable itself is just "[object HTMLInputElement]".
So no matter what is in that textbox, this function is always false. I also checked all IDs inside final client page and there are no duplicates. Can you tell why this is? Thanks.
I supose you set the input's value in code behind right?
Anyways, you might try using document.querySelector, and it seems that your logical operator is wrong, you are using | instead of ||.
function CheckContactName() {
let name = document.querySelector(
'#ContentPlaceHolder1_ContactList_con_fullname'
);
if ((name.value == '') || (name.value == null) || (name == undefined)) {
return false;
}
UploadContact();
return true;
}
Changed name to cname.
It seems that when you use control on a page that already contains some JavaScript function and that function declares variable with the same name as the one in usercontrol - this happends.

display a hidden input field when enter value on a particuloar input filed

anyone could help me out on how i could achieve this with either javascript or jquery maybe to get the following as mentioned below
say i have this field1
<input type="text" name="field1" value="">
and then i have this field2
<input type="hidden" name="field2" value="">
what i mean to say the field2 should be hidden but if someone enters some value in field1 then field2 shows but if no value on field1 then it disappears?
thanks in advance and appreciate your time and help
You'd get the first field, check if it has a value, and toggle the second field based on that, but you should not be using a hidden input, but instead hide it with CSS
$('[name="field1"]').on('input', function() {
var el = $('[name="field2"]').toggle( this.value !== "" );
if (this.value === "") el.val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="field1" value="" placeholder="type something">
<br><br>
<input type="text" name="field2" value="" style="display:none">
As you've also tagged your question with JavaScript it seems worth offering the following:
// retrieving the first - if any - element with its
// 'name' attribute equal to the value of 'field1':
var input = document.querySelector('[name=field1]');
// adding an event-listener to that element, listening
// for the 'input' event (keyup, paste, copy...) and
// assigning the method's anonymous function as the
// event-handler:
input.addEventListener('input', function(e) {
// 'e': here unused, is a reference to the event
// which triggered the function to be called; using
// e.type will give the specific event, if required
// (and other properties are, of course, available).
// retrieving the first - if any - element with has
// its 'name' attribute equal to 'field2':
var conditionalInput = document.querySelector('[name=field2]');
// if the value of the <input> element that received
// the event has a value that, when leading and trailing
// white-space is removed, results in a truthy
// evaluation (the string length is non-zero):
if (this.value.trim().length) {
// we set the display style of the conditionally-
// shown <input> to 'block', you could instead use
// 'inline-block' if you prefer:
conditionalInput.style.display = 'block';
// otherwise, if the length of the trimmed-value is
// zero (falsey):
} else {
// we set the display style of the conditionally-
// shown <input> to 'none':
conditionalInput.style.display = 'none';
// and also remove its entered value:
conditionalInput.value = '';
}
});
var input = document.querySelector('[name=field1]');
input.addEventListener('input', function(e) {
var conditionalInput = document.querySelector('[name=field2]');
if (this.value.trim().length) {
conditionalInput.style.display = 'block';
} else {
conditionalInput.style.display = 'none';
conditionalInput.value = '';
}
});
<input type="text" name="field1" value="" />
<input type="text" name="field2" value="" />
In your HTML please note that I've adjusted the <input> element's type, from 'hidden' to 'text', this is because some browsers – I believe mostly Internet Explorer – has, or had, issues when changing the type of an <input> element dynamically.
If your use-case doesn't depend on cross-browser compatibility then you can, of course, change the type (conditionalInput.type = 'text'/conditionalInput.type = 'hidden') rather than the display.

Jquery `.find()` cannot find `document` `input` with value=

I have a button where i append inputs to the HTML DOM.
Later on i have a button to fetch input values if they matches with a keyword.
In this example "a".
HTML
<button class="btn btn-info" id="btnAddInput">Add input</button>
<button class="btn btn-info" id="fetchValue">Fetch value</button>
<div id="inputs"></div>
JS
$('#btnAddInput').on('click', function() {
$('#inputs').append('<input type="text" class="myInput"><br>');
});
$('#fetchValue').on('click', function() {
var value = $(document).find('input[value="a"]');
console.log(value);
});
Fiddle: https://jsfiddle.net/Ljrkdm53/
I´ve learned that, if you add HTML to the DOM with Jquery, you sometimes have to use document as selector, to find elements.
But i have no success in this case.
Inputs that you add is, in my code saved into mysql.
And if you load up all saved inputs at start, the js code find values.
So, what am i missing?
You're confusing the various values associated with inputs. You're not the only one!
The value attribute specifies the initial value of the input. It does not change when the input's value changes, and so since you're appending an input that has no value attribute, then typing in it, it doesn't suddenly get a value attribute — so you can't search for it by that value.
The value property on HTMLInputElement instances reflects the input's current value.
There's also the defaultValue property, which reflects the value attribute.
If you need to find an input based on its current value, there's no CSS selector that will do it, you need to use a broader search and filter:
var inputsWithA = $("input").filter(function() {
return this.value == "a";
});
Here's a quick example showing the values of an input's value property, defaultValue property, and value attribute:
$("button").on("click", function() {
var input = $("input");
msg("The input's <code>value</code> property is: '" + input.val() + "'");
msg("The input's <code>defaultValue</code> property is: '" + input.prop("defaultValue") + "'");
msg("The input's <code>value</code> <strong>attribute</strong> is: '" + input.attr("value") + "'");
msg("We can only use CSS with the attribute, so for instance <code>$('input[value=\"original\"]')</code> will find it but <code>$('input[value=\"" + input.val() + "\"]')</code> will not:");
msg("<code>$('input[value=\"original\"]')</code> found it? " +
($('input[value="original"]').length ? "Yes" : "No")
);
msg("<code>$('input[value=\"" + input.val() + "\"]')</code> found it? " +
($('input[value="' + input.val() + '"]').length ? "Yes" : "No")
);
});
function msg(html) {
$("<p>").html(html).appendTo(document.body);
}
<p>Type something in the input, then click the button:</p>
<input type="text" value="original">
<button type="button">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If I run that and change the input's value to "updated" before clicking the button, I get:
The input's value property is: 'updated'
The input's defaultValue property is: 'original'
The input's value attribute is: 'original'
We can only use CSS with the attribute, so for instance $('input[value="original"]') will find it but $('input[value="updated"]') will not:
$('input[value="original"]') found it? Yes
$('input[value="updated"]') found it? No
Here is the code you need.
$('#btnAddInput').on('click', function() {
$('#inputs').append('<input type="text" class="myInput"><br>');
});
$('#fetchValue').on('click', function() {
var value = $('.myInput').val();
console.log(value);
});
You can check it working here:
jsfiddle.net/Ljrkdm53/7
What you are missing is that the find returns an array of objects and not one value and that the value selector only uses the initial value. You need to use an each function on the value you have now to do something with it.
$(document).find('input').each(function () {
if( $(this).val() == "a")
console.log( $(this).val());
});
Try with each function.
$('input').each(function() {
if ($(this).val() == 'a') {
console.log('a');
}
});

Javascript can't locate HTML form ID

I'm creating a basic HTML form, and a Javascript form validator that looks for any input value in the "first name" field. The problem I'm having is that nothing seems to be working to return the first name form value to check it in JS.
Relevant HTML:
<form id="form1" name="formName">
First name:<br>
<input type="text" id="fn" >
<br>
Last name:<br>
<input type="text" name="ln" >
<br>
Email address: <span style="color:red">(required)</span><br>
<input type="text" name="email" >
<br><br>
<button onclick="validate()">Submit</button>
</form>
My JS:
var validate = function (){
var x = document.getElementById("fn").value;
if (x == null || "" || "undefined"){
alert("Please fill out your first name");
return false;
}
kickoff();
}
var kickoff = function () {
var visitor = document.forms["form1"].fn.value;
alert("Thanks for filling out, " + visitor +"\n");
return visitor;
};
Here's a JSFiddle.
My X variable is never reached, it seems, and keeps returning "undefined" when I submit the page. I've been fiddling with it for quite a while and can't seem to figure out what I'm doing wrong. Any help?
This doesn't mean what you think:
if (x == null || "" || "undefined") {
Can also be written as:
if ((x == null) || // might be false
"" || // will be false
"undefined" // will be true
) {
so the if will always be true.
You really just need:
if (! x) {
Besides the syntax issues, that method is also out-of-scope. You're not even going to be able to debug the issue with your conditional until you fix that.
You can either in-line the script higher up in the DOM or define validate directly on the window object:
window.validate = function () {
http://jsfiddle.net/frg37t3u/5/
Neither case is ideal, you should know. Globals are bad, but that's another discussion.

Change the bgcolor of array textbox if NULL

I have this input text which have a name="quiztxtBox[]", as you can see, it is an array. I want to change the color of the bg of the textbox if the value of a certain textbox is null.
var quiztxtBox = document.getElementById('quiztxtBox[]');
for (i=0; i<quiztxtBox.length; i++)
{
if (quiztxtBox[i].value == "")
{
alert('Either question or answer is empty.');
quiztxtBox[i].focus();
quiztxtBox[i].css({"background-color":"#f6d9d4"});
return false;
}
}
You're using .css() which is a jQuery function.
You should either include jQuery on your page, add cast your DOM element to a jQuery object and apply the the .css() function like so
Also you should be using getElementsByName
$(quiztxtBox[i]).css({..});
or just use vanilla JS as shown below
var quiztxtBox = document.getElementByName('quiztxtBox[]');
for (i=0; i<quiztxtBox.length; i++) {
if (quiztxtBox[i].value === "") {
alert('Either question or answer is empty.');
quiztxtBox[i].focus();
quiztxtBox[i].style.backgroundColor = '#f6d9d4'; // this line
}
}
DEMO
I am not sure If your approach is correct, getElementById always returns one element and no collections, perhaps it would be better if you could get the collection of textboxes using
document.getElementsByName('quiztxtBox')
But remember you might have to update the name attribute of all your textboxes to something like
<input name="quiztxtBox" value="yourvalue" id="someuniquestuff1" />
<input name="quiztxtBox" value="yourvalue" id="someuniquestuff2" />
<input name="quiztxtBox" value="yourvalue" id="someuniquestuff3" />
<input name="quiztxtBox" value="yourvalue" id="someuniquestuff4" />
Thanks

Categories