Ok noobablicious question. But has had me sumped.
Im declaring the value of a hidden form field with a Js script with in a function.
e.g. These are just examples not the real script.
function myFunction(){
var text = "hello world";
var number = 12345;
document.getElementById('text').value= text;
document.getElementById('number').value= number;
}
Then I want to be able to use the value of the form value as a variable in another script. I realize that there is the option to declare these variables globally. However I have heard that it is not as secure. Or a streamlined as I am going for.
Second Script example...
var autoText = document.getElementById('text').value;
var autoNumber = document.getElementById('number').value;
...do stuff with variables.
However this is not working and returns undefined. Is this the correct DOM path to access the value of my form fields or do I need to find an attribute and its child??
What other options are available to me??
Thanks for your time. HTML is...
<form action="http://mysite/mypath" method="post">
<input type="text" name="text" id="text" value="">
<input type="text" name="text" id="number" value="">
<input type= "submit" name="go" value="go" allign="middle"/>
</form>
That should be fine, assuming that you have the correct ID's set to the elements you want. Remember, that ID's are required to be unique, or unpredictable issues will arise.
Make sure that you are running your code, after the DOM is loaded. Otherwise the element might not yet exist in the DOM, and so the document.getElementById method will fail to find it..
Or, you could just store that data in a closure so that both functions have access to the variable, but it's not stored in the global scope. Like so:
(function(){
var text = "blah blah",
number = 12345;
function insertValues() {
document.getElementById('text').value= text;
document.getElementById('number').value= number;
}
function otherStuffWithValues() {
alert(text);
alert(number);
}
insertValues();
otherStuffWithValues();
}())
Additionally, You could also declare the variables inside the first function, and then pass the variables onto the second function as a parameter like so:
function insertValues() {
var text = "blah blah",
number = 12345;
document.getElementById('text').value= text;
document.getElementById('number').value= number;
otherstuff(text,number)
}
function otherstuff(sometext,somenumber) {
alert(sometext);
alert(somenumber);
}
insertValues()
I think that you haven't set starting script when page load. If so, you can use this simple event handler:
window.onload = myFunction;
With myFunction will be function with yours above code.
Related
I know it's a silly question but I am a bit confused with this. For example, if I have an input with an ID: rad1, is there any difference between below lines of code?
var $a = $('#rad1')
or
var a = $('#rad1')
No there is no real difference.
It's just a convention that helps you remember that a isn't the DOM element but it's a jQuery object.
var a = document.getElementById('a');
a.innerHTML //fine
var $a = $('#a');
$a.html() // fine
Ohhh, and by the way, neither a or $a are good variable names ... you should use meaningful variable names not abc characters.
Read the jQuery info tag on this very same site:
Variable Naming Conventions
jQuery wrapped variables are usually named starting with '$' to distinguish them from standard JavaScript objects.
var $this = $(this);
It's only for showing that it's a Jquery variable.
Declaring $a you're showing that your variable is for JQuery objects, it's just a notation. So the most readable thing will be to declare Jquery variable with $ notation
var $obj=$("#obj");
And DOM element without $ notation
var obj = document.getElementById("obj");
There's no difference. It's just a coding convention to help identify that the variable represents a jquery wrapped object.
No difference its just coding convention , check this
I think this scenario should illustrate the reason for remembering(off course, assigning '$' ) jquery and simple javascript variables:
<form id='myform' >
<input id="name" type="text" value="Peter" />
</form>
<script>
$(document).ready(function(){
var name = document.getElementById('name');
var $name = $('#name');
console.log(name.value); // javascript's properties are available
console.log($name.value); //it is undefined (worth of notice)
console.log(name.val()); // error! name.val is not a function ! (jquery function will not be available)
console.log($name.val()); // jquery functions are available
});
</script>
A composition also works fine:
You can also do something like this to show a <div>:
function getCompTable(divId){
var $d = $('#' + divId);
$d.show();
}
USAGE
getCompTable('compListDiv'); // compListDiv - is a div id=""
Yosi Lev
I have created a function named “show_alphabet” and assign to a variable named “str”, a string of the letters of the alphabet in uppercase.
I have used the prototype property of the String object to add a method named “sendArray” and assign this (sendArray) a function which returns the split() method. The split() method will split the alphabet string.
I also have a variable named “arr” and I have assigned it the sendArray() method for “str”.
I have a button that when clicked will run the show_alphabet function.
The function is supposed to display the alphabet letters in the “str” as an array with period colon followed by each letter and placing each letter on a separate line.
For example:
A:
B:
C:
…
However, whenever I click on the button, nothing is displayed.
Here is my code:
<form>
<button type = "submit" value = "submit" onclick = "show_alphabet()">submit </button>
</form>
<script type="text/javascript">
function show_alphabet() {
var str = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
String.prototype.sendArray() = function() {
return this.split("");
}
for (i=0; i<str.length-1; i++) {
var arr = str.sendArray(":" + "<br />");
document.write(arr[i]);
}
}
</script>
I couldn't stand these horrible answers, so I felt compelled to offer a correct one.
<button type="button" value="submit" onclick="show_alphabet()">submit</button>
<div id="dynamic"></div>
<script type="text/javascript">
function show_alphabet() {
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.querySelector('#dynamic').innerHtml = str.split('').join(':<br/>');
}
</script>
To recap some of the issues:
You can't document.write after the DOM has loaded. Doing so will generally only cause you frustration. Instead, as above, tweak the innerHtml or use a dozen other ways to change the DOM.
Set the button as type="button" instead of type="submit". Doing so will preclude either an actual form, or an implied one, from executing.
Your sendArray function didn't make any sense... but neither did most of the answers. Just make the string and set it somewhere, and iteration just isn't necessary here.
Ok I didn't expect to see so many incomplete answers. So let's summarize
The definition of the sendArray prototype function must not have parentheses
Above all, you don't need any sendArray prototype function (unless it is explicitly required by the Homework exercise)
You are passing a parameter to sendArray which you don't use inside the function
The action submit on the button will submit the form and hence refresh the page, so you won't see any other results of your code
You'll have to understand that pushing the button will use document.write, which will (after DOM loaded) always erase the previous document, including your script
Try it like this
<button type="button" onclick="show_alphabet()">Show alphabet</button>
<div id="output"></div>
<script type="text/javascript">
function show_alphabet() {
var str = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
var arr = str.split("");
document.getElementById("output").innerHTML = arr.join(":<br/>");
}
</script>
sendArray = function() instead of sendArray() = function()
I'm attempting to get the value of text typed by a user in an input box but the problem is that instead of getting the value which the user has typed, I get the preset value of the input which is 'undefined'.
HTML
<input type="text" id="userInput" value="" name="title"
placeholder="Enter the name here" required="required"/>
<input type="button" id="text_value" value="Set Input"/>
<!-- I have this button here because I think maybe
I should have a button to change default value but
I don't know the javascript to do this -->
Javascript
// Gets input value id
var theuserInput = $("#userInput").val();
The reason I haven't shown query string code is because the input value is passed along in the url but the problem is that the default input value 'undefined' is passed instead of actual user input.
Any solutions?
ADDITIONAL CODE
Ok so here is the querystring, when you click the 'pass' button the input is passed along in querystring:
$('.pass').click(function() {
window.location.href = 'http://lala.com/passing.php?input=' + theuserInput + '';
return false;
});
Try this instead:
$('.pass').click(function() {
var theuserInput = $("#userInput").val();
window.location.href = 'http://lala.com/passing.php?input=' + theuserInput + '';
return false;
});
The this is removed before the call to the val() method.
The reason why you get undefined is because theuserInput is not defined inside the anonymous function scope passed to #click method. The JS engine tries to find theuserInput inside the "englobing" scopes recursively until reaching the global scope or finding theuserInput value in one of the successive "englobing" scopes. Since, the variable theuserInput can't be found in any scope, it is affected the default value undefined.
DEMO 1
DEMO 2
var theuserInput = document.getElementById("userInput").value;
Consider the following code snippet:
inputTextField=document.getElementById("Phone_input");
var value = inputTextField.value;
value=value.substring(0,10);
where Phone_input is an <input type="text"/> element. Why during the running of this script there is no changes of actual value of the <input type="text"/>. We're changing value by the reference which indicates to inputTextField.value.
The variable value is not a reference, so after the change you must write it back into the textfield:
value=value.substring(0,10);
inputTextField.value = value;
Or, in one line:
inputTextField.value = inputTextField.value.substring(0,10);
Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.
In this case you have to do it this way:
var inputTextField=document.getElementById("Phone_input");
inputTextField.value = inputTextField.value.substring(0,10);
I'm beginning to learn OOP in Javascript and my instructor is not very good and I'm learning out of a very bad book. (http://www.amazon.com/JavaScript-The-Web-Technologies-Series/dp/0538748877/ref=cm_cr_pr_product_top) However I'm doing my best to use this site and any resource possible to follow along. That said! We're going over OOP and I'm trying to make a simple object oriented form validator but I'm having a problem with passing the input value to the method inside of the object. I apologize if I got the phrasing wrong. Here's my code.
function validate() {
this.isEmpty = function(value) {
if(value == "" || value.length < 1 || value == null) {
// testing alert
alert(value);
return false;
}
}
}
And my HTML
<form action="" method="get">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<input type="submit" value="submit" id="submit">
</form>
Basically what I don't get is how I can pass the input value of the field "name" to the object? And my follow up to that would be how do I pass multiple inputs? For example if I wanted to check if "name" and another field named "email" were empty?
Can anyone shed some light on how I would go about doing this in regular JS? Am I even attempting this in the right way? I have no idea since this is my first time trying anything object oriented.
Well first it's important to know which concepts you are trying to model when doing OO. You were speaking about a "validator" concept, but perhaps it's still not specific enough. What exactly are you validating? Think about it, a "Validator" object suggests that it's actually quite flexible and is an object that could be helpful to validate many disparate models. If this isin't what you have in mind, then be more specific. For instance, you could name your class MyFormValidator (it's just an example).
Here's a very simple example of a specific validator class that takes a form as an argument and implements a public validate method to trigger validation on demand. The example is very simple and not quite flexible. There's a lot of space for improvements, such as removing UI concerns (like the messages), from the validator, but I did not want to make the example too complex.
*Note: _members identifies private members. You can enforce true privacy with the module pattern and/or priviledged functions, but I prefer naming conventions.*
function MyFormValidator(form) {
this.form = form;
this._errors = [];
}
MyFormValidator.prototype = {
constructor: MyFormValidator,
validate: function () {
var errors = this._errors,
name = this._valueOf('name');
//clear previous errors
errors.length = 0;
if (this._isEmpty(name)) {
errors.push('The name is mandatory');
}
return !errors.length;
},
errors: function () { return this._errors.slice() },
_valueOf: function (fieldName) {
return this.form.querySelector('[name="' + fieldName + '"]').value;
},
_isEmpty: function (value) {
return value == "" || value.length < 1 || value == null;
}
};
//Setting up form validation
var form = document.querySelector('form'),
validator = new MyFormValidator(form);
form.addEventListener('submit', function (e) {
if (!validator.validate()) {
e.preventDefault(); //prevent submit
alert(validator.errors());
}
});
DEMO: http://jsfiddle.net/Q2d5c/
When a JavaScript function is invoked inline, "this" points to the containing DOM element.
So if you want to validate the following tag:
<input name="test" onblur="validate();">
Then your validate function can grab its container's value:
function validate(){
alert(this.value); //the value of input field "test"
//to get the name of this input:
alert(this.name);
}
Personally I don't code like this because the code is sensitive to its context. Instead I use this style:
<input name="test" onblur="validate(this);">
function validate(d){
alert(d.value); //value
alert(d.name); //name
}
As you can see, the object is explicitly passed in, and you can see that on the call stack, "this" is placed in the tag directly. Later if you want to use the same function from another location, you can, by manually getting the object, and pass it in:
<input name="test" id="test">
<button onclick="validate(document.getElementById('test'));">Validate</button>
Unless it's an inline callback (closure) function, I avoid using the ambiguous "this" pointer to increase code readability.
I do not recommend to use a framework when learning javascript. After you learn javascript itself, then you should dive into frameworks, not now. So i will not tell anything about vanilla yet.
You can get values of inputs in several ways. The best is to get their value by id:
var name = document.getElementById("name").value
So there you have it, the value of the input assigned to name variable.
After that you can pass that variable to validate function and see the results.
You would also want to catch the form's submit event and do the validation before the form gets submitted. To do so:
var form = document.getElementsByID('form'); //you should assign id 'form' to the form element
form.addEventListener("submit", function(e) {
e.preventDefault(); //do not submit the form
var name = document.getElementById("name").value
validate(name);
});
It is simply done like that:
<script type="text/javascript">
function MsgAlert()
{
var value = document.getElementById('abc').value;
alert(value);
}
</script>
<input id="abc"></input>
<button onClick="MsgAlert();">PassValue</button>