Dynamic form Javascript dropdown/input - javascript

I am using a plugin for my crowdfunding plateform which is working fine and is helping me a lot as I am not quite confortable with coding yet.
However I'd like to tweak a JavaScript function. When a customer chooses how much he wants to contribute, the customer can either decide the amount or the reward level he wants
Here is basically how the form is made:
<form action="" method="POST">
<div class="form-row inline left twothird">
<label for="level_select">Contribution Level
<span class="dropdown ">
<select name="level_select" class="dropdown__select">
<option value="1" data-price="5.00">Reward 1</option>
<option value="1" data-price="15.00">Reward 2</option>
<option value="1" data-price="25.00">Reward 3</option>
</span>
</label>
</div>
<div class="form-row inline third total">
<label for="total">Total</label>
<input type="text" class="total" name="total" id="total" value="">
</div>
<div class="form-row submit">
<input type="submit">
</div>
From there I want to bind levels with the amount entered by the user.
Currently, it is partially working as changing the amount depending on the selected level is pretty easy. Where I'm stuck is with changing the selected option depending on the input.
In the plugin I found the following lines which seems to be what I'm interested in:
jQuery(document).bind('price_change', function(event, price) {
jQuery('input[name="total"]').val(price);
var levelIndex = jQuery('select[name="level_select"]').prop('selectedIndex');
var levelPrice = jQuery('select[name="level_select"] option').eq(levelIndex).data('price');
if (price < levelPrice) {
jQuery('input[name="total"]').val(levelPrice);
}
});
Based on this I started to tweak it a bit but with my fairly low knowledge of jQuery here is where I am at the moment:
jQuery(document).ready(function() {
jQuery(document).bind('price_change', function(event, price) {
var price = jQuery('input.total').val();
var levelIndex = jQuery('select[name="level_select"]').prop('selectedIndex');
var levelPrice = jQuery('select[name="level_select"] option').eq(levelIndex).data('price');
var nextLevel = jQuery('select[name="level_select"] option').eq(levelIndex + 1);//got to check if exist, else NULL
if (nextLevel){var nextLevelPrice = jQuery('select[name="level_select"] option').eq(levelIndex + 1).data('price');}
var prevLevel = jQuery('select[name="level_select"] option').eq(levelIndex - 1);//got to check if exist, else NULL
if (prevLevel){var prevLevelPrice = jQuery('select[name="level_select"] option').eq(levelIndex - 1).data('price');}
while (prevLevel!=NULL && price < levelPrice) {
jQuery('input[name="total"]').val(prevLevel);
}
while (nextLevel != NULL && price < nextLevelPrice){
jQuery('input[name="total"]').val(nextLevel);
}
});
Am I on the right track or is their an easier way to proceed?
Thank you for your attention, any advice appreciated

Related

How can I set default and change price with checkboxes?

I am trying to create an interface of a website which has a varying price dependent on whether check boxes are checked and which has a default value if none are selected.
The varying value is in a table which has the id 'Level1Price' which I want to default to a value of '£5.11' if neither of the two check boxes are checked and the value to chage if either one or both are selected and where the two chekc boxes on their own would hold a different value each.
The two check boxes have the id's 'partner' and 'children'. When no checkboxes are checked (for the purpose of this demonstartion) the value of 'Level1Price in the table should be 5.
If just the 'partner' checkbox is checked the value of 'Level1Price' is 10.
If just the 'children' checkbox is checked the value of 'Level1Price' is 12.
If both checkboxes are checked the value of 'Level1Price' is 20.
var partner = document.getElementById("partner");
var children = document.getElementById("children");
function calc()
if (!partner.checked && !children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 5;
} else if (partner.checked && !children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 10;
} else if (!partner.checked && children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 12;
} else if (partner.checked && children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 20;
}
This is the code that I thought would work and i'm struggling. I apologies if I have made rookie mistakes i'm quite new to this and couldn't find any working resolutions anywhere.
Thanks in advance.
These are the chekcboxes that I want to help change the vale in the table.
<div class="addition">
<label for="partner">+ Partner:</label>
<input type="checkbox" name="partner" id="partner" value="partner" required>
</div>
<div class="addition">
<label for="children">+ Children:</label>
<input type="checkbox" name="children" id="children" value="children" required>
</div>
</div>
This is the Table data I want to be able to populate
<tr>
<td scope=col id="Level1Price" value="5.11"> <b></b> <br/> per month</td>
<td scope=col id="Level2Price" value="9.97"> <b></b> <br/> per month</td>
<td scope=col id="Level3Price" value="14.06"> <b></b> <br/> per month</td>
</tr>
Is it possible to automatically update without the need for a 'calculate' button?
Provided your HTML looks like:
<span id="Level1Price"></span>
then:
document.getElementById('Level1Price').innerHTML = 20;
will result in your HTML being:
<span id="Level1Price">20</span>
Basically you just have a syntax problem (remove the erroneous 'element' text).
There is a small syntax error in your code. for better understanding, I have attached a fully functional code to meet your requirement.
Kindly refer the following code.
var partner = document.getElementById("partner");
var children = document.getElementById("children");
function calc() {
var val = 5;
if (partner.checked && !children.checked) {
val = 10;
} else if (!partner.checked && children.checked) {
val = 12;
} else if (partner.checked && children.checked) {
val = 20;
}
document.getElementById('Level1Price').innerHTML = val;
}
Partner: <input type="checkbox" id="partner" /> <br /> Children: <input type="checkbox" id="children" /> <br /> Level1 Price:
<span id="Level1Price"></span>
<br />
<button onClick="calc()">Calculate</button>
If still you find any issue or have any doubt feel free to comment, I will update my answer. TIA

Creating a simple mathematics game

I am new to the javascript developing world and I took it upon myself to create a small game that my fathers students will be able to play at school. This game consists of 4 different mathematical operations (Adding,Subtracting,Multiplication,Division). Once the student clicks on the operation button, they will then be transferred to a new page. This page will have numbers from 1 to 10. This number will be used as a static number. After the user selects this number, they will have 10 different problems to answer. The first number will be a random number from 1 to 12 and the second number will be the digit they selected on the page before. After completing the 10 problems, they will be greeted with a page that will inform them which questions they have missed. I have started the code for the addition part but I ran into several complications.
1) how do i transfer the answer from one function, to another? This will be used to check the input.
2) Will it be more intuitive to use a switch statement in order to select the operation & the static number?
3) Is there any other methods that would facilitate the making of this game?
I would like to thank you in advance and apologize for the long post. I am a bit lost and would love to get some kind of feedback.
var x;
function startAdd() {
var random = new Array();
for (var i = 0; i < 1; i++) {
random.push(Math.floor(Math.random() * 13));
// console.log(random[i]);
}
var allRadioButtons = document.getElementsByName("dif");
var secondNumber;
for (var i in allRadioButtons) {
if (allRadioButtons[i].checked) {
secondNumber = +allRadioButtons[i].value;
break;
}
}
for (var a = 0; a < 1; a++) {
document.getElementById('probFirst').innerHTML = random[a];
document.getElementById('probSecond').innerHTML = secondNumber;
/*
compareUser();
function compareUser(){
if (prob != )
} */
}
}
function myFunction() {
var x = document.getElementById("userNumb").value;
document.getElementById("Answer").innerHTML = x;
}
<title>RicoMath - Addition</title>
<body>
<h1>RicoMath</h1>
<h1 class="add">Addition</h1>
<h2>Difficulty</h2>
<div id="options">
<div>
<input id="num1" type="radio" name="dif" value="1">
<label for="num1">1</label>
</div>
<div>
<input id="num2" type="radio" name="dif" value="2">
<label for="num2">2</label>
</div>
<div>
<input id="num3" type="radio" name="dif" value="3" checked>
<label for="num3">3</label>
</div>
<div>
<input id="num4" type="radio" name="dif" value="4">
<label for="num4">4</label>
</div>
<div>
<input id="num5" type="radio" name="dif" value="5">
<label for="num5">5</label>
</div>
<button onclick="startAdd()">Begin!!!!</button>
<h4 id='probFirst'></h4>
<h4 id='probSecond'></h4>
</div>
<input type="number" id="userNumb" value="">
<button onclick='myFunction()'>Enter UserNumb</button>
<p id="Answer"></p>
</body>
1) To transfer the data to your next "page", the easy option for you would be to have seperate divs for seperate pages in the same html file. Then when you need to go the the "next page", just show the div you need to show and hide the others.
Here's a the html + pure javascript code for that with a working example:
<body>
<div id="page1" style="border-width:2px;border-style:solid">
your first page
<button onclick="showPage2()">Go to Page 2</button>
</div>
<div id="page2" style="border-width:2px;border-style:solid">
2nd page
</div>
<div id="page3">
3rd page
</div>
<script>
showPage1();
function hide(id){
document.getElementById(id).hidden = true;
}
function show(id){
document.getElementById(id).hidden = false;
}
function showPage1(){
show("page1");
hide("page2");
hide("page3");
}
function showPage2(){
show("page2");
hide("page1");
hide("page3");
}
</script>
</body>
Here's a working fiddle.
To transfer your value from the input, just use document.getElementById() since you are in the same html document.
2) To get the selected value from the radio button list, just use (as per your code):
var rates = document.getElementById('options').value;
You can use the same method to get the value from a input box. Please make sure you add a check for empty input and also to check if a radio button has been selected before getting the value.
I don't see any need to loop as you have done.
3) Definitely learn and use jquery. It will make your effort much less.
Hope this helps and happy coding!

Dynamic Form Builder

Main goal: I would like to create a dynamic form-building tool that allows the user to select certain options that, when chosen, enable subsequent inputs to occur.
An example of what I am describing:
Text Entry: Put in a Chapter Name.
Choose to add question
Choose Question type (mult. choice, check box, etc.)
Type in question.
Choose to add new question. If so, repeat ques. steps.
Choose to add new Chapter. If so, repeat add ques. options.
Submit whole content from above, and export (with the ultimate goal of being parsed/prepared into format for use, as per these guidelines (but that's for much later).
Example of what I have done so far: JS Fiddle
Note: Example is incomplete. Stopped because I realize I am building a mess and assume there is an easier/better way to do this.
Thanks in advance for any assistance that can be offered - I hope I was clear!
Kuan
Caveat: I am relatively new to programming/etc. That said, I feel I have searched quite a bit and there appears to be not much in regards to this specifically (the difficulty being primarily the nested nature of the questions, within the chapters).
JS Fiddle code:
<title>Dynamically build FT survey</title>
<script language="javascript">
function addChap(name) {
var element = document.createElement("li");
element.innerHTML = name;
var foo = document.getElementById("currentChapList");
//Append the element in page (in span).
foo.appendChild(element);
// Update drop down select lists
updateSelect();
}
function delChap() {
var foo = document.getElementById("currentChapList");
var allChildNodes = foo.childNodes;
var lastElem = allChildNodes.length - 1;
foo.removeChild(allChildNodes[lastElem]);
// Update drop down select lists
updateSelect();
}
function updateSelect() {
// First delete everything in the Chapter selection list
var currentChaps = document.getElementById("chapOptions");
var newFoo = document.getElementById("currentChapList");
for (i = 0; i < currentChaps.children.length; i++) {
currentChaps.remove(currentChaps.children[i]);
}
// Then re-add the remaining components from Chapter list
for (i = 0; i < newFoo.children.length; i++) {
nfCont = newFoo.children[i].innerHTML;
nfElem = document.createElement("option");
nfElem.innerHTML = nfCont;
currentChaps.appendChild(nfElem);
}
}
function addAns() {
//Create an input type dynamically.
var element = document.createElement("input");
var foo = document.getElementById("lastAns");
foo.appendChild(element);
}
function addQues() {
var allQues = document.getElementById("questionSubSect");
var newQues = document.createElement("div");
newQues.innerHTML = allQues.innerHTML;
//Append the element in page (in span).
allQues.appendChild(newQues);
}
</script>
</head>
<body>
<b>Current Chapter Index</b>
<br>
<ol id="currentChapList">
</ol>
<input type="text" style="width:400px" value="Enter Chapter Name" id="newChapName"/><br>
<input type="button" value="Add Chapter" onclick="addChap(newChapName.value)"/>
<input type="button" value="Delete Last Chapter" onclick="delChap()"/>
<br>
<br>
<b>Dynamically add element in form.</b>
<br>
Select the element and hit Add to add it in form.
<br>
<br>
<b>Chapter Builder</b>
<br>
<form>
Chapter Select:
<select id="chapOptions"></select>
<br>
<div id="questionSubSect">
<br>
Question ID:
<input type="text" style="width:400px" value="Enter Question"/>
<br>
Question:
<input type="text" style="width:400px" value="Enter Question"/>
<br>
Question Type:
<select name="element">
<option value="text">Checkbox</option>
<option value="text">Multiple Choice</option>
<option value="text">Open Text</option>
<option value="number">Open Number</option>
<option value="text">Ordered List</option>
<option value="image">Picture</option>
<option value="text">True or False</option>
</select>
<br>
Other open answer option:
<select name="element">
<option value="text">False</option>
<option value="text">True</option>
</select>
<br>
<br>
<span id="lastAns"></span>
<br>
<input type="button" value="Add Answer Option" onclick="addAns()"/>
<br>
<br>
</div>
<span id="lastQues"></span>
<input type="button" value="Add New Question" onclick="addQues()"/>
</form>
</body>
I have done some investigation about dynamic form. Here are some excellent open-source solutions. They usually do it in this way:
describe form structure as JSON in the backend.
then use one of the following libraries to render JSON to form in the frontend.
jsonform/jsonform
React JSONSchema Form (React) (demo)

Dynamically Update fields through Input field and dropdown

I'm trying to dynamically update a text field through an input field. This will then be linked to a dropdown selection with values. I also need to show a due date to show 30 days in advance from today's date.
Here is my HTML:
<div>
<label for="payment">Payment:</label>
<input type="text" name="amount" id="amount" onChange="myfunction()"/>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1">Fast</option>
<option value="2">Medium</option>
<option value="3">Slow</option>
</select>
</div>
<br />
<div>
Payment Breakdown: <br /><br />
Payment:
<div name="amount" id="amount"></div>
Freight:
<div name="delivery" id="delivery"></div>
Total Payment:
<div name="total" id="total"></div>
Due Date:
<div name="date" id="date"></div>
</div>
I'm struggling with the Javascript part though and fitting it all together.
I've gotten as far as this and now I'm stuck. (Not very far I know)
function myFunction()
{
var amount = document.getElementById("amount");
var delivery = parseInt($(this).find("option:selected").val());
total = amount + delivery
$("#total").html(total);
};
I've looked at examples on Stackoverflow and Google but nothing seems similar to what I'm trying to achieve. Although I know the answer is out there, I'm not sure if I'm asking the right question.
Cheers
I would change it to this. Here I have an updateCost() function which is called when the amount is changed or the delivery is changed. I also added code to handle the due date.
Remove the inline onchange event from the amount:
<input type="text" name="amount" id="amount"/>
Javascript:
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var total = amount + delivery
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
// handle the due date
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30);
var dateStr = todayPlus30.getDate() + "/" + (todayPlus30.getMonth()+1) + "/" + todayPlus30.getFullYear();
$('#date').html(dateStr);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
Your original code has a few problems:
The wrong case on the inline function call
The use of this within the function when this is not actually any of your elements (you didn't pass it as an argument).
The use of amount in the calculation when amount is an input element, not a value.
From a usability point of view, it would only try to update when the amount is changed, I think it would be better to update on both change of the amount and delivery.

Dynamic Drop Down that changes Text Box value issue?

Alright, I am going to try to ask this clearly as I can.
I am creating a drop-down menu that will upon selection of an option show:
Shipping Total dynamically update for User Experience
Change the 'value="CHANGETHISINFORMATION"' value in the textbox dynamically
Here is where my code is at:
// Pre populated array of data
var myData = new Array();
myData[''] = '';
myData['Light Oak 6" x 6" Set|65.05|0606'] = '$50.00';
var setTotal = new Array();
setTotal[''] = '';
setTotal['Light Oak 6" x 6" Set|65.05|0606'] = '15.00';
document.setSelect.selector.onchange = updateText;
function updateText() {
var obj_sel = document.setSelect.selector;
var shipTot = document.setSelect.shippingTotal.value;
var totTot = document.setSelect.setTotal.value;
shipTot = myData[obj_sel.value];
totTot = ("item-AI SWDO|" + (myData[obj_sel.value] + setTotal[obj_sel.value]) + "|SoftWoods - Dark Oak|NA|0");
}​
HTML:
<h1>Dark Oak</h1>
<br>
<form action="/qs3/cart.php" method="get" onSubmit="return doOptionCheck(this);" id="setSelect" name="setSelect">
<select id="selector" name="OPTION|1|AI SWDO">
<option value="" selected>Choose your set size</option>
<option value='Light Oak 6" x 6" Set|65.05|0606'>
6' x 6' Set - $65.05
</option>
</select>
<br><br>
Shipping Estimate: <input type="text" value="" id="shippingTotal" name="shippingTotal" disabled>
<br><br>
QTY: <input type="text" name="item-AI SWDO|CHANGETHISINFORMATION|SoftWoods - Dark Oak|NA|0" id="setTotal" size="3" value="1">
<input type="submit" name="add_to_cart2" value="Add to Cart!">
</form>​​​​​​​​​​​​
Now this cart is archaic to say the least. Perl with other script engines were used. So I am having to make due until we upgrade our site to a better cart.
I was able to originally* make the shipping box value physically change, it was only after I tried toying with the inner-value on the 'Qty:' box that made things stop working.
EDIT: Fixed my last sentence.
Can't you use datatable for this? http://www.datatables.net/ If I understand correctly, you want some element to update the total/shipping price?
Not sure why you want to change an element name field...

Categories