I have this HTML/Javascript code and I want to be able to print the product of a function inside the body of my code. Here is my code:
<form>
<div class="answer1wrap">
<label>Select your top champion:</label>
<select id="topSelect">
<option value="void">Select a champion</option>
<option value="aatrox">Aatrox</option>
<option value="ahri">Ahri</option>
<option value="akali">Akali</option>
</select>
</div>
</form>
<button class="btn btn-default" id="checkbtn" onclick="topAnswer();" type="button"><span class="glyphicon glyphicon-check"></span> Calculate Win Chance</button>
The JavaScript I have is this:
< script >
function topAnswer() {
var element = document.getElementById("topSelect");
var elementValue = element.value;
if (elementValue == "aatrox") {
document.write("You selected Aatrox for your teams top lane champion");
}
}
< /script>
If you select "Aatrox" it executes the document.write and prints what I want it to. But I don't want to to overwrite everything. What do I use to make my message appear after the "The top champion you selected is" line.
Here is a jsbin of the console: http://jsbin.com/eSiveyU/2/
Thanks
You have to create an additional DOM element and put the result value there. Quick example: http://jsbin.com/OkERuQeJ/1
document.getElementById("selectionResult").innerHTML = elementValue;
This might help you. http://jsfiddle.net/KPz6X/embedded/result/
I have created a div which will display your result below your button. No need to use document.write(). You can simple use the text() method of jQuery to modify the text of the div.
HTML
<form>
<div class="answer1wrap">
<label>Select your top champion:</label>
<select id="topSelect">
<option value="void">Select a champion</option>
<option value="aatrox">Aatrox</option>
<option value="ahri">Ahri</option>
<option value="akali">Akali</option>
</select>
</div>
</form>
<button class="btn btn-default" id="checkbtn" type="button"><span class="glyphicon glyphicon-check"></span> Calculate Win Chance</button>
<div class="display">
<p>The top champion you selected is: </p>
</div>
jQuery
$(document).ready(function(){
$(".btn-default").on('click', function () {
if ($("#topSelect").val() == "aatrox") {
$(".display p").text("You selected Aatrox for your teams top lane champion.");
}
});
});
You can store the message 'The top champion you selected is:' in variable once and concate it with selected option and display it in result box. The code would be for this.
function topAnswer(){
var element = document.getElementById("topSelect");
var elementValue = element.value;
if(elementValue == "aatrox"){
var div = document.getElementsByClassName('display')[0];
var ptag = div.getElementsByTagName('p')[0];
if(typeof greeting == 'undefined'){
greeting = ptag.innerHTML;
}
ptag.innerHTML = greeting + elementValue;
}
}
document.getElementById('checkbtn').addEventListener('click', topAnswer);
Here is the Demo.
Hey FYI your question does not contain all the HTML, making it very confusing. Thankfully the jsbin does.
I don't think document.write() is the right way, because of this:
Why is document.write considered a "bad practice"?
First, you need to wrap "The top champion you selected is:" in a span with an id.
<span id='bottomText'>The top champion you selected is:</span>
If you want to use pure JavaScript, here is what to do:
http://jsbin.com/EzUNuTUy/1/edit
Taken from here: How to do insert After() in JavaScript without using a library?
<script>
//This function will insert a node after an element
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function topAnswer(){
var element = document.getElementById("topSelect");
var elementValue = element.value;
if(elementValue == "aatrox"){
var el = document.createElement("span");
el.innerHTML = "You selected Aatrox for your teams top lane champion.";
var div = document.getElementById("bottomText");
insertAfter(div, el);
}
}
</script>
If you want to use jQuery, it is really easy:
<script>
function topAnswer(){
var element = document.getElementById("topSelect");
var elementValue = element.value;
if(elementValue == "aatrox"){
$("You selected Aatrox for your teams top lane champion.").insertAfter($("#bottomText"));
}
}
</script>
You seem to be new to HTML/JavaScript, I would definitely recommend learning a library like jQuery. It will make your life much easier.
Related
I asked about this previously but failed to provide enough detail so I thought I'd give credit where it's due (the responses were excellent, but didn't answer my issue because I'd failed to provide enough information) and start over.
So I have this pair of modals; one that accepts a text input, and one that gets input out of a dropdown selection, in google sheets and scripts (see hyperlinks) that is supposed to provide a different descriptive paragraph depending on which which selection the user has made from a dropdown step. Currently it just shows a single paragraph that doesn't change depending on selection. I want it to:
show id='PUBLIC' paragraph when Public is selected, show id='INTERNAL' when internal is selected. Etc. Etc.
Save their selection and send it to be pasted it where it's needed.
function AddValuesFromModal(selectValue) {
var documentId = SpreadsheetApp.getActiveSpreadsheet().getId();
console.log("Getting document log...");
var infoSheet = SpreadsheetApp.getActive().getSheetByName('Information Control')
console.log("Got document!");
console.log("Selected value: " + selectValue);
console.log("Start setting value....");
infoSheet.getRange('C4').setValue(selectValue);
console.log("Value has been set!");
}
function myFunk() {
// Display a dialog box for each field you need information for.
var documentProperties = PropertiesService.getDocumentProperties();
var ui = SpreadsheetApp.getUi();
//var response = ui.prompt('Enter Name', 'Enter owners person's name', ui.ButtonSet.OK);
var nameResponse = ui.prompt("Enter the name of the document OWNER");
var salesperson = nameResponse.getResponseText();
var documentProperties = PropertiesService.getDocumentProperties();
var infoSheet = SpreadsheetApp.getActive().getSheetByName('Information Control')
var date = new Date();
var htmlDlg = HtmlService.createHtmlOutputFromFile("HTML_myHtml")
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
var modal = SpreadsheetApp.getUi();
modal.showModalDialog(htmlDlg, "Document Classification");
//Get Current Document ID
var documentId = SpreadsheetApp.getActiveSpreadsheet().getId();
console.log(documentId);
//Get the document body as a variable
var body = SpreadsheetApp.openById(documentId).getDataRange().getValues();
console.log(body);
//Insert the entries into the document
infoSheet.getRange('C5').setValue(salesperson);
infoSheet.getRange('C8').setValue(date);
}
<form id="docType">
<select id="selectDocumentType" name="documentClass" onchange='CheckSelect(this.value);'>
<option value="PUBLIC">Public</option>
<option value="INTERNAL">Internal</option>
<option value="CONFIDENTIAL">Confidential</option>
<option value="SECRET">Secret</option>
</select>
<body>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:block;" class="light work"
id="Choose" >Please Choose any one</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="PUBLIC" >Wizard Is working</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="INTERNAL" >Wizard Is Twerking</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="CONFIDENTIAL" >Wizard Is Laughing</p>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;display:none;" class="light work"
id="SECRET" >Wizard Is Eating</p>
</body>
<hr/>
<input type="button" onClick="formSubmit();" value="Submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function HideAll(val)
{
var all = document.getElementsByClassName(val);
for(var i =0; i<all.length; i++)
all[i].style.display = 'none';
}
function CheckSelect(val){
HideAll('work');
document.getElementById(val).style.display='block';
}
function formSubmit(){
Submit();
}
function Submit() {
var selectedValue = $('#selectDocumentType').val();
console.log(selectedValue);
google.script.run
.withSuccessHandler(closeIt)
.AddValuesFromModal(selectedValue);
};
function closeIt(){
google.script.host.close();
};
</script>
I updated the script. "CheckColors" should have been "CheckSelect". Bad version control facepalm.
I'm looking at this fiddle: http://jsfiddle.net/npH8X/
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
addBox = function(){
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
anybody have javascript example like it, but showing exactly how I might give each of those boxes its own id either at its creation or right afterwards while I'm at it?
I want to create a writer's tool where they can type info into each box and then port all the inputs into one larger container afterwards, so the boxes need ids to do that...
thanks
All you need to do is set the .id property of the textbox after it is created, but before it is inserted to the DOM. This can correspond to a variable, and automatically increment based off of it:
var count = 3; // Corresponding to the existing textbox count
addBox = function() {
var textBox = document.createElement("textarea");
count++;
textBox.id = count;
document.getElementById("parent").appendChild(textBox);
console.log("New element's ID: " + textBox.id);
}
<div id='parent'>
<textarea id="1">txt1</textarea>
<textarea id="2">txt2</textarea>
<textarea id="3">txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
However, note that you don't need to give your <textarea> elements IDs in order to be able to target them. You use document.querySelectorAll() to return a collection of all textboxes, including those that have been dynamically created:
addBox = function() {
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
checkBoxes = function() {
console.log(document.querySelectorAll("#parent textarea"));
}
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
<button onClick="checkBoxes()">check boxes</button>
Hope this helps! :)
Comment Answer:
.querySelectorAll() simply returns a node list of all of the <textarea> elements. As such, you can access the fourth element with 3 as an index (as it starts from 0). document.querySelectorAll("#parent textarea")[3] corresponds to the fourth <textarea>, and you can retrieve its contents with the .value property:
addBox = function() {
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
var box4content;
getBox4 = function() {
if(document.querySelectorAll("#parent textarea")[3]) {
box4content = document.querySelectorAll("#parent textarea")[3].value;
}
console.log("The variable `box4content` has the value: " + box4content);
}
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
<button onClick="getBox4()">get box 4</button>
I am trying to build a search that uses multiple drop downs. The script for the search uses the values for the first drop down and the second drop down. It works correct for Acura and MDX, but if I choose RLX it still passes MDX to the search as the value.
I know I have so somehow set for the value for the appended option to be whatever array is chosen in the second drop down, but I have had no luck. I am new to javascript so for all I know there may be a way easier than this to accomplish my goal.
FORM FOR SUBMIT
<form name="searchform" onSubmit="return dosearch();">
Brand:
<select id="brands">
<option val="Acura">Acura</option>
<option val="Chrysler">Chrysler</option>
</select>
<select id="item">
</select>
<input type="submit" value="Submit">
</form>
SCRIPT FOR URL STARTING WITH A BASE URL
<script type="text/javascript">
function dosearch() {
var sf=document.searchform;
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
location.href = baseUrl.concat('make='+ sf.brands.options[sf.brands.selectedIndex].value + '&&&&' + 'model=' + sf.item.options[sf.brands.selectedIndex].value + '&&&&' );
return false;
}
SCRIPT FOR DROP DOWNS
// JavaScript Document
$(document).ready(function(){
Acura=new Array("MDX","RLX","ILX","TLX");
Chrysler=new Array('200','3000','Town&Country');
populateSelect();
$(function() {
$('#brands').change(function(){
populateSelect();
});
});
function populateSelect(){
cat=$('#brands').val();
$('#item').html('');
eval(cat).forEach(function(t) {
$('#item').append('<option val="">'+t+'</option>');
});
}
});
Wow wow!
Please read some code style for js. If it works it doesnt mean that it's good.
DO NOT USE eval, EVER! eval = evil
You forgetting var declaration.
Inline handler in html bad practice too.
forEach will break in IE <= 8
concat is good, plus is good too
... lot of mistakes, that will cost you after.
I`ve wrote you a one liner, but it doesnt have structure. Just some ideas and removed a lot of things.
http://jsfiddle.net/gwEP5/
Whole js code:
$(function (){
// Selector
var $form = $("#searchform");
// it could be hashchange in the future
var setPath = function (url) {
window.location = url;
};
var searchHandler = function (e) {
e.preventDefault();
// You can serialize whole form just by .serialize
var url = window.location.pathname + "?" + $form.serialize();
setPath(url);
};
// Handlers, set handlers in js not in DOM, inline delegation is really nasty
// alias for .submit
$form.on("submit", searchHandler);
// Form elements
var $brands = $('#brands'),
$item = $("#item");
// Items list, dont use new Array or String. It`s good way in
var items = {
"Acura": ["MDX","RLX","ILX","TLX"],
"Chrysler": ['200','3000','Town&Country']
};
// eval is EVIL !!!! don`t use it ever
var populateItems = function () {
var elements = "",
value = $brands.val();
if (items[value] != null) {
$.each(items[value], function (i, item) {
elements += "<option value=\"" + item + "\">" + item + "</option>";
});
}
$item.html(elements);
}
// Alias .change
$brands.on("change", populateItems);
// init for start
populateItems();
});
Html form:
<form name="searchform" id="searchform">
Brand:
<select id="brands" name="make">
<option value="Acura">Acura</option>
<option value="Chrysler">Chrysler</option>
</select>
<select id="item" name="model">
</select>
<input type="submit" value="Submit"/>
</form>
The setup itself is fine. However, you have a typo:
sf.item.options[sf.brands.selectedIndex]
Should be:
sf.item.options[sf.item.selectedIndex]
Or, if you prefer the more aesthetic jQuery:
function dosearch() {
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
var brand = $('#brands').find(":selected").text();
var item = $('#item').find(":selected").text();
location.href = baseUrl + 'make=' + brand + '&&&&' + 'model=' + item + '&&&&';
return false;
}
I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.
I've created a madlib style paragraph with multiple drop-down selections for synonyms of various words. Here's an example:
<p id="the-text">This is an example paragraph containing many
<select class="selector">
<option>selections</option>
<option>dropdown thingies</option>
<option>option choosers</option>
</select>that I would like to be able to
<select class="selector">
<option>click on</option>
<option>select</option>
<option>choose</option>
</select>and then know what the
<select class="selector">
<option>final</option>
<option>selected</option>
<option>variable</option>
</select>paragraph text is.
<select class="selector">
<option>It would be great</option>
<option>It would be nice</option>
<option>It'd be delightful</option>
</select>, and
<select class="selector">
<option>useful</option>
<option>helpful</option>
<option>interesting</option>
</select>to dynamically create paragraphs like this.</p>
<textarea id="text-area" rows="4" cols="110">This is where the text should appear...
</textarea>
Here is a live example: http://jsfiddle.net/T4guG/2/
Using jQuery and Javascript, I am trying to get the selected (and surrounding) text to appear in the text area.
It's kind of working, but there are two problems:
1) SOLVED: There was a problem with punctuation, but replacing:
if (element == "{") {
content_array[i] = foo[j];
j++;
}
with
if (element.indexOf('{') >= 0) {
content_array[i] = foo[j];
j++;
}
allows { to be detected consistently
2) SOLVED: you only can change the options once.
Is there a more elegant solution than what I have come up with? Here is the code:
function updateTextArea() {
//get all of the text selections, and put them in an array
var foo = [];
$('.selector :selected').each(function (i, selected) {
foo[i] = $(selected).text();
});
//get the paragraph content, and store it
var safe_content = $('#the-text').html();
//delete all the options
$('.selector').text('');
//get the text without the dropdown options
var content = $('#the-text').html();
//create a regex expression to detect the remaining drop-down code
var pattern = "<select class=\"selector\"></select>",
re = new RegExp(pattern, "g");
//replace all the drop-down selections with {
content = content.replace(re, "{");
//turn the content into an array
content_array = content.split(" ");
//go through the array, and if a element is {, go to "foo" and replace it with the selected option
var length = content_array.length,
element = null;
var j = 0;
for (var i = 0; i < length; i++) {
element = content_array[i];
if (element == "{") {
content_array[i] = foo[j];
j++;
}
}
//turn the array back into a paragraph
new_content = content_array.join(" ");
//replace the text with the origionanl text
$('#the-text').html(safe_content);
//put the new content into the text area
$('#text-area').val(new_content);
}
$(document).ready(function () {
updateTextArea();
});
$(".selector").change(function () {
updateTextArea();
});
You are splitting text based on " " (using space) and replacing element { with array value but text is. {, and contains comma i.e., {, is not equal to {. Add space after element {. This solves your first problem.
As you are removing and adding select options dynamically in function updateTextArea(). You have to use .on() to attach event handler for dynamically created elements.
Try:
$( document ).on("change",".selector",function() {
updateTextArea();
});
Instead of
$(".selector").change(function () {
updateTextArea();
});
DEMO FIDDLE