Set Default Value for hidden field - javascript

I have a hidden field where i save a value when button is clicked. But on page load there is no value assigned to it. I need to know how to set default value of hidden field.
I am saving a string in hidden field when button is clicked and then access it in a JS function. But on page load the JS function return Undefined value error as the value of hidden field is not set on page load.
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom != "")
{
// logic here
}
}

You can simply try with this
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom) {
// logic here
}
}
So if(nom) will return true only when it has non-blank value. It'll return false if it is "" or undefined
Now the next thing, you need to make sure about the Id of the element. If you are using the asp.net hidden field with runat="server" then Id would be different than what are you expecting. So to make sure that Id remains same as you've given in asp.net markup, use ClientIdMode="Static"

you can also do this:
if (nom != "" || nom != undefined) {
//Your Logic
}

try to use this
if (nom !== "" && nom !== undefined)
so, your code should be rewritten as below
function Confirm() {
var nom = document.getElementById('hdNomValue').Value;
if (nom !== "" && nom !== undefined)
{
// logic here
}
}

Here for only text,password fields in html only you can give a default value attribute .But in the case of html
<input type="hidden" value="">
element the value would not be assigned by default.
If you want to use a hidden field with a default value use a text field with the property of display:none like
<input type="text" style="display:none" value="Default">
Or else if you are determined to use the hidden element only then you can go for a javascript based check solution like
var nom = document.getElementById('hdNomValue').Value;
if (nom != "" || nom != undefined)
{
}

what are you using jquery or javascript, if u are using jquery you may try to use
var nom = $('#hdNomValue').val();

Related

How to get update all hidden fields with same name?

I have multiple hidden field with same name on html page like below
<input type="hidden" name="customerID" value="aa190809" />
I need to update values of all hidden field with same name i.e. customerID
I know how to do it(through Jquery) if html page contains single hidden field with customerID like below but not sure if there are multiple hidden field with same name
if(updatedCsrf !== null) {
var customerIDHidden = $("input[name='customerID']");
if(customerIDHidden !== null) {
customerID.val("some_value");
}
}
You can do something like this:
$("input[name=customerID]").each(function(){
this.value ="new value"
})
this will reference each DOM element. You can parse it again to jQuery DOM element by replacing this.value to $(this).val("new value") but since you only need to change the value its better with javascript vanilla
You can do that with pure JS,
var x = document.getElementsByName("customerID");
for(var i=0; i < x.length;i++){
x[i].value='new value';
}
Use jQuery each function
$("input[name='customerID']").each(function(){
$(this).val("some-value");
});

how do i make js dectect whats typed in a input box

I'm trying to make js detect whats in a input box, and if the user typed in a code, something will happen so far I got this
function input() {
document.getElementById('hehe').value
if (value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
<input id="hehe" type="text" oninput="input()">
but it's not working for some reason and I can't see why
you have to save the value before you can use it. document.getElementById('hehe').value RETURNS the value of the input textfield but in the next line you're using the non existing variable value.
just change it to:
function input() {
var value = document.getElementById('hehe').value
if (value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
or use it directly:
function input() {
if (document.getElementById('hehe').value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
You are not assigning the DOM element value to a variable. You should write:
var value = document.getElementById('hehe').value;
Or, using jQuery:
var value = $('#hehe').val();
However, another automated way to detect entered text, using KnockoutJS library, is data-bind. It automatically synchronizes the DOM element with your Model after applying the binding to your ModelView.
Here is an example: (jsfiddle)
HTML:
<p>Name: <input data-bind="textInput: name"></p>
<h1>The typed name is: <span data-bind="text: name"></span>.</h1>
JavaScript:
ko.applyBindings({
name: ko.observable("SOMETHING")
});
Use onkeypress instead of oninput.
http://jsfiddle.net/VDd6C/8/

What is the value of an empty text input box?

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

javascript if("" != "") not working

HTML & PHP
<?for($i=1;$i<=10;$i++){?>
<input type='textbox' style="width:100%" name='name[]' id = 'name<?echo $i;?>'>
<?}?>
Javascript
for(var i=1;i<="?";i++){
if(document.getElementById('name'+i).value != "") {
alert("text_if");
}else{
alert("text_else");
}
}
In the textbox don't have value (mean "") so "" != ""
return false alert text_if but it's not working don't alert all.
i try "" == "" it's working why != not working please help me
Okay it's working now
but i have loop but i don't know max of element
because i have function add&del textbox (create element)
It works:
http://jsfiddle.net/uyz6fozt/
I just needed to add a closing bracket }.
Change
<input type='textbox' style="width:100%" name='name[]' id = 'name' value="ENTERSOMETHINGHEREORREMOVEIT">
to
<input type='textbox' style="width:100%" name='name[]' id = 'name' value="">
and press RUN to see it working.
It's false because the empty strings are equal.
"" != "" translates to "an empty string is not equal to an empty string" which is false because they are indeed equal.
if(document.getElementById('name').value != "") {
alert("text_if");
}else{
alert("text_else");
}
<input type='textbox' style="width:100%" name='name[]' id = 'name'>
Notice how the else statement runs here. If it is not running for you, it means you may have placed your javascript in a location where it runs before the DOM is loaded.
Also make sure you are calling this after the element has loaded - so ensure you wrap it in a function that is only called after the page has fully loaded - or alternatively have the script after the closing body tag (page runs more efficiently this way)
JavaScript can only call elements with IDs that exist in the DOM :)

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

Categories

Resources