How to get html input in JavaScript? - javascript

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}

You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>

These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>

You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>

You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

Related

Can't get Result to show with HTML Forms and Javascript

I'm trying to get my results to show up in the text box inputs as per my assignment but I can't get them to show up at all. The math isn't showing up at all so my big issue is that I can't get the code to show up in the box.
document.querySelector.("#buttonS").addEventListener("click", function(e) {
if (document.querySelector("#gallons").reportValidity()) {
let gallons = document.querySelector("#gallons").value;
if (document.querySelector("#quarts").checked) {
quartsTotal = gallons * 4;
document.querySelector("#quartsResult").placeholder = `quartsTotal`);
} else if (document.querySelector("#pints").checked) {
} else if (document.querySelector("#cups").checked) {
}
}
});
<form id="bakimg">
<input type="number" step=".01" min="0" id="gallons" required><label for="gallons"> How many gallons of milk do you have?</label>
<br>
<br>
<label for="conversion">Which conversion would you like?</label><br>
<input type="radio" value="quarts" name="gallonsC" checked><label for="quarts">Quarts</label>
<input type="radio" value="pints" name="gallonsC"><label for="pints">Pints</label>
<input type="radio" value="cups" name="gallonsC"><label for="cups">Cups</label>
</form>
<br>
<button type="button" id="buttonS">Submit</button><br>
<h1>Results</h1>
<br>
<input type="text" id="quartsResult" placeholder=""><label for="quartsResult">Quarts</label><br>
<input type="text" id="pintsResult"><label for="pintsResult">Pints</label><br>
<input type="text" id="cupsResult"><label for="cupsResult">Cups</label>
</div>
Check your syntax and make the following changes:
Check the browser console for errors and use the appropriate syntax:
document.querySelector.("#buttonS")
should be written like this:
document.querySelector("#buttonS") // No . after querySelector
Check the extra parentheses:
document.querySelector("#quartsResult").placeholder = `quartsTotal`); // <-- Remove the closing parens
Add the proper IDs to the HTML input elements (quarts, pints, cups):
<input type="radio" value="quarts" name="gallonsC" checked id="quarts">
<input type="radio" value="pints" name="gallonsC" id="pints">
<input type="radio" value="cups" name="gallonsC" id="cups">
Remove the backticks in order to use the variable value (otherwise quartsTotal is still a string):
`quartsTotal` -> quartsTotal
// Perhaps this is what you meant:
`${quartsTotal}`
Good luck with the assignment!

How to assign input radio value to a textarea content?

I have this form:
<form>
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
</form>
And I have this other form with an textarea:
<form>
<textarea id="textarea-field" placeholder='Type your message here...' required/>
</form>
I would like to know if there is any simple way to assign the value of the chosen input inside the textarea content right when user click one of these input.
A more feasible and easiest way would be do this way by making sure you assign an id to your form which will ensure that you are only selecting Input[type=radio] from that form and not every input on your page.
Also use textContent to assign a value to your textArea. Using innerHTML is not recommended.
We need to use forEach function to loop through all the input which we will find using querySelectorAll function (which returns all nodes list) and then use we can addEventListener to make sure that we listen to change events on your input and assign the value of the checked radio button to your textArea
Live Demo:
//get all radio buttons
let getRadios = document.querySelectorAll('#myForm > input[type="radio"]');
//get text area
let getTextArea = document.querySelector('#textarea-field');
//Loop through the radio button
getRadios.forEach(function(radio) {
radio.addEventListener('change', function() {
getTextArea.textContent = this.value //assign value to textArea
})
})
<form id="myForm">
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
<br>
<br>
<textarea id="textarea-field" placeholder='Type your message here...' required>
</textarea>
</form>
If you give each of your input a class purely for this script below it should work.
<script>
// GIVE EACH OF YOUR INPUTS A CLASS OF .input
// THEN ADD THIS SCRIPT
$(document).ready(function(){
$('.input').click(function(e) {
var text = $( this ).val();
$('#textarea-field').val( text );
});
});
</script>
You can do it this way
const radios = document.querySelectorAll('input');
const textarea = document.querySelector('#textarea-field');
radios.forEach(radio => {
radio.addEventListener('change', ({
target
}) => textarea.innerHTML = target.value);
});
<form>
<input type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
<textarea id="textarea-field" placeholder='Type your message here...' required></textarea>
</form>
Add a Custom Class to input where you want to put Radio Button
The Code below Gets the Value of clicked input radio button and sets in the TextArea Field.
$('.radiobuttoninput').click(function() {
$('#textarea-field').val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input class="radiobuttoninput" type="radio" id="option-1" name="name" value="Hello! I would like to talk to John"><label for="option-1">John</label>
<input class="radiobuttoninput" type="radio" id="option-2" name="name" value="Hello! I would like to talk to Maria"><label for="option-2">Maria</label>
<input class="radiobuttoninput" type="radio" id="option-3" name="name" value="Hello! I would like to talk to Kennedy"><label for="option-3">Kennedy</label>
<input class="radiobuttoninput" type="radio" id="option-4" name="name" value="Hello! I would like to talk to Adam"><label for="option-4">Adam</label>
</form>
<br>
<form>
<textarea id="textarea-field" placeholder='Type your message here...' required> </textarea>
</form>
If you don't want to use any libraries then you can also use vanilla to do this. Nothing to explain here so I will just show you.
HTML file:
<form name="form">
<input type="radio" name="rate" value="1"/>i am 1
<input type="radio" name="rate" value="2"/>i am 2
<input type="radio" name="rate" value="3"/>i am 3
</form>
<textarea value="" id="ta"></textarea>
You don't need id for the form or radio boxes. Just declare a name. That would do the trick.
JavaScript file:
document.form.onclick = function() {
var v = document.form.rate.value;
var t = document.getElementById("ta");
t.value = v;
}
Let me know if it worked.

jQuery - Sending "Select All" Check boxes with Multiple Forms

I have checked online for a solution to pass my values for the checkbox "select all". I have multiple forms in a page. So I will need to separate passing the values based on specific forms.
jQuery:
$(document).ready(function() {
$(".select-all").change(function () {
$(this).siblings().prop('checked', $(this).prop("checked"));
});
})
HTML for form:**
<div class="col">
<fieldset>
<form action="{$link->getLink('controller')|escape:'htmlall':'utf-8'}" method="post">
<p>
{foreach from=$payment item=row}
<input type="checkbox" name="payment[]" maxlength="50" value={$row.id_order}>
<label> ID: <b>{$row.id_order}</b></label><br/>
{/foreach}
<br/>
<input id="submit" name="submitpayment" type="submit" value="PACK ITEMS" class="button" />
</p>
</form>
</fieldset>
</div>
Error (Value is empty):
input type="checkbox" class="select-all" name="payment[]" value=""
SQL query to pass records:
public function displayOrdersbyID()
{
$query1 = new DbQuery();
$query1->select('o.id_order')
->from('orders','o')
->leftJoin('carrier','c','o.id_carrier=c.id_carrier')
->leftJoin('order_state_lang','s','o.current_state=s.id_order_state')
->where('c.name = ' . "'XXX'")
->where('s.name = ' . "'Payment accepted'");
$payment = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query1);
$this->context->smarty->assign( 'payment', $payment);
Controller:
if (Tools::isSubmit('submitpayment')) {
$ids= Tools::getValue('payment');
$query18 = new DbQuery();
$query18->select('id_order_state')
->from('order_state_lang')
->where('name = ' . "'Processing in progress'");
$updateinprogress = Db::getInstance()->getValue($query18);
foreach ($ids as $updateids) {
$objOrder = new Order($updateids);
$history = new OrderHistory();
$history->id_order = (int)$objOrder->id;
$history->id_employee = $cookie->id_employee;
$history->changeIdOrderState($updateinprogress, (int)($objOrder->id));
$history->add(true);
$history->save();
}
}
SELECT ALL checkbox:
<input type="checkbox" class="select-all" name="payment[]" value=
{$row.id_order}>
<label> SELECT ALL</label>
I was using the above code to create a SELECT ALL checkbox for the form, placing it outside the loop. I understand it is wrong and value is not passing, where should I place the checkbox at?
Any guidance is appreciated.
Thank you.
I think the problem in select-all value because there no initialization for $row.id_order in
<input type="checkbox" class="select-all" name="inprogress[]" value={$row.id_order}>
But if you assign the value of $row.id_order then might be not used in the following child like the {foreach from=$payment item=row} must use another variable identifier then row.
you working with a wrong practice you can't assign $row.order_id outside the loop.If there you want to use these element value in PHP then no need to do anything the $_POST['payment'] for the second form and $_POST['inprogress'] will return the value you want.
if no checkbox is selected then the result is returned blank.
and remember this will return an array type object.
The line
<input type="checkbox" class="select-all" name="inprogress[]" value={$row.id_order}>
lies outside the loop. Thus the value of {$row.id_order} will not be defined in your template. Check the DOM tree for compiled value.
And what is your final goal with the SELECT ALL button ? Is there any relation between the two forms?
Edit:
See the value of output variable. You can collect this value and pass it along with form submission.
<div class="col">
<fieldset>
<form>
<p>
<input type="checkbox" class="select-all" name="payment[]" value="22">
<label> SELECT ALL</label>
<br/><br/>
<input type="checkbox" name="payment[]" maxlength="50" value="a">
<label> ID: <b>A</b></label><br/>
<input type="checkbox" name="payment[]" maxlength="50" value="b">
<label> ID: <b>B</b></label><br/>
<input id="submit" name="submitinprogress" type="submit" value="PACK ITEMS" class="button" />
</p>
</form>
</fieldset>
</div>
$(document).ready(function() {
$(".select-all").change(function () {
$(this).siblings().prop('checked', $(this).prop("checked"));
let inputs = $(this).siblings("input[type=checkbox]");
let output = [];
for(let i = 0; i < inputs.length; i++){
output.push(inputs[i].value);
};
console.log(output); // ["a", "b"]
});
});

Get value from muti dimensional-array textbox using javascript

I have a list of textbox which is dynamically generated and and named with multi-dimensional array for posting to php later.
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']">
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
However, before the values get posted, i am trying to get the value of the specific textbox and do the validation.
var nodeValue = document.getElementsByName("node['X22']['in']").value;
alert(nodeValue);
Tried the above but it is not working. May i know is there a good way to parse trough the textbox list and get the specific textbox's value, let's say for 'X22' -> 'in'?
getElementsByName returns not a single element, but array-like object. Access the [0] indexed element of the result.
If you have unique elements, it will be better to get them by id (getElementById) which returns a single element.
var nodeValue = document.getElementsByName("node['X22']['in']")[0].value
// ----^^^----
alert(nodeValue);
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']" value='SomeValue'>
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
you need a value to get one
<html>
<head></head>
<body>
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']">
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
</body>
<script>
parse = function(){
var nodeValue = document.getElementsByName("node['X22']['in']");
console.log(nodeValue[0]);//to demonstrate that a nodelist is indeed returned.
}
parse()
</script>
</html>
You could use the id attribute and give it an identifier.
var nodeValue = document.getElementById("X22in").value;
console.log(nodeValue);
<input type="text" id="X22in" name="node['X22']['in']" value="foo">
<!-- ^^^^^^^^^^ -->

Copy multiple input fields to other matching input fields with jQuery/Javascript

I have a dummy form and the actual form in which at some point I want to copy all the input values from the dummy form across to the real form.
The dummy fields will have the same names as the real form (so I can match them up).
So in dummy form:
<input name="item1" value="field1" />
<input name="item2" value="field1" />
<input name="item3" value="field1" />
and in real form:
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
I assume I'll need to iterate over each input in dummy form (using jQuery .each() ?) while collecting the name and value in an JS object.
Then iterate over each input in the real form, matching the name as the selector and setting the value (perhaps this can be done in the one .each() function ???)
I've started with the following code which only grabs the values (and index) into an array, but because I need two values (name and value, and index is irrelevant) I assume I'll need an object not an array, but really not sure where to begin with that.
var inputValues = [];
$("#dummyForm input").each(function() {
inputValues.push($(this).val());
});
Any help or advice much appreciated.
Map them like
$('#DummyForm [name]').each(function() {
var name = $(this).attr('name');
$('#RealForm [name="' + name + '"]').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form id="DummyForm">
<input name="item1" value="field1" />
<input name="item2" value="field2" />
<input name="item3" value="field3" />
</form>
<form id="RealForm">
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
</form>
You could do something like below:
$('#dummy input').each(function(){
if($('#real input[name='+$(this).prop('name')+']').length == 1)
$('#real input[name='+$(this).prop('name')+']').val($('#dummy input[name='+$(this).prop('name')+']').val())
});
Here is my Fiddle...

Categories

Resources