What is the value of an empty text input box? - javascript

I am trying to implement a search box. The following is the code (both HTML and JS)
HTML
<form>
<input type="text" ng-model="searchVar" class="searchbox">
<input type="button" value="Search" ng-click="Search()" class="button">
</form>
JS
var Search = function() {
/* code to implement the table content loading part */
//The following is what I have to filter out the table contents based on input in the text field
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {
ItemsToDisplay.push(tableContent[i])
}
//Call function to load table
}
What is happening is that, if I enter some string into the input text field, the search algorithm works fine and only the relevant items are displayed. However, if I clear the contents of the search box and click on Search button, nothing is displayed in the table. That is, when the text field is cleared and clicked on the search button, it is as if ItemsToDisplay is empty and the if condition fails.
Can someone explain why this is the case? And how I can solve this?

Before your indexOf($searchVar) you should check that searchVar is != ''. Otherwise no item will be displayed afterward. A suggestion, javascript has a really great console.log functionality that will help you a lot when it comes to if branches

If you cleared input, the value of $scope.searchVar willbe undefined and your condition
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {...}
will be false, so you didn't push into ItemsToDisplay and nothing append.
I suggest you to write an else statement :
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {...}
else {
ItemsToDisplay.push(tableContent[i]);
}

U can try with,
if (($scope.searchVar) != undefined)
or
if (typeof ($scope.searchVar) != 'undefined')

when you do not enter anything in INPUT box then its value become UNDEFINED.
you will have to check in if() condition, if input is undefined then write your logic, if input has some value then write your logic.
<form>
<input type="text" ng-model="searchVar" class="searchbox">
<input type="button" value="Search" ng-click="Search()" class="button">
</form>
var Search = function()
{
if ( $scope.searchVar == undefined){
//Do something, input box is undefined
}
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {
ItemsToDisplay.push(tableContent[i]);
}
}

Related

Trying to remove disable attr on an html button tag when the input value is > 0 && value !== undefined

Struggling to remove the disable attr. on a button.
Javascript is not reading anything I put into the input field
I have tried a lot of things...lol
// Here is my button in Html
<button id="rollDice" class="mainBtns btn-roll" disabled>
<i class="ion-ios-loop"></i>Roll dice</button>
<input class="finalScore" type="text" placeholder="Winning Score">
// My JavaScript to see if value is true / false
var enableRoll = document.querySelector('.finalScore').value;
if (enableRoll > 0 && enableRoll !== undefined) {
document.getElementById('rollDice').removeAttribute('disabled');
}
When I enter a value into the Html Page, it isnt registered.
When I wrap Number() around enableRoll i get NaN --
Im not sure what I am doing wrong. Thanks in advance for any help :)
Here is a sample of enabling it when the text changes. Note use of parseInt
const enableRoll = () => parseInt(document.querySelector('.finalScore').value);
document.addEventListener('DOMContentLoaded', () => {
// NOTE: Change occurs when loses focus
document.querySelector('.finalScore').addEventListener('change', () => {
if (enableRoll() > 0) {
console.log('enabling button');
document.getElementById('rollDice').removeAttribute('disabled');
}
});
});
<button id="rollDice" class="mainBtns btn-roll" disabled>
<i class="ion-ios-loop"></i>Roll dice</button>
<input class="finalScore" type="type" placeholder="Winning Score">
You should use onkeyup if you want your button to be enabled while user types in the input field.
I suggest you use a number input so you are pretty sure only numbers can be entered. That might not be enough and if you have a 'sensible' application, you should consider adding more validation for this. Plus some other validations regarding not starting with 0 and so on.
I also suggest you use const and let when declaring variables. There is a ton of documentation on the web regarding this.
And ofc use an else statement if the user deletes all the input content/value.
const input = document.querySelector('.finalScore');
const button = document.getElementById('rollDice');
input.onkeyup = function(e) {
const enableRoll = parseInt(e.target.value,10)
console.log(enableRoll)
if (typeof enableRoll !== undefined && enableRoll > 0) {
button.removeAttribute('disabled')
} else {
button.setAttribute('disabled','disabled')
}
}
<button id="rollDice" class="mainBtns btn-roll" disabled>
<i class="ion-ios-loop"></i>Roll dice</button>
<input class="finalScore" type="text" placeholder="Winning Score" >
P.S. Word of advice. When comparing number values do not use if (value) to check if the value exists. Compare it with undefined or/and null. Because if the value is 0, the if will return false. Just putting this out there :)
Just use:
document.getElementById('rollDice').disabled = false
There is no need ot validate enableRoll !== undefined, cause undefined > 0 returns false
For the NaN part, any NaN will return NaN > 0 false

forcing focus to remain on a form text element until the value is numeric

I have a form which has input fields that expect numbers only.
I'm using javascript to validate the form when the value of the field changes.
If the value is numeric, do nothing.
If the value is not numeric, set it to zero and put focus in that text field. Essentially, I'm trying to trap the cursor in that field until a numeric value is entered. For some unknown reason, focus is not being placed on that form element. cell.focus() does not work. I've even tried document.getElementById(cel.getAttribute("ID")).focus(); What might I be doing wrong?
<html>
<head>
<script>
function NAN(cell){
if (cell.value != "") {
var re = /^(0|[1-9][0-9]*)$/;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = "0";
cell.focus();
}
}
}
</script>
</head>
<body>
<input type="text" name="num" value="" onchange="NAN(cell)"/>
</body>
</html>
Your problem is in the onchange attribute:
<input type="text" name="num" value="" onchange="NAN(cell)"/>
The value is executed as JavaScript code directly. You're passing code, not just a generic signature or prototype.
Inside those event handler snippets, there's a special object this defined, referring to the current DOM element (the input tag in this example).
(Just to mention it, there is also a second predefined object event, which most likely caused your confusion.)
As a simple fix for your issue, replace cell with this in the call and it should work:
<input type="text" name="num" value="" onchange="NAN(this)"/>
It's also important to note that you should keep in mind that this verification requires JavaScript to be executed. If it's disabled, the user might still pass any values, so you should check the value server side as well (assuming this isn't just client-only code).
As an alternative to using JavaScript, you could just use HTML5 to force a specific pattern on inputs. In this case this would be trivial to do:
<input type="text" name="num" value="" pattern="(?!0)\d+" title="Quantity">
The user won't be able to submit the form unless the pattern is validated, so there's no need to force the input focus. The pattern always has to match the full value, from beginning to the end. The title attribute is typically used to provide more information in the error popup.
There are two things done:
You have to change cell to this with onchange.
According to this question at least with Firefox setTimeout has to wrap this focus-method so that it works as expected.
And a more user-friendly approach is inserted as well at the second input-field.
Hope this example helps you:
function NAN(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
}, 0);
}
}
}
/*
* a more user friendly approach
*/
function NAN2(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
markElement(cell);
}, 0);
}
else{
tickElement(cell);
}
}
}
function tickElement(cell){
cell.setAttribute('style','border: 1px solid green');
}
function markElement(cell){
cell.setAttribute('style','border: 1px solid red');
}
<p>
Your approach(onchange):
<input type="text" name="num" value="" onchange="NAN(this)"/>
</p>
<p>
Or you can use a more user friendly approach to notify an user right now when they are tipping something wrong (onkeyup):
<input type="text" name="num" value="" onkeyup="NAN2(this)"/>
</p>

How can i validate form with JavaScript

I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.
I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect".
How i can do it, help.
<form action="" method="post">
<input type="text" name="text1" placeholder="Text 1">
</br>
<input type="text" name="text2" placeholder="Text 2">
</br>
<input type="submit" value="Enter">
</form>
What kind of validation are you interested in ?
You can do everything with javascript my friend:).
This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.
<html>
<body>
<form name="LovelyForm" action="" method="post">
<input type="text" name="text1" placeholder="Text 1"> </br>
<input type="text" name="text2" placeholder="Text 2"> </br>
<input type="submit" onclick="validateForm()" value="Enter">
</form>
<script type="text/javascript">
function validateForm() {
var x = document.forms["LovelyForm"]["text1"].value;
var y = document.forms["LovelyForm"]["text2"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Fill me in");
return false;
}else{
alert("Good");
return true;
}
}
</script>
</body>
</html>
Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.
If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.
Here: Best practice as I see it :)
Only validate the most necessary on client side.
Avoid compulsory input unless they realy are.
Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.
Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/
form.elements['one'].value may cause issues if the inputs are not of type text.
The code:
<script>
function trim(str) {
if(!str) return '';
return str.replace(/\s{2,}/g, '');
}
function valid(form) {
var v1 = trim(form.elements['one'].value),
v2 = trim(form.elements['two'].value);
if (v1 === '') {
alert('one');
return false;
}
if (v2 === '') {
alert('two');
return false;
}
alert('full!')
return true;
}
</script>
<form action="/echo/json/" onsubmit="return valid(this)">
<input name="one" type="text" />
<input name="two" type="text" />
<input type="submit" />
</form>
First step is to give JavaScript an easy way to reference the element in the DOM. Generally, the easiest way is to give each element you need to reference a unique ID.
<input id="num1" />
<input id="num2" />
Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.
var val1 = i1.value;
var val2 = i2.value;
Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.
if(
// if the first value does not equal an empty string ""..
val1 != ""
// and the second value does not equal an empty string ""..
&& val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');
Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler. When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.
<form action="#" onsubmit="validate()">
<input id="num1" />
<input id="num2" />
<input type="submit" />
</form>
<script>
function validate(){
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
var val1 = i1.value;
var val2 = i2.value;
if(val1 != "" && val2 != "") alert("correct");
else alert("incorrect");
}
</script>

How to check if an input is a radio - javascript

How can I check if a field is a radio button?
I tried if(document.FORMNAME.FIELDNAME.type =='radio') but document.FORMNAME.FIELDNAME.type is returning undefined.
The html on the page is
<input name="FIELDNAME" type="radio" value="1" >
<input name="FIELDNAME" type="radio" value="0" >
Unless I am taking the whole approach wrong. My goal is to get the value of an input field, but sometimes that field is a radio button and sometimes its a hidden or text field.
Thanks.
Your example does not work because document.FORMNAME.FIELDNAME is actually an array with 2 elements (since you have 2 inputs with that name on the form). Writing if(document.FORMNAME.FIELDNAME[0].type =='radio') would work.
EDIT: Note that if you don't know if document.FORMNAME.FIELDNAME is a radio (ie you might have a text/textarea/other) it is a good idea to test if document.FORMNAME.FIELDNAME is an array first, then if the type of it's first element is 'radio'. Something like if((document.FORMNAME.FIELDNAME.length && document.FORMNAME.FIELDNAME[0].type =='radio') || document.FORMNAME.FIELDNAME.type =='radio')
In case you don't have a form then maybe go by attribute is an option.
var elements = document.getElementsByName('nameOfMyRadiobuttons');
elements.forEach(function (item, index) {
if (item.getAttribute("type") == 'radio') {
var message = "Found radiobutton with value " + item.value;
if(item.checked) {
message += " and it is checked!"
}
alert(message);
}
});
Your code should work, but you could try the following:
document.getElementById('idofinput').type == 'radio'
Edit: Your code doesn't work for the reason mihaimm mentions above

Set default value for Search field - Please Help!

I'm trying to set a default value for a search field. The idea is that the Search-Field has the value "Search" until the user clicks into it, then it should be empty. Also as long as it is "blank" (with "Search" as the value) it should have the class ".blank".
I tried this
<input autocomplete="off" class="" id="searchq" name="searchq" onblur="if (this.value == '') { this.value='Search'; jQuery(this).addClass('blank'); };" onfocus="if (this.value == 'Search') { this.value=''; jQuery(this).removeClass('blank'); };" type="text" value="" />
it works so far, but when I load the site, the field is just empty. I have to click inside the field first and then somewhere on the page to make the effect working.
I guess it has something to do with onBlur. Any ideas?
Thanks!
This is known as a watermark. see http://digitalbush.com/projects/watermark-input-plugin/ for an example
Another idea is to put placeholders in your input types:
(Note this is HTML5.)
<input type=text placeholder="Default text here"/>
this way the textfield will show in a grey text color: Default text here. Once clicked it will remove the text and replace it with your current text and when its empty it comes back.
Just give it the default value 'Search' hardcoded, as in
<input ... type="text" value="Search" />
Sounds like you just need to set the initial value to Search, directly in the input tag, like so:
<input autocomplete="off" class="blank" id="searchq" name="searchq" onblur="if (this.value == '') { this.value='Search'; jQuery(this).addClass('blank'); };" onfocus="if (this.value == 'Search') { this.value=''; jQuery(this).removeClass('blank'); };" type="text" value="Search" />
Note that we also set the initial class to blank as well.
I found the problem, my mistake: onBlur is called, when the user clicks somewhere else. onLoad is only allowed for the tags BODY and FRAMESET. The solution is to set the default value somewhere serverside (for me in the application_controller, if no search term is submitted).
Thanks anyway!
blur is when a field looses focus, it cant loose focus until it has focus to begin with, hence you need to click in the field, then click out to see it working. have you tried setting the class to .blank by default ?
<input autocomplete="off" class="blank" ....
Here's a snippet I use to do this. There may be simpler ways, but this works. Any item with class .cleardefault will have it's value cleared on first mouseover. Any item with class .setcleardefault will clear the default and, if the user has not put anything in the box, reset it to the default value on mouse out.
function ClearDefault(item) {
// clear the default value of a form element
if (item.defaultValue == undefined)
item.defaultValue = item.value;
if (item.defaultValue == item.value)
item.value = '';
} // ClearDefault
function SetDefault(item) {
// if item is empty, restore the default value
if (item.value == '')
item.value = item.defaultValue;
} // SetDefault
$(document).ready(function() {
$(".cleardefault")
.mouseover(function(){
ClearDefault(this);
})
$(".setcleardefault")
.mouseover(function(){
ClearDefault(this);
})
.mouseout(function(){
SetDefault(this);
});
/*
*/
});

Categories

Resources