Display image on radio select and add price - javascript

im trying to select club and display image and return price using radio buttons.
Im stuck because I cannot get the pictures to display. any ideas what could i add?
<label>Select Club:</label><br>
<UL>
<label class="radiolabel"><input type="radio" name="SelectedJersy" value="MUFC" onclick="displayJersy()"> MUFC-(15€)</label><br>
<label class="radiolabel"><input type="radio" name="SelectedJersy" value="MCFC" onclick="displayJersy()"> MCFC-(20€)</label><br>
</UL>
<div id='jersy'></div>
<script type="text/javascript">
var img_Jersy = new Array();
img_Jersy["MUFC"]= "<img src='data/images/MUFC.png'>";
img_Jersy["MCFC"]= "<img src='data/images/MCFC.png'>";
var jersy_prices = new Array();
jersy_prices["MUFC"]=15;
jersy_prices["MCFC"]=10;
function displayJersy()
{
var jersyPrice=0;
var theForm = document.forms["tshirtform"];
var selectJersy = theForm.elements["SelectedJersy"];
for(var i = 0; i < selectJersy.length; i++)
{
//if the radio button is checked
if(selectJersy[i].checked)
{
jersyPrice = jersy_prices[selectJersy[i].value];
//imgJersy = img_Jersy[selectJesry[i].value];
imgJersy = img_Jersy[selectJesry[i].value];
document.getElementById("jersy").innerHTML =imgJersy;
document.getElementById('jersy').style.visibility="visible";
break;
}
return jersyPrice;
}
</script>

I see a couple issues. You forgot a closing curly brace in your for loop.
There's a typo here:
imgJersy = img_Jersy[**selectJesry**[i].value];
Anyway, here's a working version: http://jsfiddle.net/z92togqd/2/

Related

Display selected checkbox values in an HTML using javascript/ google script

I created a Select Element which creates Checkbox dropdown elements based on the items on the Google sheet.
Here is my HTML code:
<div class="form-row">
<div class="multiselect form-group">
<div class="selectBox" onclick="showCheckboxes()">
<select class="form-control" >
<option>Select an option</option>
</select>
<div class="overSelect" ></div>
</div>
<div id="checkboxes">
</div>
</div>
Here is my javascript code:
<script>
document.addEventListener("DOMContentLoaded", afterLoad);
document.getElementById("checkboxes").addEventListener("change", loadDisplayPos);
function afterLoad(){
google.script.run.withSuccessHandler(loadPosApp).checkPosApp();
}
function loadPosApp(postOpen){
postOpen.forEach(function(r){
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = r[0];
var label = document.createElement('label')
label.appendChild(checkbox);
label.appendChild(document.createTextNode(" " + r[0]));
var content = document.getElementById('checkboxes');
content .appendChild(label);
});
}
function loadDisplayPos(){
var contentCheck = document.getElementById('checkboxes').value;
console.log(contentCheck);
}
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
</script>
Here is my Google Apps Script function:
function checkPosApp()
{
const ss = SpreadsheetApp.openByUrl(url);
const ws = ss.getSheetByName("VacantPositions_Data");
//const myDates = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
var postOpen = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
Logger.log(postOpen)
return postOpen;
}
Upon the load of the Web App, it will load the values from the Google sheet to the Web App as dropdown checkboxes. My problem is how to display the checked items to the Select Element as selected. I tried to get the value of the element ID "checkboxes" but it says undefined. Do you have any suggestions or advice? I am still trying to look for a solution. Thank you in advance for the help.
I got the idea on how to answer my problem in this link: https://www.dyn-web.com/tutorials/forms/checkbox/group.php. I just modified it in a way that I could get all the checked/ selected in an array then display it in the Web App
Here is the modified function in javascript.
function loadDisplayPos(){
var element = document.getElementById('checkboxes');
var tops = element.getElementsByTagName('input');
var tags = [];
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
if (tops[i].checked){
tags.push( tops[i].value);
}
}
}
var selectedPost = document.getElementById('posapp').innerHTML= tags;
}

How do I use getElementById on dynamically created inputs?

I'm having a some trouble getting the state of dynamically created checkboxes. I used the code below to add several checkboxes, with dynamic Id's, to the body.
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
html +=
`
<label class="checkbox" [attr.for]="'myCheckboxId' + i">
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
In another part of the code, I would like to get and/or set the state of the checkboxes but havent succeeded so far. I tried using the code below to achieve my goals, but "document.getElementById(...)" keeps returning "null".
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById("'myCheckboxId' + i").checked);
}
As you can see, I'd like to save the checkbox states in an array and use it, to reset the new states to the old ones (for example when a button is pushed).
So how should I be adding the states to this buffer array? What am I doing wrong in the code above? Tried several other things but none of those worked.
It looks like you just have a simple error in your code. What you're trying to do is something to the affect of:
id=myCheckboxName1
id=myCheckboxName2
id=myCheckboxName3
...
However, your code is not correct:
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
It's interpreting the entire id as a string and not inserting the numeric value so it looks like this: myCheckboxIdi
Perhaps try the following:
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
var checkboxId = `myCheckboxId${i}`;
html +=
`
<label class="checkbox" [attr.for]=${checkboxId}>
<input class="checkbox__input" type="checkbox" [name]=${checkboxId} [id]=${checkboxId}>
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
Notice how the value is now inserted in the string via the template string? This should work, but I didn't run it so it may need some modification. Your new code for accessing would be something like:
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById(`myCheckboxId${i}`).checked);
}
Something to this affect should fix your code. Let me know if you need more clarification.
Okay so I found a solution. Apparently you can't use getElementById(checkboxId) to get the checkbox states. You have to create an array using getElementsByTagName("input") and afterwards itterate through this array while checking for inputs of the checkbox type.
var inputsArray = document.getElementsByTagName("input");
var ckbStateBuffer = new Array();
for (var i = 0; i < 3; i++)
{
if(inputsArray[i].type == "checkbox")
{
ckbStateBuffer.push(inputsArray[i].checked);
}
}
JSFiddle here: https://jsfiddle.net/Maximo40000/agL9opq6/
A big thanks to Jarred Parr!

can't get radio buttons to appear on page

I need to make a group of 2 radio buttons in my javascript for my web app. So far I have this code:
//radio buttons start
var AddRadio = function(options){
var _dom_element = document.createElement("radio");
for ( var i = 0; i < options.length; i++ ) {
var _option = document.createElement("radio");
_option.value = options[i];
_option.innerHTML = options[i];
_dom_element.appendChild(_option);
};
this.getDomElement = function() {
return _dom_element;
}
}
//radio buttons end
var _temp_radio = new AddRadio(['Max Temp', 'Min Temp']);
container_element.appendChild(_temp_radio.getDomElement());
The problem is that only the 'Max Temp' and 'Min Temp' strings show up, the actual radio buttons are not there. Thanks If you can help in any way.
radio buttons are
<input type="radio">.
You are creating a
<radio>
tag instead.
Use an <input type="radio"/> tag.
e.g.
var option = document.createElement('input');
option.type = 'radio';
http://www.w3schools.com/html/html_forms.asp

storing user input in array

I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.

Multiple checkbox can't access from JavaScript function

I have dynamic multiple check boxes which is used to restore multiple files. It works perfectly when I have more than 1 check boxes. Here is my php code for check boxes:
<form name="RestoreFile">
<input type="checkbox" title="'.$FldDoc['FldDocumentName'].'" name="restore_checkbox" value="'.$FldDoc['FldDocumentID'].'" id="restore_'.$NodeId.'_'.$FldDoc['FldDocumentID'].'"/>
<input type="button" value="Restore" onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);" />
</form>
And the definition of function RestoreDocFile() is given below:
function getSelected(opt)
{
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].checked)
{
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function RestoreDocFile(nodeid, opt)
{
var getSelectDocIds = getSelected(opt);
//alert(nodeid+','+getSelectDocIds);
var strSelectedDocIds = "";
var i=0;
for (var item in getSelectDocIds)
{
if(i!=0)
{
strSelectedDocIds+=":";
}
strSelectedDocIds += getSelectDocIds[item].value ;
i++;
}
}
The problem is that if there has 1 checkbox at the time of form load it doesn't work properly.
Try replacing
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);"
with
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.getElementsByName(\'restore_checkbox\'));"
This will ensure you get a NodeList regardless of how many checkboxes there are.

Categories

Resources