Changing onClick value through radio buttons - javascript

I am quite new to all this and wondering if someone can help with something. I have the code below which when the button is clicked is references a javascript file and populates a random english word. I am wanting to change it to add a radio button. The radio button will allow the user to select an english word or french word. How can I change my onClick command to use the value of the selected radio button?
<FORM NAME="Generator">
<INPUT TYPE=TEXT NAME="WordBox" id="wordbox"><BR>
<INPUT TYPE=BUTTON VALUE="Generate" onClick="English(document.WordForm);" id="button">
</FORM>

I guess that you've a function English that take the form as a only parameter, you don't have to change anything just add the radio and get the value from the form inside your function, like :
<FORM NAME="Generator">
<INPUT TYPE="TEXT" NAME="WordBox" id="wordbox">
<BR>
<INPUT TYPE="RADIO" NAME="language" value="ENGLISH">ENGLISH
<INPUT TYPE="RADIO" NAME="language" value="FRENCH">FRENCH
<BR>
<INPUT TYPE=BUTTON VALUE="Generate" onClick="English(document.WordForm);" id="button">
</FORM>
Then get the value :
function English(form){
var language = form.language.value;
}
Hope this helps.

I'm not sure if I fully understand what it is that you're trying to achieve, but is it something along the lines of what I've created in this fiddle?
https://jsfiddle.net/pq6eh1jk/5/
HTML:
<input id="word" type="text"/>
<input id="english" type="radio" name="language" checked="checked"> English
<input type="radio" name="language" value="english"> French
<input type="button" onclick="generateText()" value="Generate Text"/>
JS:
var englishWordBank = [ 'Animal', 'Bank', 'City' ];
var frenchWordBank = [ 'Avion', 'Bonjour', 'Chat' ];
var generateText = function() {
var wordInput = document.getElementById('word');
var randomIndex = Math.round(Math.random()*2); //Between 0-2
if (document.getElementById('english').checked)
wordInput.value = englishWordBank[randomIndex];
//French:
else
wordInput.value = frenchWordBank[randomIndex];
};

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"]
});
});

Store input radio selections when submit is clicked

I need to store in my js file which radio option for each radio name was selected as well as store the Username that was entered. Here is my form
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input type="radio" name="class"/>Archer
<input type="radio" name="class"/>Mage
<input type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input type="radio" name="race"/>Orc
<input type="radio" name="race"/>Elf
<input type="radio" name="race"/>Human
<input type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
EDIT:
When I try to target the submit button for a click function it causes my page to reload instead of making the form fadeOut
var userInput;
var classInput;
var raceInput;
$('input[type=submit]').click(function(){
$('#newPlayer').fadeOut(500);
userInput = $('input[name="user"]').val();
classInput = $('input[name="class"]:checked').val();
raceInput = $('input[name="race"]:checked').val();
});
Maybe this helps. First, you will have to put values on those inputs
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input value="archer" type="radio" name="class"/>Archer
<input value="mage" type="radio" name="class"/>Mage
<input value="warrior" type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input value="orc" type="radio" name="race"/>Orc
<input value="elf" type="radio" name="race"/>Elf
<input value="human" type="radio" name="race"/>Human
<input value="worg" type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
Then, using jQuery, a simple .val() will do the job:
var class_val = $('input[name="class"]:checked').val();
var race = $('input[name="race"]:checked').val();
var user = $('input[name="user"]').val();
After that, you just need to put in localStorage
localStorage.setItem('class', class_val);
localStorage.setItem('race', race);
localStorage.setItem('user', user);
To access those values in the future, you do that
var stored_class = localStorage.getItem('class');
var stored_race = localStorage.getItem('race');
var stored_user = localStorage.getItem('user');
To make things happens on submit, you add an submit event to the form, like that:
$('form').on('submit', function() {
// Get values
var class_val = $('input[name="class"]:checked').val();
...
// Store values
localStorage.setItem('class', class_val);
...
// Avoid form submit
return false;
});
Hope it helps :)
I think I would use localStorage.
For example:
//Make sure to set the selection variable to a object that contains the selections made by the user.
function save() {
//This will save the current settings as an object to the localStorage.
localStorage.selections = JSON.stringify(selections) ;
}
function load() {
if (!localStorage.selections) {
alart("No saves found.") ;
return false ;
}
selections = JSON.parse(localStorage.selections) ;
}
Read more about localStorage here.

Javascript adding values to radio buttons to input price

Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.

Categories

Resources