Get object sent to function with this.value - javascript

Is there a way to get the object itself when a function receives a value from it?
Example:
<input id="field1" onblur="testFunction(this.value)" />
<input id="field2" onblur="testFunction(this.value)" />
<script>
function testFunction(x){
field_value_length = x.length;
field_object = ????;
}
</script>
When I blur the field, I apply it's length to "field_value_length" in testFunction(). Ok!
Is there a way to get the object itself (the input) where data in "x" came from, so I can get other properties from the form field that has sent data value to the function, like the "id" etc. just like it was sending testFunction(this) instead testFunction(this.value)?

What is sent to the function is the value from the input... Only.
But nothing prevents you from sending the input element, using just this.
<input id="field1" onblur="testFunction(this)" />
<input id="field2" onblur="testFunction(this)" />
<script>
function testFunction(x){
field_value_length = x.value.length;
field_id = x.id;
}
</script>

Related

Cannot pass input value to another input value via javascript

I wanted to pass the value of input field to another input field with its value via javascript. I wrote code as shown below.
First input:
<input type="text" class="form-control" id="recipient" name="recipientName" value="RecipientName" onkeyup="recipient()"/>
Second input:
<input type="hidden" id="recipientHidden" name="recipientName"/>
Js Code
function recipient(){
var recipientNameValue = document.getElementById('recipient').value;
document.getElementById('recipientHidden').value = recipientNameValue;
console.log(document.getElementById('recipientHidden').value);
}
When I open console, there is no value in the console. When I click on the first input field, value is printed.
How can I get it instantly ?
Your code works fine, but it will only log the value on key up. You can log the value immediately by calling the recipient() function right away:
function recipient() {
var recipientNameValue = document.getElementById('recipient').value;
document.getElementById('recipientHidden').value = recipientNameValue;
console.log(document.getElementById('recipientHidden').value);
}
// Call function straight away
recipient()
<input type="text" class="form-control" id="recipient" name="recipientName" value="RecipientName" onkeyup="recipient()" />
<input type="hidden" id="recipientHidden" name="recipientName" />

no able to get the value of textbox

<form id="myRegisterationForm">
<label>Name</label>
<input type="text" id="nameTextbox" />
<input type="submit" value="Submit" />
</form>
And the js is
var myform = document.getElementById('myRegisterationForm');
var name = document.getElementById('nameTextbox');
function onSubmit(e) {
console.log(name.value);
e.preventDefault();
}
myform.addEventListener('submit', onSubmit, false);
But somehow the value shows undefined for the text inside name textbox.... even when i enter something and press submit..why?
var r = document.getElementById('nameTextbox').value;
//added .value
Use this to store the value of the text box in variable r.I have renamed the variable to r.
The value property sets or returns the value of the value attribute of a text field.
document.getElementById("nameTextbox").value;
The getElementById method needs a pair of round brackets. In between these round brackets you type the ID you're trying to access. The ID needs to be surrounded by quote marks, single or double. Textboxes have a VALUE attribute. You can get at this value by adding it after the round brackets
var myform = document.getElementById('myRegisterationForm');
function onSubmit(e) {
var name = document.getElementById('nameTextbox');
alert(name.value);
e.preventDefault();
}
myform.addEventListener('submit', onSubmit, false);
<form id="myRegisterationForm">
<label>Name</label>
<input type="text" id="nameTextbox" />
<input type="submit" value="Submit" />
</form>

JS rescue text form

I'm using this to rescue the text in the form in case the user goes to another page without submitting. But how can I clear the form when the user presses the submit button?
function rescuefieldvalues(idarray){
for (var i=0; i<idarray.length; i++){
var el=document.getElementById(idarray[i])
if (!/(text)/.test(el.type)) //skip to next element if it isn't a input type="text" or textarea element
continue
if (el.addBehavior && !window.sessionStorage){ //use IE behaviors to store info?
el.style.behavior='url(#default#userData)'
el.load("userentereddata")
}
var persisteddata=(window.sessionStorage)? sessionStorage[idarray[i]+'data'] : (el.addBehavior)? el.getAttribute('dataattr') : null
if (persisteddata) //if rescued data found for this element
el.value=persisteddata
el.onkeyup=function(){
if (window.sessionStorage)
sessionStorage[this.id+'data']=this.value
else if (this.addBehavior){
this.setAttribute("dataattr", this.value)
this.save("userentereddata")
}
} //onkeyup
} //for loop
}
<form>
<p>Name: <input type="text"/></p>
<p>Address*: <input type="text" id="address" style="width:200px;" /></p>
<p>Feedback*:<br />
<textarea id="feedback" style="width:300px;height:150px">Your feedback here</textarea><br
/>
<input type="submit" /></p>
</form>
<script type="text/javascript">
rescuefieldvalues(['address', 'feedback']) //rescue data
</script>
You are setting your key/value pairs with:
sessionStorage[this.id+'data']=this.value
(just a note here, I would prefer the syntax: sessionStorage.setItem(key, value)).
Similarly, you should iterate over the keys that you've stored and clear them with:
sessionStorage.removeItem(key)
If you don't have the keys that you want to clear, you might iterate over sessionStorage properties as if it was a regular object.
You can also clear all your sessionStorage with sessionStorage.clear().
Of course you have to create a function that does this and bind it to the submit event of your form.

Turn HTML Form Input into JavaScript Variable

I am new to HTML forms and I was wondering how I can easily (or not) change it's input to a JavaScript variable. Here is my code:
<head>
<title>Begin</title>
<link type="text/css" rel="stylesheet" href="begin.css"/>
</head>
<body>
<form action="begin-create-done.html" method="get">
First Name: <input type="text" name="firstname">
<br>
Last Name: <input type="text" name="lastname">
<br>
<br>
New Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pass">
<br>
Repeat Password: <input type="password" name="rpass">
<input type="submit" value="Submit">
</form>
</body>
</html>
I want each part of the form (e.x. First Name, Last Name, New Username, etc.) to be it's own JavaScript variable. Thank you very much!
Accessing HTML input elements from JavaScript
Assuming you don't have other elements with same names, you can access input values from JavaScript by name as follows:
var firstName = document.getElementsByName("firstname")[0].value;
You now have the value from firstname field in JavaScript variable called firstName. Just keep repeating and you got the other input fields too. You can then proceed and wrap these statements to a function and call it when input data changes. For example:
function formChanged() {
var firstName = ...
var lastName = ...
}
Now register this function call to change / keyup events and you have a function that monitors changing form values:
<input type="text" name="firstname" onkeyup="formChanged()" onchange="formChanged()"/>
Should you prefer a more structured approach, or if you have more than one form on the page, you could:
Create an object that will hold all form values and update them. After that you could simply access them with formValues.inputName.
Store your default values in an array (in the same order as your inputs).
Execute a function that will take care of outputting the default values & updating the object when the values are changed. It takes the form (selected by Id, Class, whatever) and an array of default values as parameters.
// create the object that will hold the input values
var formValues = {};
// store code in the function for a more 'modular' approach
function inputObj(formNR, defaultValues) { // where defaultValues is an array
var inputs = formNR.getElementsByTagName('input');
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].type === 'text' || inputs[i].type === 'password') {
formValues[inputs[i].name] = defaultValues[i]; // store default in object
}
inputs[i].value = defaultValues[i]; // output default in input
inputs[i].addEventListener('keyup', function() { // update object on change
formValues[this.name] = this.value;
}, false);
}
}
// build a little array with the defaultValues for each input
var defValues =['defaultFirstName','defaultLastName','defaultUser',
'defaultPass','defaultPass'];
// this will push all inputs from the given form in the formValues object.
inputObj(document.forms[0], defValues);
// Access the values like this, eg.
console.log(formValues.firstname); // will return 'defaultFirstName'
See it in action here. Or with CodeView. Note: The code in the example has some additions to show the object's values on the page.
Try to first create a function that grabs the value from the input field:
<script>
function XX()
{
var first2 = document.getElementById("firstname").value;
}
</script>
Then you have to fire it up when the input changes with onchange:
FirstName: <input type="text" id="firstname" name="firstname" onchange="XX()">

How do I pass Bootstrap-tags input as an array to a form?

I need to pass an array to a form based on what is returned from bootstrap-tags input. I have followed the documentation to try and retrieve the array using the following code:
<form>
<input type="text" name = "language" value="Javascript,Ruby" id = "languages" data-role="tagsinput" />
<input type='hidden' name='languages_hidden[]' id = "languages_hidden" value='' />
<input name="save" onclick="mySubmit()" type="submit" value="Save">
</form>
<script>
function mySubmit() {
document.getElementById('skills_hidden').value = $("#skills").tagsinput('items')
}
</script>
I expect the resulting array that is passed on to be in the format when I click the submit button:
["Javascript", "Ruby"]
However, I see that that is actually how the array is passed on:
["Javascript, Ruby"]
How do i rectify this?
Change the function to the following. Also added a fall back just in case.
function mySubmit() {
document.getElementById('skills_hidden').value = ($("#skills").tagsinput('items') || [''])[0].split(', ');
}
Edit: Updated function to reflect returning of an array.

Categories