Getting value of input and passing along through querystring - javascript

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;

Related

Force one way binding while assigning variable to another variable

I'm trying to assign a variable to another variable and try to do only one way binding. But when value is updated in view, it updates to original variable too. How do I stop this two way binding while assigning variable to another.
For example:
function personController ($scope) {
var templateValue= "original value";
$scope.myVal= templateValue;
}
In view:
<input type="text" ng-model="myVal" />
Result:
When we type something in textbox, it updates value in myVal and templateValue too, i.e value in templateValue changes to whatever I just typed in the input box. Is there a way to assign variable to another variable doing only one way binding? I want two way binding between $scope.myVal and the input box but not between templateValue and input box.
You can't "force one-way binding" because of the weay JavaScript works.
In your example, updating myVal will not actually update templateValue.
function personController($scope) {
var templateValue = "original value";
$scope.myVal = templateValue;
}
If you have the following structure, then yes, changing myVal.test will update templateValue.test because they both reference the same object in memory.
function personController($scope) {
var templateValue = { test: "original value" };
$scope.myVal = templateValue;
}
if you want myVal and templateValue to reference different objects but have the same content, make a copy of the original object:
$scope.myVal = angular.copy(templateValue);
I also suggest familiarising yourself with Javascript by reference vs. by value.

Reference to the value of input field

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

How do I pass an input value to a method in Javascript?

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>

Javascript: Passing variable to function breaks function

I am using an onsubmit variable to ensure that the user really means to delete something, however as soon as I put a value in the parenthesis inside the onsubmit it no longer calls the confirm box.
Code:
onClick="confirmSubmit(abc)"
Doesn't work but the following:
onClick="confirmSubmit()"
Does work
Function:
function confirmSubmit(category)
{
var category = category;
var agree=confirm("Are you sure you wish to DELETE" + category + " and all of its subcategories and photos?");
if (agree)
return true ;
else
return false ;
}
you need quotes around your abc:
onclick="confirmSubmit('abc')"
Without them you are trying to pass a variable, abc, which doesn't exist and triggers an error
onClick="confirmSubmit(abc)" is trying to pass the variable abc, if you intend to pass a string with the value "abc" then do this:
onClick="confirmSubmit('abc')"
function confirmSubmit(category)
{ var category = category;
And you've declared "category" twice! Once in the function header and then as a function variable in the next line! What for?
You're try to pass the variable abc (which does not exist) to the function.
Do:
onclick="return confirmSubmit('abc');"

js call form value to variable

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.

Categories