update textfield when radio button is selected and button is pressed Javascript - javascript

I have 4 radio buttons, when I select one, I want the default value of the quantity(addNumberOfItems) to be 1.
when a radio button is selected it should update a textfield that holds the quantity. Afterwards I have a button to add to the order. The problem is when I click addToOrderBtn and try and increase the quantity on the textfield(I replace the default 1 with 2 or 3) it always sets it back to 1.
My textfield that keep track of Total items(totalItems), should add what I input into addNumbersOfItems.
I tried to update the value of addNumberOfItems when the button is clicked. but its still set to default value.
Javascipt only please.
Thank you!
Code pen: http://codepen.io/anon/pen/LpJqgj
var addNumberOfItems = document.getElementById("numberOfItems");
var addToOrderBtn = document.getElementById("addToOrder");
var totalItems = document.getElementById("items");
var totalPrice = document.getElementById("total");
if (selected == "Classic" && foodOptionChecked1 == true) {
addNumberOfItems.value = 1;
};
addToOrderBtn.onclick = function() {
document.getElementById('numberOfItems').value = addNumberOfItems.value;
totalItems.value = addNumberOfItems.value;
totalPrice.value = foodClassic[0].smallPrice;
addNumberOfItems.value = "";
};
HTML
<fieldset class="form1 hide" id="choices">
<legend> your Choices </legend>
<p style="margin-left:25%">Which one would you like?</p>
<form style="float: right" id="selectSize">
<input type="radio" id="food1" name="size" value=""><label id="foodLabel1">food1</label>
<br>
<input type="radio" id="food2" name="size" value=""><label id="foodLabel2">food2</label>
<br>
<input type="radio" id="food3" name="size" value=""><label id="foodLabel3">food3</label>
<br>
<input type="radio" id="food4" name="size" value=""><label id="foodLabel4">food4</label>
<input type="text" id="numberOfItems" name="" value="">
<button type="button" id="addToOrder">Add to order</button>
<button type="button">Remove last item</button>
</form>
<p style="margin-top: 15%; margin-left:25%"> Extras! </p>
<p style="margin-top: 11%; margin-left:25%"> How many? </p>
</fieldset>
<fieldset class="form1 hide" id="orderStatus">
<legend> Order Status </legend>
<form>
Items<input type="text" name="" id="items">
Total<input type="text" name="" id="total">
<button type="button">Order Now</button>
<button type="button">Cancel</button>
</form>
</fieldset>

This is because inside getOrder() this line addNumberOfItems.value = 1; make quantity to 1 when you change quantity value
try following code in your getOrder() where you setting default value will solve you problem of quality reset
if (selected == "Classic" && foodOptionChecked1 == true) {
if(addNumberOfItems.value.length == 0)
addNumberOfItems.value = 1;
}
};
but sill i am unable to find why getOrder() call after changing the quality value might be because of code in your main.js

Related

How can I hide a button until at least three input checkboxes (one from each separate set of six) are checked?

I have three lists (HTML Fieldset elements) with six foods (HTML input elements - starting as unchecked) in each. I would like to keep a button element below these three lists hidden until at least one food from each of the three lists has been checked. When at least one food from each list has been checked I would like the button to unhide.
This will unhide the button when one of the inputs in the first fieldset is clicked... but I need to expand the functionality so that the button will only appear when at least one of each of the 3x fieldsets (protein, carbs, and fats) is selected.
// Add variable for the DOM element button with id "generate-meals"
let generateMealButton = document.getElementById("generate-meals");
generateMealButton.classList.add("hide");
// Add an eventlistener to generate meal button to listen for a "click" event and run the
// function "runMealGenerator when the event occurs"
generateMealButton.addEventListener("click", runMealGenerator);
// find all input fields
const proteinInputs = document.querySelectorAll("input[class='protein-input']");
console.log(proteinInputs[0].checked)
const carbInputs = document.querySelectorAll("input[class='carb-input']");
console.log(carbInputs)
const fatInputs = document.querySelectorAll("input[class='fat-input']");
console.log(fatInputs)
// add click event-listener for all input buttons
proteinInputs.forEach((input) => {
input.addEventListener("click", checkProteinInput);
});
// check if any input buttons are 'checked'
function checkProteinInput() {
// if the macroChoice button is 'not' hidden, then unhide it
console.log(proteinInputs[0].checked)
if (generateMealButton.classList.contains("hide")) {
generateMealButton.classList.remove("hide");
}
}
function runMealGenerator() {
console.log("Dummy Function Added")
}
<!-- This section contains the 3x menus of sample foods the user can select for inclusion in their meal plan ideas -->
<section id="foodListContainer">
<!-- Small section for direction to the user - instructions on how to proceed -->
<section class="food-groups" id="generator_instructions">
<h3 id="food-heading">Instructions</h3>
<p>Please select at least one food from each group for inclusion in meal plans:</p>
</section>
<!-- Fieldset to contain checkboxes for each Protein food option for selection by user -->
<fieldset class="food-groups" id="proteinFieldset">
<legend>Protein:</legend>
<!-- Each Protein input is housed in a div to enable dematcation & styling -->
<div>
<label for="chicken">Chicken</label>
<input class="protein-input" type="checkbox" id="chicken" name="chicken">
</div>
<div>
<label for="turkey">Turkey</label>
<input class="protein-input" type="checkbox" id="turkey" name="turkey">
</div>
<div>
<label for="fish">Fish</label>
<input class="protein-input" type="checkbox" id="fish" name="fish">
</div>
<div>
<label for="beef">beef</label>
<input class="protein-input" type="checkbox" id="beef" name="beef">
</div>
<div>
<label for="eggs">eggs</label>
<input class="protein-input" type="checkbox" id="eggs" name="eggs">
</div>
<div>
<label for="pork">pork</label>
<input class="protein-input" type="checkbox" id="pork" name="pork">
</div>
</fieldset>
<!-- Fieldset to contain checkboxes for each Carbohydrate food option -->
<fieldset class="food-groups">
<legend>Carbohydrate:</legend>
<!-- Each Carbohydrate input is housed in a div to enable dematcation & styling -->
<div>
<label for="bread">Bread</label>
<input class="carb-input" type="checkbox" id="bread" name="bread">
</div>
<div>
<label for="pasta">Pasta</label>
<input class="carb-input" type="checkbox" id="pasta" name="pasta">
</div>
<div>
<label for="rice">Rice</label>
<input class="carb-input" type="checkbox" id="rice" name="rice">
</div>
<div>
<label for="oats">Oats</label>
<input class="carb-input" type="checkbox" id="oats" name="oats">
</div>
<div>
<label for="cereal">Cereal</label>
<input class="carb-input" type="checkbox" id="cereal" name="cereal">
</div>
<div>
<label for="quinoa">Quinoa</label>
<input class="carb-input" type="checkbox" id="quinoa" name="quinoa">
</div>
</fieldset>
<!-- Fieldset to contain checkboxes for each Fat food option -->
<fieldset class="food-groups">
<legend>Fat:</legend>
<!-- Each Fat input is housed in a div to enable dematcation & styling -->
<div>
<label for="butter">Butter</label>
<input class="fat-input" type="checkbox" id="butter" name="butter">
</div>
<div>
<label for="cheese">Cheese</label>
<input class="fat-input" type="checkbox" id="cheese" name="cheese">
</div>
<div>
<label for="cream">Cream</label>
<input class="fat-input" type="checkbox" id="cream" name="cream">
</div>
<div>
<label for="nuts">Nuts</label>
<input class="fat-input" type="checkbox" id="nuts" name="nuts">
</div>
<div>
<label for="bacon">Bacon</label>
<input class="fat-input" type="checkbox" id="bacon" name="bacon">
</div>
<div>
<label for="olive-oil">Olive Oil</label>
<input class="fat-input" type="checkbox" id="olive-oil" name="olive-oil">
</div>
</fieldset>
<!-- End of foodListContainer section -->
<!-- Button to allow the user proceed to generate meal plan ideas when they have selected
All foods they wish to include/exclude -->
<section id="generate-container">
<button id="generate-meals">Generate A Meal Plan</button>
</section>
</section>
You will need to iterate over ALL checkboxes, whether at least one of each section is checked. And you will need to do this, also, when a checkbox is unchecked, because probably you want to hide the button again, when the condition is not met anymore ...
The straight forward approach would be the following
function checkInputs() {
let p = false, f = false, c = false; //protein, carbon, fat
for (let i = 0; i < proteinInputs.length; i++) {
if (proteinInputs[i].checked) { p = true; break;} //we found at least one
}
for (let i = 0; i < fatInputs.length; i++) {
if (fatInputs[i].checked) { f = true; break;} //we found at least one
}
for (let i = 0; i < carbonInputs.length; i++) {
if (carbonInputs[i].checked) { c = true; break;} //we found at least one
}
if (p && f && c) { //found at least one in each section
//show the button
generateMealButton.classList.remove("hide");
} else { //at least one is missing
//hide the button
generateMealButton.classList.add("hide");
}
}
and add this checkInputs to all your checkboxes (ie not only for proteins, but also for fat and carbons)
Btw. You don't need to explicitly check with classList.contains if you are using classList.add or classList.remove. Those functions will take care of that. Ie, it won't add the same class twice if it's already contained, and there is no error if you try to remove a class, that isn't contained in the classList)
Of course you can optimize this code. For instance just evalute the checkbox that was just changed and keep a counter for each of the sections. And when all counters are > 0 unhide the button, and hide the button when one goes to zero ...
let cb = document.querySelectorAll("input[type='checkbox']")
for (let i = 0; i < cb.length; i++) cb[i].addEventListener("change", check);
let c = 0, f= 0, p= 0
function check(event) {
let addval = event.currentTarget.checked ? 1 : -1
switch(event.currentTarget.getAttribute("data-tag")) {
case "f": f += addval; break;
case "c": c += addval; break;
case "p": p += addval; break;
}
console.log(f,c,p);
if (f && c && p)
document.getElementById("thebutton").classList.remove("hide")
else
document.getElementById("thebutton").classList.add("hide")
}
.hide {
display: none;
}
<input type="checkbox" data-tag="f"/>fat
<input type="checkbox" data-tag="c"/>carbon
<input type="checkbox" data-tag="p"/>protein
<input type="checkbox" data-tag="f"/>fat2
<input type="checkbox" data-tag="c"/>carbon2
<input type="checkbox" data-tag="p"/>protein2
<input id="thebutton" type="button" value="create meal" class="hide">

Using jQuery's prop() to click on a checkbox isn't running the onClick() function set on the checkbox

I have two checkboxes that has a onclick() function assigned to them. Now in a button, I have jquery set so that the checkboxes are checked automatically, via prop()
When the button is pressed, the checkboxes are checked but the onclick() function isn't working. How do I make it work? Any idea?
html:
<div class="container">
<h2 class="mt-5">Tester</h2>
<form>
<div class="form-group row align-items-center">
<div class="col-3">
<label for="policyinInt">Int</label>
<input class="form-control" value="0" readonly="readonly" type="text" name="total" />
</div>
<div class="col-3">
<label for="policyinHex">Hex</label>
<input class="form-control" value="0" readonly="readonly" type="text" name="totalhex" id="policyinHex" />
</div>
</div>
</form>
<input class="form-check-input" name="values" value="256" type="checkbox" onclick="totalIt()" id="bit8" /> <span class="code">0x00000100</span><br>
<input class="form-check-input" name="values" value="512" type="checkbox" onclick="totalIt()" id="bit9" /> <span class="code">0x00000200</span> <br>
<button type="button" class="default btn btn-outline-primary">Check the boxes</button>
<br>
</div>
javascript:
function totalIt() {
var input = document.getElementsByName("values");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseInt(input[i].value);
}
}
document.getElementsByName("total")[0].value = total;
document.getElementsByName("totalhex")[0].value = decimalToHexString(total);
}
function decimalToHexString(number)
{
number = number.toString(16).toUpperCase()
number = "0x"+number;
return number;
}
$(document).ready(function(){
$(".default").click(function(){
$("#bit8").prop("checked", true);
$("#bit9").prop("checked", true);
});
});
jsfiddle of what I have so far: https://jsfiddle.net/fahims/7eyf5v86/
So when the checkboxes are checked manually, the function is working. But when the button is used to trigger the checkbox, the functions arent working. Is there a better way to do what I'm trying to achieve?
Just call totalIt() after you set the checked properties. Setting properties or values programmatically does not trigger user events
$(".default").click(function(){
$("#bit8, #bit9").prop("checked", true);
totalIt();
});

Compare two variables with generated numbers

Currently I learn the curve of PHP and for first time trying to make AJAX request to my PHP script. I got cart in my own written shop for learning purposes, it generates button and input field with same "data-id" attributes for each position. And of course, input field got "value" attribute with current amount of products.
Code:
Jquery:
$(document).ready(function() {
$(".btn").click(function () {
var id = $(this).attr("data-id");
var idInput = $(".field").attr("data-id");
var value = $(".field").attr("value");
if (id === idInput) {
$.post("/cart/addAjax/" + id, {}, function (data) {
$("#cart-count").html(data);
});
$.post("/cart/addAjax/" + value, {});
return false;
} else {}
});
});
Example of input of PHP generated HTML:
<input class="field" data-id="3" type="number" value="23">
<button class="btn" data-id="3">Quantity</button>
<input class="field" data-id="14" type="number" value="3">
<button class="btn" data-id="14">Quantity</button>
<input class="field" data-id="17" type="number" value="2">
<button class="btn" data-id="17">Quantity</button>
<input class="field" data-id="18" type="number" value="8">
<button class="btn" data-id="18">Quantity</button>
<input class="field" data-id="19" type="number" value="10">
<button class="btn" data-id="19">Quantity</button>
I want Jquery script to compare input/button "data-id" attributes and send "value" of selected "data-id" attribute request to PHP side, but don't know how to tell script get "value" from selected "data-id", guess its the reason why its POST successfully only for first generated product in cart, for the rest products script doesn't work. Can someone enlighten me how to achieve this? Thanks in advice.
You need to structor your html a little better.
I made some changes to the html and put each btn and field under a div.
This will make things easer to find the selected input by its btn click.
Read the comment to understand.
$(document).ready(function() {
$(".btn").click(function () {
var id = $(this).attr("data-id");
// now go to the selected btn Parent, and then find the .field
// there you are sure its the right field becouse both the button
// and the field is containe under one div{Parent}
var idInput = $(this).parent().find(".field")
console.clear();
console.log("you Selected id " +id + " and its value is " + idInput.val())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="field" data-id="3" type="number" value="23">
<button class="btn" data-id="3">Quantity</button>
</div>
<div>
<input class="field" data-id="14" type="number" value="3">
<button class="btn" data-id="14">Quantity</button>
</div>
<div>
<input class="field" data-id="17" type="number" value="2">
<button class="btn" data-id="17">Quantity</button>
</div>
<div>
<input class="field" data-id="18" type="number" value="8">
<button class="btn" data-id="18">Quantity</button>
<div>
<input class="field" data-id="19" type="number" value="10">
<button class="btn" data-id="19">Quantity</button>
</div>
$('button').on('click',function(){
var data = $(this).data('id');
var url = 'your php file';
$.post(url,data,function(rdata){
//do whatever yo want with returned data
});
});

Hide button until two names are checked

I want to hide a button until two specific radiobuttons with two different names are checked. I'm just not sure how to go about this..
HTML
<form>
<!-- First question -->
<fieldset>
<input type="radio" name="trend1" value="Progressing">
<input type="radio" name="trend1" value="Regressing">
</fieldset>
<fieldset>
<input type="radio" name="q1" value="Good">
<input type="radio" name="q1" value="Bad">
</fieldset>
<button class="next" type="button" name="hideQ1">
<!-- Disable this button until one option on #trend1 and #q1 are checked. -->
<!-- Not a submit button, if that matters -->
<!-- Second question -->
<fieldset>
<input type="radio" name="trend2" value="Progressing">
<input type="radio" name="trend2" value="Regressing">
</fieldset>
<fieldset>
<input type="radio" name="q2" value="Good">
<input type="radio" name="q2" value="Bad">
</fieldset>
<button class="next" type="button" name="hideQ2">
<!-- Disable this button until one option on #trend2 and #q2 are checked. -->
<!-- Not a submit button, if that matters -->
</form>
I kinda know how to do it over the entire form, but what the button does is that it hides the current question, and shows the next one, so just hiding the button till specific names are checked would be the best way for me to go about it..
Any help/tips are much appreciated.
EDIT:
Hide as in, either disable or hide. Something like that.
EDIT 2:
This is what I've tried, maybe it helps you get an idea of what I want.. All it does however is disabling the next button completely.
$(document).ready(function(){
$('button[name="hideQ1"]').attr('disabled');
if ($('input[name="q1"]').is(':checked')) && ($('input[name="trend1"]').is(':checked')) {
$('button[name="hideQ1"]').removeAttr('disabled');
}
});
Maybe something like that.
var trend1 = document.getElementsByName('trend1'),
q1 = document.getElementsByName('q1'),
button1 = document.getElementsByName('hideQ1')[0],
trend2 = document.getElementsByName('trend2'),
q2 = document.getElementsByName('q2'),
button2 = document.getElementsByName('hideQ2')[0]
function checked(inputArr) {
return [].some.call(inputArr, function (input) {
return input.checked
})
}
[].forEach.call(document.querySelectorAll('input[type=radio]'), function (input) {
input.addEventListener('click', function () {
if (checked(trend1) && checked(q1)) button1.removeAttribute('disabled')
if (checked(trend2) && checked(q2)) button2.removeAttribute('disabled')
})
})
<form>
<!-- First question -->
<fieldset>
<input type="radio" name="trend1" value="Progressing">
<input type="radio" name="trend1" value="Regressing">
</fieldset>
<fieldset>
<input type="radio" name="q1" value="Good">
<input type="radio" name="q1" value="Bad">
</fieldset>
<button class="next" type="button" name="hideQ1" value="next" disabled>Next for q1</button>
<!-- Disable this button until one option on #trend1 and #q1 are checked. -->
<!-- Not a submit button, if that matters -->
<!-- Second question -->
<fieldset>
<input type="radio" name="trend2" value="Progressing">
<input type="radio" name="trend2" value="Regressing">
</fieldset>
<fieldset>
<input type="radio" name="q2" value="Good">
<input type="radio" name="q2" value="Bad">
</fieldset>
<button class="next" type="button" name="hideQ2" disabled>Next for q2</button>
<!-- Disable this button until one option on #trend2 and #q2 are checked. -->
<!-- Not a submit button, if that matters -->
</form>
Here's an approach: on every radio change, run a function that checks if the specific ones are checked, and if so, show the button. Otherwise, hide the button.
That's all there is to it, and it should be pretty easy to translate this into JS.
You can use same radio name ( Two radio ) if you added question through ajax call.
Then you can use same code for all question.
Here's is my approach bro:
$( document ).ready(function() {
// Your Code Start
var isTrend1 = false;
var isQ1 = false;
$("input[name='trend1']").on("click", function (e){
isTrend1 =$("input[name='trend1']").is(':checked');
isQ1 =$("input[name='q1']").is(':checked');
if ( isTrend1 && isQ1 ) {
$('.hideQ1').css({'display':'block'});
}
});
$("input[name='q1']").on("click", function (e){
isTrend1 =$("input[name='trend1']").is(':checked');
isQ1 =$("input[name='q1']").is(':checked');
if ( isTrend1 && isQ1 ) {
$('.hideQ1').css({'display':'block'});
}
});
$(".hideQ1").on("click", function (e){
$('.hideQ1').css({'display':'none'});
$('.question_1').css({'display':'none'});
$('.question_2').css({'display':'block'});
});
var trend2 = false;
var isQ2 = false;
$("input[name='trend2']").on("click", function (e){
isTrend2 =$("input[name='trend2']").is(':checked');
isQ2 =$("input[name='q2']").is(':checked');
if ( isTrend2 && isQ2 ) {
$('.hideQ2').css({'display':'block'});
}
});
$("input[name='q2']").on("click", function (e){
isTrend2 =$("input[name='trend2']").is(':checked');
isQ2 =$("input[name='q2']").is(':checked');
if ( isTrend2 && isQ2 ) {
$('.hideQ2').css({'display':'block'});
}
});
// Your Code End
});
// Document Ready Start
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<!-- First question -->
<div class="question_1">
<fieldset>
<input type="radio" name="trend1" value="Progressing">Progressing Q1
<input type="radio" name="trend1" value="Regressing">Regressing Q1
</fieldset>
<fieldset>
<input type="radio" name="q1" value="Good">Good Q1
<input type="radio" name="q1" value="Bad">Bad Q1
</fieldset>
</div>
<button class="next hideQ1" type="button" name="hideQ1" style="display:none;" value="Next">Next Question Q2
</button>
<!-- Disable this button until one option on #trend1 and #q1 are checked. -->
<!-- Not a submit button, if that matters -->
<div class="question_2" style="display:none;">
<!-- Second question -->
<fieldset>
<input type="radio" name="trend2" value="Progressing">Progressing Q2
<input type="radio" name="trend2" value="Regressing">Regressing Q2
</fieldset>
<fieldset>
<input type="radio" name="q2" value="Good">Good Q2
<input type="radio" name="q2" value="Bad">Bad Q2
</fieldset>
</div>
<button class="next hideQ2" type="button" name="hideQ2" style="display:none;">Next Question Q 3</button>
<!-- Disable this button until one option on #trend2 and #q2 are checked. -->
<!-- Not a submit button, if that matters -->
</form>
I think this will help you.
Thanks
Check this approach
https://jsfiddle.net/q4vvdwc5/1/
$(document).ready(function(){
var inputs = $("input[name^='trend'], input[name^='q']");
inputs.change(function(){
selected = [0, 0];
var self = $(this);
qnumber = $(this).attr('name').slice(-1);
inputs.each(function(index, element){
if ($(element).attr('name').slice(-1) == qnumber && $(element).prop('checked')) {
selected[qnumber-1] += 1;
if (selected[qnumber-1] > 1) {
$(this).closest('fieldset').siblings(".next[class$='after"+qnumber+"']").show();
}
console.log(qnumber, selected[qnumber-1]);
}
});
});
});
I also altered your DOM a bit so it's valid HTML. And added a few classes.

Change radio button value to the value of text input

I have this code which has a radio button. I want to get the value of the text box and set it as the value of the selected radio button.
HTML
<form action="add.php" id="registration" method="post" name='registration'
onsubmit="return formValidation();">
Monthly amount of<br>
<input id="300" name="amounts" type="radio" value="300"><label for="300">P
300.00</label><br>
<input id="amntother" name="amounts" type="radio" value="">P
<input disabled="disabled" id="otherAmount" name="amntotherSpecify" type=
"text" value=""><label for="amntother">(please specify)</label><br>
<button name="submit" style="width:305px" type="submit" value=
"Submit">ADD</button>
</form>
Javascript
window.onload = function() {
var promised = document.getElementsByName("amounts");
for (var i = 0; i < promised.length; i++) {
promised[i].onclick = function() {
var rads = this.form[this.name];
for (var i = 0; i < rads.length; i++) {
var textField = this.form[rads[i].value.toLowerCase() + "Amount"];
if (textField) textField.disabled = !rads[i].checked;
}
}
}
}
<form form="view" name='registration' method="POST" action="add.php" onSubmit="return formValidation();">
Monthly amount of</br>
<input type="radio" name="amounts" id="300" value="300" ><label for="300">P 300.00</label><br/>
<input type="radio" name="amounts" id="amntother" value="" >P<br/>
<input type="text" name="amntotherSpecify" id="otherAmount" value="" onchange="addValueToRadioBtn();"/><label for="amntother">(please specify)</label><br/>
<button type="submit" name="submit" value="Submit" style="width:305px">ADD</button>
<script>
function addValueToRadioBtn() {
if (document.getElementById("amntother").checked == true){
document.getElementById("amntother").value = document.getElementById("otherAmount").value;
}
//added an alert box just to test that the value has been updated
alert(document.getElementById("amntother").value);
}
</script>
I have removed the disabled value so that a value can be entered, on change of this value and if the radio button (otheramount) is selected then other amount value will reflect the value that was entered in the textbox.
Just to note that if you disable the text then no user will be able to add a value. If this isn't what you are looking for could you explain in more detail as to how the textbox will be populated and more in what you are trying to achieve.
Anyway hope this script helps
You don't specify formValidation or add.php. If all you want to do is add the specified value as an option, you don't need to call back to the server to do that. Just update the form with the new option:
html
<form form="view" name='registration' method="post" action="add.php" onsubmit="return formValidation();">
<div id="amountOptions">
Monthly amount of</br>
<input type="radio" name="amounts" id="opt300" value="300" ><label for="opt300">P 300.00</label><br/>
</div>
<input type="text" name="amntotherSpecify" id="newvalue" value=""/>
<input type="button" id="btnNewValue" value="Specify your own amount"/>
</form>
javascript
var btnNewValue = document.getElementById('btnNewValue');
btnNewValue.addEventListener('click', function()
{
var div = document.getElementById('amountOptions');
var newAmount = document.forms[0].amntotherSpecify.value;
var optCheck = document.getElementById('opt'+newAmount);
if(optCheck !== null)
return;
var newopt = document.createElement('input');
newopt.type = 'radio';
newopt.id = 'opt'+newAmount;
newopt.name = 'amounts';
newopt.value = newAmount;
var newoptLabel = document.createElement('label');
newoptLabel.for = newopt.id;
newoptLabel.innerHTML = 'P ' + newAmount;
var br = document.createElement('br');
div.appendChild(newopt);
div.appendChild(newoptLabel);
div.appendChild(br);
var newAmount = document.forms[0].amntotherSpecify.value = '';
});
Here's a fiddle to demonstrate it in action. You'll want to add in validation that the new option's value is a number and fits whatever constraints you have.
It's important that you note that according to the html spec, ids cannot start with a number, in fact they must start with a character in the range a-zA-Z.
how about this option...
Slight modification to HTML - extra button, extra label tag
HTML
<form form="view" name='registration' method="POST" action="add.php" onSubmit="return formValidation();">
Monthly amount of</br>
<input type="radio" name="amounts" id="300" value="300" ><label for="300">P 300.00</label><br/>
<input type="radio" name="amounts" id="amntother" value="" ><label id="labelamntother" for="amntother">P</label>
<input type="text" name="amntotherSpecify" id="otherAmount" value="" /><label for="amntother">(please specify)</label><br/>
<button type="button" name="reset" value="Reset Value" style="width:305px" onclick="location.reload(true)">Reset Radio Button Value</button>
<button type="submit" name="submit" value="Submit" style="width:305px">ADD</button>
</form>
Javascript
<script>
document.getElementById("otherAmount").onkeyup = function() {
document.getElementById("labelamntother").innerHTML ="P " + this.value;
}
</script>

Categories

Resources