Display textbox due selected option, and add new divs --jQuery - javascript

I have articles that I want to get recorded. Each article has mutliple references (up to 100), and a reference might be a book or an article.
If a reference is a book, I have to get author name, page number etc.
If it is an article, then I have to get published journal, year etc. (there are differences).
So, I want to let the user select if it is an article or a book from a dropdown menu. Then related textboxes have to come visible. The user fills in related information and reference 1 is ok.
But, because when a reference number is unknown, and might be 10-20-30 etc., I have to add a add button, when reference 1 information is done, reference 2 have to be displayed.
If the add button is clicked first, the very same selection menu appears and related to that selection a new textbox become visible, and so on...
Here is a little jquery for displaying textboxes after selected option:
$(function() {
//This hides all initial textboxes
$('label').hide();
$('#sel').change(function() {
//This saves some time by caching the jquery value
var val = $(this).val();
//this hides any boxes that the previous selection might have left open
$('label').hide();
//This just opens the ones we want based off the selection
switch (val){
case 'option1':
case 'option4':
case 'other':
$('#label1').show();
break;
case 'option2':
$('#label1').show();
$('#label2').show();
$('#label3').show();
break;
case 'option3':
$('#label1').show();
$('#label2').show();
break; }
});
And this is for adding new div's:
<script type="text/javascript">
var initial=0;
function addReference(){
var newDiv= addNewDiv();
var htcontents="";
document.getElementById(newDiv).innerHTML=htcontents;
}
function addNewDiv(){
initial=initial+1;
var ni = document.getElementById('area');
var newdiv=document.createElement('div');
var divIdName = 'Div #' +initial;
newdiv.setAttribute('id', divIdName);
ni.appendChild(newdiv);
return divIdName;
}
</script>
Of course htcontents is filled with html form.
How to do that efficiently?
Thanks very much in advance.

Related

Swap Divs then swap selected option value between two select lists

The Problem:
Before I began adding the div swaps, I could only type into the left (from_value) input and the result of the calculations would be applied via ajax to the right (to_value) input.
I would like to allow the user to type into either box and have the results display in the opposite box they're typing in.
What I am doing to make this happen:
I am swapping the left div with the right div on mouseover of the to_value input. Here's the code i'm using to do the swap:
$.fn.swapWith = function (that) {
var $this = this;
var $that = $(that);
// create temporary placeholder
var $temp = $("<div>");
// 3-step swap
$this.before($temp);
$that.before($this);
$temp.after($that).remove();
return $this;
};
var leftSide = $('#left-side');
var rightSide = $('#right-side');
$('#to_value_input').on('mouseover', function () {
$(rightSide).swapWith(leftSide);
});
This effectively swaps the divs, bringing along with it ids and names of the inputs which retains functionality of my server-side script to perform calculations. As expected, the from_unit select list and to_unit select list are swapped and their values / displayed text are also swapped from one side to the other.
I would like to swap the values and text of the two select boxes either directly before or more likely, directly after the div swap so it appears as if nothing changed on screen.
Similar questions that I have reviewed:
How to swap values in select lists with jquery?
How to swap selected option in 2 select elements?
I have tried several variations of each of the provided solutions. This seems like it should be a fairly simple thing to do but I find myself stuck. Any further help would be greatly appreciated.
The full code base is available on github if you need to see it: https://github.com/pschudar/measurement-conversion
I have made minor changes to the code hosted there to accommodate the div swaps.

How to use Javascript to click on an html item (A spreadsheet text box?) that has a different ID each time you click?

I am a teacher with the worst possible slow gradebook, so much so that I would like to use some code to automate it. Basically to submit a grade I need to:
Find the cell box and click on it once to show the submit button
Then click on the button
HOWEVER: Every time you click on the box or button it gives it a new html ID. Therefore I need some code that looks for all the boxes and buttons and hits them. I am not sure how to do this without a static ID.
My code is most definitely formatted improperly, I am a total beginner.
var selectorBox = ['name_of_cell']
var selectorCollection = ['name_of_button']
selectorBox.forEach((s) =>{
let element = document.querySelector(s);
if(element) element.click();
else console.warn('No element found for the supplied selector:', s);
});
selectorCollection.forEach((s) =>{
let element = document.querySelector(s);
if(element) element.click();
else console.warn('no element found for the supplied selector:', s);
});
I need help:
Reformatting to the proper syntax / spacing etc.
Writing a function that finds and clicks on the box THEN the button (the above works).
Making my code look for the boxes then buttons, however as mentioned above the ID for each box and button switches every time you click on one, and for each different class i have (I have about 400 students.)
If you can select cells/buttons by class, you can loop through all cells, "click" them, and then "click" the button once it appears.
var cells = document.querySelectorAll('.x-grid-cell');
cells.foreach((cell) => {
cell.click();
var button = document.querySelector('.class_of_your_button')
button.click()
})

How to accumulate a score/value based on the choices selected on a form using jQuery

I wanna to try to researching around on how to achieve this but I am not sure about how to make the solution for this.
Basically I have a form that contains some select list, radio buttons, and checkboxes. Each option on the form has a corresponding numeric value that will be accumulated and displayed to the user when the form gets submitted.
What I am not sure about is how to be able to add or deduct a value if the user chooses to change the a choice on the form.
For example, when a user is on the first dropdown element, and they choose option 2 which has a value of 5 then the current accummulated value us 5. Then on question 2, they choose option 1 which has a value of 2 which makes the accummulated value 7. Then the user changes the answer for question one from option 2 to option one which means 5 will be deducted from the accumulated value and 2 will be added since it is the value for option 1 which changes the accumulated value to 4.
I know the description I mentioned might be all over the place but I hope it makes sense.
I am trying to use jQuery and so far, my approach would be to check if any of the form element's value has changed:
(function($) {
var score = 0;
$(".the-form #step-5 :input").change(function() {
console.log($(this).val());
});
})(jQuery);
But I can't seem to figure out how to get the previous value of the option that was selected if the user changes their answer.
Any suggestion would be appreciated.
Can you recalculate across the whole form each time the user changes any of the elements?
$(".the-form :input").change(calculateChanges);
function calculateChanges() {
// Retrieve the current values of all elements and add them together
}
When a user submits, then start doing the calculations or when a select is changed, i.e. attach it to the event. Score is now a local variable
function calcValue() {
var score = 0;
//select all the elements using example below
$(".the-form :input").each(function( index ) {
//i forgot jQuery exact syntax but $(this).val or //$(this).val()
score += $( this ).val();
});
console.log(score);
}
In this case you can attach it to the submit
function submit() {
var score = calcValue();
}
Or you can put it in a change event of a select
function selectChanged() {
var score = calcValue();
}

On click, I need the button to hide and a hidden div to appear

I'm attempting to recreate the form located here: http://yeticustomshop.com/get-quote (PLEASE look at this for reference)
Needed user experience:
Select Product, product selection is replaced by table showing
product selection name, checkbox, and quantity selector.
Option to add another product. If clicked, button disappears and the
product selection is shown BELOW the table. Then the process is
repeated, adding new selections to table.
The ability to remove previously selected items.
Here's the fiddle
// Get all the product radio buttons and loop them
var products = document.getElementsByName('product');
for (var i = products.length; i--;) {
// add an event listener to do stuff when one of them is clicked
products[i].addEventListener("click", function() {
// get the value of the clicked button
var cup = this.value;
// put the value in the input box
document.getElementById('yourSelection').value = cup;
// hide the radio buttons and show the table
document.getElementById("cupDesc").style.display = "block";
document.getElementById("addProductBtn").style.display = "block";
document.getElementById("cupSelect").style.display = "none";
});
}
Here's my previous post on here
Side note: This process is being used in a form. I'm wondering if it would be possible and easier to almost make it like a shopping cart. I've downloaded simplecart.js, but Javascript is NOT my strong-suit. Please help.

Hide an option in a dropdown menu, when a specific option has been selected in another menu

I'm stuck right now on the following problem:
I have 2 dropdown menus next to each other, that both offer the same options to choose from (users can choose their travel route by choosing their point of departure and their destination).
The items on these dropdown menus are taken from a table in my database.
I want to achieve the following:
Locations "A", "B" and "C" are choosable as start or destination. When a user chooses "B" as point of departure (in the 1st dropdown menu), this option should not be shown anymore in the 2nd dropdown menu (destination). (EDIT: But it should reappear, when another option is selected in the 1st dropdown)
Same with "A" and "C" of course.
The code I use right now to fill the dropdown menus is:
<select name="anfang">
<?php
$sql = "SELECT * FROM orte";
$result = mysqli_query($dblogin,$sql);
while($zeilestart=mysqli_fetch_array($result))
{
include("includes/database.php");
$ortname=$zeilestart['name'];
$ortkurz=$zeilestart['kurz'];
echo "<option value=\"$ortkurz\">";
echo $ortname;
echo "</option>";
}
?>
</select>
This is the code for the 1st dropdown menu (start), the code for the 2nd menu is pretty much the same.
I assume that some JavaScript-code can solve my problem, but I don't really know how to do it... Can anyone help me? :)
Thanks and kind regards
weheri
The following code should be easy to understand - it basically queries the DOM for the first dropdown list's select element and the second dropdown lists' options elements. It attaches an event handler to the onchange event of the first select, so that whenever its value changes, the handler function is called to check all the options on the second select against the selected value. If the value matches, it sets a disabled attribute on the option, otherwise if the option has a disabled attribute (from a previous selection), it removes it.
You can add this to your page before the closing body tag, changing secondSelect to the name of your second dropdown.
<script>
var select1 = document.querySelector('select[name="anfang"]'),
secondList= document.querySelectorAll('select[name="secondSelect"] option');
select1.onchange = function(){
var selected = this.value;
for(var i=0;i<secondList.length;i++){
if(secondList[i].value==selected)
secondList[i].setAttribute('disabled',true);
else if(secondList[i].getAttribute('disabled'))
secondList[i].removeAttribute('disabled');
}
}
</script>
If you would like to hide the element altogether (instead of disabling it), you can to use the style attribute instead of disabled:
<script>
var select1 = document.querySelector('select[name="anfang"]'),
secondList= document.querySelectorAll('select[name="secondSelect"] option');
select1.onchange = function(){
var selected = this.value;
for(var i=0;i<secondList.length;i++){
if(secondList[i].value==selected)
secondList[i].style.display = "none";
else if(secondList[i].style.display == "none")
secondList[i].removeAttribute('style');
}
}
</script>
I was writing the code when I saw this already have been answered, but here is my contribution (full code example, using a php array to get the data from instead of a mysqli object/array)
http://pastebin.com/0J31FK15

Categories