javascript function is not working ( no errors ) [duplicate] - javascript

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 1 year ago.
hi i have javascript issue that i wrote a input when i change it text to sadra it doesn't alert "your text contains "sadra" word " how can i resolve it ? thanks for helping ...
here is the code:
var realText;
function text(realText) {
var realText = document.getElementById('input1').innerHTML;
if (realText.includes('sadra')) {
alert("your text contains \"sadra\" word ");
}
}
<label>Input :</label>
<input type="text" name="test" id="input1" onchange="text(realText)" />

If you are trying to access the value inside the element with id input1, then the selector should point to value of the node.
document.getElementById('input1').value
Also there is no need to pass the realText parameter to the onchange event. This is not going to have an impact on the functionality.
innerHTML gives the html code inside a specified id
innerHTML Example
function text() {
var realText = document.getElementById('container').innerHTML;
console.log('Inner HTML', realText);
}
<div id="container">
<label>Input :</label>
<input type="text" name="test" id="input1" onchange="text()" />
</div>
Your Working fiddle
function text() {
var realText = document.getElementById('input1').value;
if (realText.includes('sadra')) {
alert("your text contains \"sadra\" word ");
}
}
<label>Input :</label>
<input type="text" name="test" id="input1" onchange="text()" />

Related

Create Custom validation Class in javaScript/Jquery

Let say there is an input element field and i want to create a new validation class myClass ,that i can insert with any html element that might performing some function and also setting attribute such as
readonly="true"
required='true'.
HTML is
<td>
<input type="text" id="endDate" name ="endDate" class="select_200" required readonly="true">
</td>
Now rather setting elements separately need one class for performing:
A function check "let say character count less then 10" and setting
attribute.
Setting attributes such as readonly ,required
So that i can add that class to all elements with similar property.
Validation + Setting/ Reseting attributes by adding class only
You can set your own custom attributes for your input elements and use those custom attributes to query the input fields and perform various actions. You can find my sample below.
$(function () {
//Set various input field attributes here
$("input[data-myCustomClass]").each(function(){
//$(this).attr("readonly", true);
$(this).attr("required", true);
});
//Sets max length - you can change this code to retrieve info from attribute
$("input[data-setFieldLength]").each(function(){
$(this).attr("maxlength", 10);
});
//Validate for field length based on "validateFor" attribute
$("input[data-validateFieldLength]").each(function(){
$(this).on('focusout', function(){
var validateFor = $(this).attr("validateFor");
if ($.trim($(this).val()).length < parseInt(validateFor))
{
$(this).focus();
$(this).select();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" data-myCustomClass data-setFieldLength id="field1" />
<input type="text" data-myCustomClasss id="field2" />
<input type="text" data-setFieldLength id="field3" /> <!-- set field length to 10 -->
<input type="text" data-validateFieldLength id="field4" validateFor="5" /> <!-- validate for 5 characters and return focus -->
you have create new function for a field?
on
<form onsubmit="return validate()" name="form">
<td>
<input type="text" id="custname" name ="endDate" class="select_200"
required readonly="true">
<font style="color:red" id="custnameerror"></font>
</td>
<button onclick="return validate()"></button>
</form>
javascript validation function like
<script type="text/javascript">
function validate(from)
{
var error=document.getElementById("custnameerror");
var custname=form["custname"].value;
error.innerHTML="";
if( custname==null || custname==""){
error.innerHTML="Enter customer name";
return false;
}
if(custname.length<3){
error.innerHTML="Customer name should be minimum 3 character";
return false;
}
if(custname.length>80){
error.innerHTML="Customer name should be in between 3 to 80
character";
return false;
}/*end */
</script>

Why i'm getting the option to use nodeValue insted of just Value? [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 5 years ago.
i'm writing an html page that gets a name, an address and a phone number to practice validation. when the javascript function tries to get the length of the value in the inputs i get this error: "Uncaught TypeError: Cannot read property 'length' of null"
i dont know what nodeValue means but i simply want to get the value in the input.
this is the part of the code in the javascript that gives me the error:
function Validate(nameInput, lastNameInput, addressInput, phoneInput)
{
var errorSpan = document.getElementById("errorSpan");
var okSpan = document.getElementById("okSpan");
var nameErrSpan = document.getElementById("nameErrSpan");
var lastNameErrSpan = document.getElementById("lastNameErrSpan");
var addressErrSpan = document.getElementById("addressErrSpan");
var phoneErrSpan = document.getElementById("phoneErrSpan");
var nameLength = nameInput.nodeValue.length;
var lNameLength = lastNameInput.nodeValue.length;
var addressLength = addressIput.nodeValue.length;
var phoneLength = phoneInput.nodeValue.length;
what do i need to change to just get the value in the inputs and measure them?
here is my html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validation Form</title>
</head>
<body>
<div>
<span>First name:</span><br />
<input type="text" id="firstName" /> <span id="nameErrSpan" class="nHidden">Name Must Be Between 3 - 10 Letters</span>
<br>
<span>Last name:</span><br />
<input type="text" id="lastName" /> <span id="lastNameErrSpan" class="lnHidden">Last Name Must Be Between 3 - 10 Letters</span>
<br>
<span>Address:</span><br />
<input type="text" id="address" /> <span id="addressErrSpan" class="adHidden">Address Must Be Between 10 - 25 Letters</span>
<br>
<span>Phone number:</span><br />
<input type="text" id="phoneNumber" /> <span id="phoneErrSpan" class="pHidden">Phone Must Be Between 3 - 10 Digits</span>
<br>
<button onclick="Validate(firstName, lastName, address, phoneNumber)">Check</button><br />
<span id="errorSpan" class="hidden">Missing fields</span><br />
<span id="okSpan" class="hidden">All fields are filled</span><br />
<button onclick="reset()">Reset</button><br />
</div>
<link rel="stylesheet" href="registrationForm.css">
<script src="registrationForm.js"></script>
</body>
</html>
To get the text entered into an input, you should use .value, not .nodeValue.
var nameLength = nameInput.value.length;
var lNameLength = lastNameInput.value.length;
var addressLength = addressIput.value.length;
var phoneLength = phoneInput.value.length;
The value of an input element is available from its value property. nodeValue is a property of all DOM nodes, and not relevant to input elements.

checking for an empty input [duplicate]

This question already has answers here:
How to select empty inputs (value="") using jQuery
(7 answers)
Closed 6 years ago.
I am trying to get an empty input if there is one in my div using jQuery. It is not working as it should.
There are 4 empty inputs in the div.
Here is my jquery:
var firstEmpty = $('#brochureItems').find('input:text:not(:checkbox,:button):visible:first:enabled[value= ""]').first().val();
console.log(firstEmpty);
That outputs 'undefined'.
When I remove the "[value=""]", I get '(an empty string)' outputted.
I just thought of something, I am adding those inputs in dynamically with jquery on page load. Would that have something to do with it?
If I understood you right you want to get all empty inputs inside a div. To do so, try this code:
HTML
<div>
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text" value="asdsad">
</div>
JS
var firstEmpty = $("div input[type='text']").filter(function() { return $(this).val() == ""; });
or if you want take all empty:
var emptyInputs = [];
$("div input[type='text']").each(function(){
if($(this).val() == '')
emptyInputs.push($(this))
});
Here is working Fiddle: https://jsfiddle.net/xs9jagc8/
Try this:
function findEmpty(){
var div=document.getElementById('theDivID');
for(var i=0;i<div.children.length;i++){
if(div.children[i].value==''){
return div.children[i].id;
}
}
return false;
}
function verify(){
var lol = findEmpty();
if(lol===false){
//Do whatever
alert("All filled!");
} else {
alert("The first empty input is: "+lol);
}
}
<div id='theDivID'>
<input id='blah' type='text'/>
<input id='bleh' type='text'/>
<input id='qwertyuiop' type='text'/>
<input type='text'/>
</div>
<input type='button' onclick='verify();' value='Check'/>

How to clear text field on focus of text field

I want to clear the text field when the user clicks on that
<input name="name" type="text" id="input1" size="30" maxlength="1000" value="Enter Postcode or Area" onfocus=="this.value=''" />
Unless you are doing something specific where you only want to clear onclick, I would suggest (as others have noted) to use the onfocus actions instead. This way if someone is using tab to navigate it will also clear the default text.
You can also use onblur to check if it's empty to bring it back:
<input type="text" value="Default text" name="yourName" onfocus="if(this.value == 'Default text') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Default text'; }">
To do this you will need to use a scripting language, probably javascript. Here an example
<input type='text' value'Some text' onclick='javascript: this.value = ""' />
Hope this helps.
Edit:
To meet what David is explain here is a second example in case that is what you are looking for
<script type='javascript'>
var clear = true;
function clear(obj)
{
if(clear)
{
obj.value = '';
clear = false;
}
}
</script>
<input type='text' value'Some text' onfocus='clear(this);' />
Using jQuery library:
<input id="clearme" value="Click me quick!" />
$('#clearme').focus(function() {
$(this).val('');
});
Or you can simply use the placeholder attribute
For example<input name="name" type="text" id="input1" size="30" maxlength="1000" placeholder="Enter Postcode or Area"/>
You can use <input ... onfocus="this.value='';"/>.
This way, the field will be cleared when it gains focus. However, if you only want to clear it when user clicks on it (i.e. not when the field gains focus with the keyboard for example), then use onclick instead of onfocus.
However, as pointed by David Dorward in a comment, this behavior may not be expected by the user. So be careful to set this feature on really specific fields (such as search field).
This is how I use it for a temperature converter/calculator - when the user types (keyup), the text input box calculates using the assigned function; when the user selects the other text input (there are only two inputs), the selected text input will clear.
HTML:
<p class="celcius"><h2 style="color:#FFF">Input:</h2>
<input name="celsius" type="text" class="feedback-input" placeholder="Temperature (Celsius)" onkeyup="Conversion()" onfocus="this.value='';" id="celsius" />
</p>
<hr>
<h2 style="color:#FFF">Result:</h2>
<p class="fahrenheit">
<input name="fahrenheit" type="text" class="feedback-input" id="fahrenheit" onkeyup="Conversion2()" onfocus="this.value='';"placeholder="Temperature (Fahrenheit)" />
</p>
JavaScript:
function Conversion() {
var tempCels = parseFloat(document.getElementById('celsius').value);
tempFarh =(tempCels)*(1.8)+(32);
document.getElementById('fahrenheit').value= tempFarh;
}
function Conversion2() {
var tempFarh = parseFloat(document.getElementById('fahrenheit').value);
tempCels =(tempFarh - 32)/(1.8);
document.getElementById('celsius').value= tempCels;
}
try this ,it worked for me
add this into your input tag
<code>
onfocus="this.value='';"</code>
for example if your code is
<code>
<input type="text" value="Name" /></code>
use it like this
<code><input onfocus="this.value='';" type="text" value="Name" /></code>
function Clear (x) {if (x.cleared) {} else {x.value = ""; x.cleared = true}}
onfocus = "Clear (this)"
Add a following script to your js file:
var input1 = document.getElementById("input1")
input1.onfocus = function() {
if(input1.value == "Enter Postcode or Area") {
input1.value = "";
}
};
input1.onblur = function() {
if(input1.value == "") {
input1.value = "Enter Postcode or Area";
}
};

retrieving text field value using javascript

I want to retrieve textfield value using javascript. suppose i have a code like:
<input type='text' name='txt'>
And I want to retrieve it using javascript. I call a function when a button is clicked:
<input type='button' onclick='retrieve(txt)'>
What coding will the retrieve function consist of?
You can do this:
Markup:
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="retrieve('txt');"/>
JavaScript:
function retrieve(id) {
var txtbox = document.getElementById(id);
var value = txtbox.value;
}
Let's say you have an input on your page with an id of input1, like this:
<input type="text" id="input1" />
You first need to get the element, and if you know the Id, you can use document.getElementById('input1'). Then, just call .value to get the value of the input box:
var value = document.getElementById('input1').value;
Update
Based on your markup, I would suggest specifying an id for your text box. Incase you don't have control over the markup, you can use document.getElementsByName, like so:
var value = document.getElementsByName('txt')[0].value;
One of the way is already explained by Andrew Hare.
You can also do it by entering the value in the textbox and getting a prompt box with entered message when a user click the button.
Let's say, you have a textbox and a input button
<input type="text" name="myText" size="20" />
<input type="button" value="Alert Text" onclick="retrieve()" />
The function for retrieve()
function retrieve()
{
var text = document.simpleForm.myText.value;
alert(text);
}

Categories