Input doesn't show its value in console - javascript

I have written this:
var $emailLogin = document.querySelector('#emailLogin')
var Email = ''
function emailLogin () {
Email = this.value
}
$emailLogin.addEventListener('input', emailLogin)
function myFunction() {
console.log(Email)
}
$loginBtn.addEventListener('click', MyFunction)
But console doesn't show input's value
It's empty like shown. I have no idea how to fix it

You should try and avoid global variables. The following will get you what you want without any "collateral damage" to the global name space:
document.querySelector('#button').addEventListener('click',function(ev){
console.log( document.querySelector('#emailLogin').value )
})
<input type="text" id="emailLogin"><button id="button">login</button>

In JavaScript, you could try this:
document.getElementById('ButtonID').addEventListener('click',function(){
console.log(document.getElementById('emailLogin').value);
});

Related

Assign cookie's value to the input field

I m trying to assign cookie's value to the input field.
code
Javascript
if ($.cookie("clientcookie")) {
var cookieval = $.cookie("clientcookie");
var inputs = document.getElementById("search");
inputs.value =cookieval;
}
HTML
<input id="search" type="search" placeholder="Search Text" class="input-medium search-query" >
But its not working its says:
Use of attributes' specified attribute is deprecated. It always returns true.
inputs.value =cookieval;
and
TypeError: inputs is null
I also tried
$('#search').val(cookieval);
But not working.
How to assign value to the input field
try{
$.cookie("clientcookie",'test'); //setting cookie in browser
if ($.cookie("clientcookie")) {
var cookieval = $.cookie("clientcookie");
var inputs = document.getElementById("search");
inputs.value =cookieval;
}
}catch(e){
alert(e);
}
very simple:
1. check cookie exist
2. if so then extract its value
3. fill text field's value.
check working example in jsfilddle.
I think if ($.cookie("clientcookie")) is not proper way to check the cookie.
Try this.
if ($.cookie("clientcookie") !== null) {
var cookieval = $.cookie("clientcookie");
var inputs = document.getElementById("search");
inputs.value =cookieval;
}
jsfiddle demo

Referencing a form assigned to a variable in jQUERY

I have a form with id='form1' as well as another one with 'form2'. On submit, i want to pass both forms as objects to a single validate function which can validate them. I am confused on how to do this.
If i do something like
var form = $('#form1');
Validate(form);
how do i access the text-fields of the variable form?
i don't want to write duplicate validate functions as both forms are ALMOSt similar.
You can do following also...
A Complete example is here...
function validate(formid){
var form = $("#"+formid);
var name = form.find("#name");
var number = form.find("#number");
alert(name.val());
alert(number.val());
}
validate("form1");
validate("form2");
Try .find. Your form will serve as the context and you could reuse it for different forms.
See below:
var form = $('#form1');
function Validate(form){
var field1 = form.find(".field1");
}
With the name of the fields, you can do this:
function Validate(form) {
form = form[0]; // raw element
if (check_syntax(form.name.value)) { doSomething(); }
if (check_syntax(form.email.value)) { doSomething(); }
if (check_syntax(form.anotherfield.value)) { doSomething(); }
}
If every field in the form has a name, you can access it via form.fieldName or form['fieldName'].
Regards.
Assuming both forms are similar:
ValidateForm($("#form1, #form2"));
function ValidateForm(forms){
forms.each(function(){
$(this).find('input[type=text]').each(function(){
//Do something to validate text field
})
$(this).find('input[type=checkbox]').each(function(){
//Do something to validate checkbox
})
})
}

javascript function inside function

I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!
This is what I came up with, but it doesn't do what I need:
function validateFirstName()
{
var x=document.forms["demo"]["firstname"].value;
if (x==null || x=="" || x==)
{
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
document.getElementById('firstname').value= ('Firstname must be filled out')
}
return false;
}
}
So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.
The HTML code looks something like this:
<div id="errors"></div>
<form onSubmit="return validate(this);">
<input type="text" name="firstName" placeholder="What's your first name?">
<button type="submit" value="submit">Submit</button>
</form>
The Javascript code looks something like this:
function validate(form) {
var errors ='';
if(form.firstName.value =="") {
errors += '<li>Please enter your first name</li>';
}
if(errors !='') { //Check if there are any errors, if there are, then continue
var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message"
message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML
return false;
} else {
return true;
}
}
Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.
I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:
var x = undefined; // Can be undefined, null, or empty string
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined
function addMessage(id, text) {
// Your validation code goes here
alert(id + text);
};
addMessage(1234, "Mandatory field!");
}
Note, there are several ways to do it. I just showing the simplest way I can think of...

Unable to create a variable in javascript

I am creating an app that will tell you the price of a product when the barcode is scanned. Basically, when a barcode is scanned, it goes into the text field, and then based on which barcode it is, the textarea will have a price put into it via javascript. I've gotten this to work, but I can't seem to create a certain variable to save me from looking through tons of code later on.
Here is my javascript:
function showPrice() {
var userInput = document.getElementById('barcode').value;
var price = document.getElementById('textarea').innerHTML;
if (userInput === "783466209834") {
price = "16.99";
} else {
price = "Not a valid barcode";
}
}
And here is my HTML:
<input type="text" name="text" class="textinput" id="barcode">
<input type="button" onclick="showPrice()" value="Submit">
<textarea name="" cols="" rows="" readonly="readonly" id="textarea"></textarea>
Right now, my code isn't working, but if I remove
var price = document.getElementById('textarea').innerHTML;
and replace "price" in the if statement respectively, then it works. I'm not sure why I can't create this price variable.
Because you're storing the value of the innerHTML as the variable, not storing a reference to it.
Change it to var textarea = document.getElementById('textarea'); and then textarea.innerHTML = "16.99" and so on.
If you want to work with the value of the textarea, you need to access document.getElementById('textarea').value, not innerHTML.
And, yes, as others have pointed out, you want to set the variable to reference to the element, not the value. Then you can retrieve or set the value of the element.
You are getting the innerHTML of the textarea and storing it in the variable price. Instead, you need to only store the element in the variable and then call price.innerHTML to place your result in the DOM. Like such:
function showPrice() {
var userInput = document.getElementById('barcode').value;
var price = document.getElementById('textarea');
if (userInput === "783466209834") {
price.innerHTML = "16.99";
} else {
price.innerHTML = "Not a valid barcode";
}
}
EDIT: As talemyn correctly points out, you should use .value rather than .innerHTML for altering the contents of textareas. While it might look like it does the same thing, there are slight disadvantages that come with the use of .innerHTML.
You should not assign a value to price and then overwrite it... That's what your code is doing. I believe you think you are creating a storage location in the innerHTML?
Instead, just create the variable:
var price;
Run your code as you did; and then put the result into the page with
document.getElementById("text area").innerHTML = price;
You're setting the 'price' variable twice with two separate things. You're not actually changing the DOM. Instead use:
var price = document.getElementById('textarea');
if (userInput === "783466209834") {
price.innerHTML = "16.99";
} else {
price.innerHTML = "Not a valid barcode";
}

Reset textbox value in javascript

If I have a input textbox like this:
<input type="text" id="searchField" name="searchField" />
How can I set the value of the textfield using javascript or jQuery?
You would think this was simple but I've tried the following:
Using defaultvalue
var a = document.getElementById("searchField");
a.value = a.defaultValue;
Using jQuery
jQuery("#searchField").focus( function()
{
$(this).val("");
} );
Using js
document.getElementById("searchField").value = "";
None of them are doing it... :/
In Javascript :
document.getElementById('searchField').value = '';
In jQuery :
$('#searchField').val('');
That should do it
With jQuery, I've found that sometimes using val to clear the value of a textbox has no effect, in those situations I've found that using attr does the job
$('#searchField').attr("value", "");
Use it like this:
$("#searchField").focus(function() {
$(this).val("");
});
It has to work. Otherwise it probably never gets focused.
To set value
$('#searchField').val('your_value');
to retrieve value
$('#searchField').val();
I know this is an old post, but this may help clarify:
$('#searchField')
.val('')// [property value] e.g. what is visible / will be submitted
.attr('value', '');// [attribute value] e.g. <input value="preset" ...
Changing [attribute value] has no effect if there is a [property value].
(user || js altered input)
Try using this:
$('#searchField').val('');
First, select the element. You can usually use the ID like this:
$("#searchField"); // select element by using "#someid"
Then, to set the value, use .val("something") as in:
$("#searchField").val("something"); // set the value
Note that you should only run this code when the element is available. The usual way to do this is:
$(document).ready(function() { // execute when everything is loaded
$("#searchField").val("something"); // set the value
});
This worked for me:
$("#searchField").focus(function()
{
this.value = '';
});
this is might be a possible solution
void 0 != document.getElementById("ad") && (document.getElementById("ad").onclick =function(){
var a = $("#client_id").val();
var b = $("#contact").val();
var c = $("#message").val();
var Qdata = { client_id: a, contact:b, message:c }
var respo='';
$("#message").html('');
return $.ajax({
url: applicationPath ,
type: "POST",
data: Qdata,
success: function(e) {
$("#mcg").html("msg send successfully");
}
})
});

Categories