Reading form field data in Javascript - javascript

I just can't get this to work.
HTML:
<form action="index.php?page=n0402" method="post" Name="AddPolish" >
<div id="frmBrandInput">
<label for="frmBrand">Brand name:</label>
<input type="text" name="frmBrand" size="50" onkeypress="BrandCheck();" maxlength="100" id="frmBrand" value="Enter existing or new brand" />
<span id="frmBrand_Status"></span>
</div>
</form>
Javascript:
function BrandCheck()
{
var jsBrandName = document.forms["AddPolish"]["frmBrand"].value;
alert(jsBrandName);
}
Why can't I get the value of frmBrand into jsBrandName? If I use Firebug to debug, I get the following in my Watch list:
Watch Expression:
document.forms["AddPolish"]["frmBrand"];
Result:
NodeList[input#frmBrand property value = "G" attribute value = "Enter existing or new brand", input#frmBrand attribute value = ""]
I can see the value "G" which is what I entered in the input field. What am I doing wrong in passing it into the jsBrandName?

The output you got implies that there are two inputs with name="frmBrand" in the form. You need to index them, e.g.
var jsBrandName = document.forms["AddPolish"]["frmBrand"][0].value;
to get the value of the first one.

Related

HTML FORM - Change Parts Of Readonly String Field Using onchange()

I want to assign the values - value and value 2 into the DATAID and DEPNUM when clicking the drop-down and using onchange() function in the following HTML FORM
The places that are being assigned are parts of a readonly field which contains string.
My goal is to create a readonly string which will contain the values that I've chosen from the dropdown fields, all combined in 1 string and separated by underscore.
I've been trying to use onChange method "myFunction()"
<input name="_1_1_2_1" tabindex="-1" class="valueEditable" id="myInput" onchange="myFunction()" type="text" size="32" value="...">
which will look like :
function myFunction()
{
var x = document.getElementById("myInput").value;
document.getElementById("demo").innerHTML = x;
}
eventually I run it on the paragraph :
<p id="demo" value="DATAID_DOCTYPE_DEPNUM_NTA">DATAID_DOCTYPE_DEPNUM_NTA</p>
The problem is that the value at is not changing instant as i change value2 or value.
You can bind two event-listener for both two input fields and updated the readonly textfield value by below approach.
$(document).ready(function(){
$('#field1').keyup(function() {
updatedReadonlyFieldVal($(this), 0);
});
$('#field2').keyup(function() {
updatedReadonlyFieldVal($(this), 2);
});
function updatedReadonlyFieldVal(elem, index) {
let val = elem.val();
let destVal = $('#destination').val();
let splittedDestVal = destVal.split('_');
splittedDestVal[index] = val;
$('#destination').val(splittedDestVal.join('_'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input value="DATAID_DOCTYPE_DATANUM" readonly id="destination">
Please don't hesitate to let me know if you have any query.

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" />

How do I pass a dataset attribute dynamically using user input?

I have a text input box where a user inputs what data-* they want to look for in the DOM. I get this user input on a button click then do a little bit of parsing. How would I get the value of the entered text to be the final part of the HTMLElement.dataset selector?
//HTML for text input
<div class="form-group">
<label for="specificSelector">Specific Selector</label>
<input type="text" class="form-control" id="specificSelector" placeholder="Enter the specific selector here">
</div>
<p id="a"></p>
//JavaScript
var specificSelector = document.getElementById("specificSelector").value;
var a = document.getElementById("a"); // Test element
var parsedSelector = specificSelector.match(/data-(.*)/)[1];
console.log("Parsed selector: ", parsedSelector);
//I need to pass the value of the parsedSelector to the below line
var aData = a.dataset.parsedSelector;
console.log("aData: ", aData);
I have read this from MDN Developers but can't figure it out. It looks like you have to pass the data attribute in camel case but might not be able to do it via a variable?
Thanks in advance.
When you need to access an object property via a variable, you need to use array-bracket syntax.
In the example below, type "data-test" into the text box and then hit TAB.
// Get a reference to the input
var specificSelector = document.getElementById("specificSelector");
var a = document.getElementById("a"); // Test element
// Set up an event handler for when the data is changed and the
// input loses focus
specificSelector.addEventListener("change", function(){
// Extract the custom name portion of the data- attribute
var parsedSelector = specificSelector.value.match(/data-(.*)/)[1];
console.log("Parsed selector: ", parsedSelector);
// Pass the string (stored in the variable) into the dataset object
// of another element to look up the object key.
var aData = a.dataset[parsedSelector];
console.log("aData: ", aData);
});
<div class="form-group">
<label for="specificSelector">Specific Selector</label>
<input type="text" class="form-control" id="specificSelector" placeholder="Enter the specific selector here">
</div>
<div id="a" data-test="test2"></div>

Javascript set value for Form obeject Array

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

Set Input array value using jquery

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

Categories