Please accept my apologies for asking which might seem obvious to everyone besides me ...
Is it normal that in the following snippet:
let form;
form = document.getElementById('thing1');
console.log(form.id, typeof form.id);
form = document.getElementById('thing2');
console.log(form.id, typeof form.id);
<form id="thing1">
<input name="id">
<input name="thing1">
</form>
<form id="thing2">
<input name="identifier">
<input name="thing2">
</form>
which yields the following console log:
<input name="id"> 'object'
thing2 string
the form's child input (which has a name identical to an existing global attribute of the parent) overwrite's the form's attribute?
I'm using the inputs' names to relate to an external database field names ... and of course 'id' is a very common column name there ....
You cannot rely on Element.id all the time, you can try Element.getAttribute("id"):
<form id="thing1">
<input name="id">
<input name="thing1">
</form>
<form id="thing2">
<input name="identifier">
<input name="thing2">
</form>
<script>
let form;
form = document.getElementById('thing1');
let temp;
temp = form.getAttribute('id');
console.log(temp, typeof temp);
form = document.getElementById('thing2');
temp = form.getAttribute('id');
console.log(temp, typeof temp);
</script>
Elements inside form are appended to its DOM object as properties, with their names as key.
You can alternatively access them like this:
form = document.getElementById('thing1');
input = form.querySelector('[name="id"]')
Related
I am looking to add data to a form object which is an array.
This works fine:
<input type="text" name="object" value="">
<script>document.form.object.value = "value";</script>
But when the object is an array it's not working:
<input type="text" name="object[]" value="">
<script>document.form.object[0].value = "value";</script>
The value of the object is not changing.... Any idea?
I would like to loop the script so I need to create an array. Didn't find any solution...
Per example, I would utilize document.form.elements['object[]'].value = "value". Otherwise, if you intended on having multiple form elements with the same name (multiple inputs with object[], and iterate via the collection, can use the following:
var myForm = document.form;
var myControls = myForm.elements['object[]'];
for (var i = 0; i < myControls.length; i++) {
var aControl = myControls[i];
}
The example provided, in your code, the name provided is not perceived as an array.
The attribute value "object[]" is just a string to JavaScript -- it does not interpret that as an array. However, when brackets appear in a name, you cannot use it any more in the dot-notation, but must write:
document.form["object[]"].value = "value";
<form name="form">
<input type="text" name="object[]" value="">
</form>
If you have more than one element with name="object[]", then the above will only target the first one of these. To set the value of all those elements, you must loop. This you can (for instance) do with the elements property and Array.from to iterate over those elements:
Array.from(document.form.elements["object[]"], function(elem) {
elem.value = "value";
});
<form name="form">
<input type="text" name="object[]" value="">
<input type="text" name="object[]" value="">
</form>
For those using IE: replace Array.from with [].map.call
I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>
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()">
I am trying to implement html input array.
<input type="text" name="firstName[]" id="firstName[]">
And i need to set value of another form which looks something like
<form id="tempForm">
<input type="text" name="userName" id="userName">
<input type="text" name="userId" id="userId">
</form>
into the input array using jquery on form submit.
For that i tried following on form submit,
var currentIndex=$("input[name^=firstName]").length;
$("#firstName").eq(currentIndex).val($("#userName").val());
But it doesn't works,obviously.
Question:
How to set value of input array using jquery?
Use the jquery append function for add inputs with different attribute value :
Check it :
$(document).ready(function(){
var a = ["username","userid"];
var b = ["username","userid"];
for( var i = ; i <3 ; i++){
$('#tempForm').append('<input type="text" name="'+a[i]+'" id="'+b[i]+'" />);
}
});
Then continue your other work:
replace this code with your js code :
var currentIndex=$("input[name^=firstName]").length;
$("#firstName").eq(currentIndex).val($("#"+userName).val());
Consider the following form:
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" id="file"/>
<input type="hidden" id="hidden"/>
<input type="image" id="image" />
<input type="password" id="password" />
<input type="radio" id="radio" />
<input type="reset" id="reset" />
</form>
Utilizing Javascript (and jQuery), what would be the easiest way to clone the entire form and increment each individual id within, to ensure uniqueness.
Using jQuery I would assume you would clone the form initially via clone() and iterate through the cloned objects id and add the new id fieldname1, fieldname2 etc. However, my knowledge of jQuery isn't too great and this project is almost killing me.
Any help would be great!
You would clone() it, and before attaching the cloned element to the DOM, you'd run through and add the number to each id attribute.
(function() {
var count = 0;
window.duplicateForm = function()
var source = $('form:first'),
clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
return val + count;
});
clone.appendTo('body');
count++;
};
})();
jsFiddle.
This one starts with 0, but you could easily start count with 1.
You could also use a closure if you wanted, i.e.
var cloneForm = function(form, start) {
start = start || 0;
return function() {
var clone = form.clone();
clone.find(':input').attr('id', function(i, val) {
return val + start;
});
start++;
return clone;
};
};
Then you would do...
var cloneContactForm = cloneForm($('#contact-form'), 5);
// Now I want to clone it and put it somewhere.
$(cloneContactForm()).appendTo('body');
jsFiddle.
Here's a solution without updating any ids:
Give all forms the same class
Give all fields a name
Refer to cloned forms relative to all the forms with the class
Refer to fields with their name
Example:
How about giving each cloned form a different id, and then using names for each input element?
<form class="theForm">
<input type="password" name="password" />
</form>
Then Clone it with
container.append($('.theForm:first').clone());
(or cache the first form in a variable).
Finally, access the input fields with:
$('form.theForm:eq(0) [name=password]') // password from first form
$('form.theForm:eq(1) [name=password]') // password from second form
...
If the selector lookup efficiency is a factor here then there are several trivial ways to speed it up, such as caching variables with the different forms, caching $('.theForm') and using the eq() method, etc.
Sample jsFiddle is here: http://jsfiddle.net/orip/dX4sY