How do I use HTML/Javascript radio buttons to prompt specific downloads? - javascript

I'm trying to let users choose from five radio buttons that link to a separate file, and on the click of a "Accept & Download" button, they download the file that they selected in the radio button.
This is what I have below. When I click one of the radio buttons and click download, nothing happens.
Javascript:
<script>
var isgeorge = document.getElementById('george').checked;
var ismaci = document.getElementById('maci').checked;
var isandre = document.getElementById('andre').checked;
var iscaroline = document.getElementById('caroline').checked;
var isthai = document.getElementById('thai').checked;
var button = document.getElementById('download');
button.onclick = downloadFile;
function downloadFile() {
if(isgeorge) {
window.open("gaa2dn-resume.docx");
}else
if(ismaci) {
window.open("maciresume.docx");
}else
if(isandre) {
window.open("andreresume.pdf");
}else
if(iscaroline) {
window.open("cpw6n-resume.pdf");
}else
if(isthai) {
window.open("tk9kb-resume.pdf");
}
}
HTML in this image:
http://i.imgur.com/2eSc3BF.png

You should be getting the checked values within the function. isgeorge and the other variables do not automatically get updated whenever the checkboxes are changed
So all you have to do is move your variables inside the function
function download(){
var isgeorge = document.getElementById('george').checked;
var ismaci = document.getElementById('maci').checked;
//etc etc etc
Demo
note: since stack snippets dont allow creating new windows the demo just displays a message instead.
var log = document.getElementById('log');
var button = document.getElementById('download');
button.onclick = downloadFile;
function downloadFile() {
var isgeorge = document.getElementById('george').checked;
var ismaci = document.getElementById('maci').checked;
var isandre = document.getElementById('andre').checked;
var iscaroline = document.getElementById('caroline').checked;
var isthai = document.getElementById('thai').checked;
if(isgeorge) {
log.innerText = "would have opened: gaa2dn-resume.docx";
//window.open("gaa2dn-resume.docx");
} else if(ismaci) {
log.innerText = "would have opened: maciresume.docx";
//window.open("maciresume.docx");
} else if(isandre) {
log.innerText = "would have opened: andreresume.pdf";
//window.open("andreresume.pdf");
} else if(iscaroline) {
log.innerText = "would have opened: andreresume.pdf";
//window.open("andreresume.pdf");
} else if(isthai) {
log.innerText = "would have opened: tk9kb-resume.pdf";
//window.open("tk9kb-resume.pdf");
}
}
<label for="george">George</label><input type="radio" name="download" id="george" /><br />
<label for="maci">Maci</label><input type="radio" name="download" id="maci" /><br />
<label for="andre">Andre</label><input type="radio" name="download" id="andre" /><br />
<label for="caroline">Caroline</label><input type="radio" name="download" id="caroline" /><br />
<label for="thai">Thai</label><input type="radio" name="download" id="thai" /><br />
<button id="download">Download</button>
<div id="log"></div>

Related

Control an input which filled automatically by a script

I have this script which checking if the value of variable is match or not value of a hidden input and return a confirmMessage.
the value of var maybe filled manually or automatically by another script.
when its manually there is a result, but when the input is filled automatically with a script i got no confirmmessage.
<script>
$('#vr').on('keyup change', function() {
var vr = document.getElementById('vr');
var confirm_vr = document.getElementById('confirm_vr');
var message = document.getElementById('confirmMessage');
if(vr.value == confirm_vr.value){
message.innerHTML = "MATCH";
}else{
message.innerHTML = "! Not match";
}
});
</script>
<span id='confirmMessage' ></span>
<input id='vr' name='vr' />
<input type='hidden' id='confirm_vr' name='confirm_vr' />
How do you set the input value "automatically with a script"? just by document.getElementById('vr').value = 'hello'? As easiest solution I would suggest to extract your handler logic into the global function and call it when you change the input via code:
<script>
function processChange() {
var vr = document.getElementById('vr');
var confirm_vr = document.getElementById('confirm_vr');
var message = document.getElementById('confirmMessage');
if(vr.value == confirm_vr.value){
message.innerHTML = "MATCH";
}else{
message.innerHTML = "! Not match";
}
};
$(function() {
$('#vr').on('keyup change', processChange);
});
</script>
<span id='confirmMessage' ></span>
<input id='vr' name='vr' />
<input type='hidden' id='confirm_vr' name='confirm_vr' />
<script>
$(function() {
document.getElementById('vr').value = 'hello';
processChange();
});
</script>
Adding another answer because #dhilt's answer requires that you change the code that sets the input value everytime you add a new listener.
$('#vr').on('keyup change', function() {
var vr = document.getElementById('vr');
var confirm_vr = document.getElementById('confirm_vr');
var message = document.getElementById('confirmMessage');
if(vr.value == confirm_vr.value){
message.innerHTML = "MATCH";
}else{
message.innerHTML = "! Not match";
}
});
$('#vr').on('keyup change', (e) => {
// This will get called without the code that sets
// input.value having to know about this handler
console.log('Value changed', e);
});
$('button').on('click', function() {
var vr = document.getElementById('vr');
vr.value += 'X';
// Notice that you don't need to know what handlers are set
$(vr).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id ="vr"/>
<span id='confirmMessage' ></span>
<input id='vr' name='vr'>
<input type='hidden' id='confirm_vr' name='confirm_vr' value="X"/>
<hr />
<button>Set text value</button>

Change HTML tag with Javascript

I asking the user to select given emails, and getting them with javascript from a form on click.
If I have an href like
And I have a bunch of checkboxes for every email obtained from the database
Using javascript, how can I add this value into the emails="" tag by clicking the checkbox?
You can listen to change event for each checkbox to keep track of checked emails:
var boxes = document.querySelectorAll('input[name=email]');
var link = document.getElementById('myHref');
var emails = [];
boxes.forEach(box => box.addEventListener('change', function(e) {
var v = e.target.value;
if (e.target.checked === true) {
if (!emails.includes(v)) emails.push(v);
} else {
emails.splice(emails.indexOf(v), 1);
};
link.setAttribute('emails', emails.join(', '));
console.log(link.attributes.emails.value)
}))
<input type="checkbox" value="1#d.com" name="email">
<input type="checkbox" value="2#d.com" name="email">
<input type="checkbox" value="3#d.com" name="email">
Link
You can set a click event on the checkbox.
var arr_el = document.getElementsByClassName('check-boxes');
for(var i = 0; i < arr_el.length; i++){
arr_el[i].addEventListener('click', function(){
var el = document.getElementById('myHref');
var emails = el.getAttribute('emails');
var userSelectedEmail = this.value;
if(this.checked){
el.setAttribute('emails', emails + ';' + userSelectedEmail);
} else {
// debugger;
emails = emails.split(';');
var index = emails.indexOf(userSelectedEmail);
emails.splice(index, 1);
el.setAttribute('emails', emails.join(';'));
}
document.getElementById('emails').innerText = el.getAttribute('emails');
});
}
<html>
<head>
</head>
<body>
<a id="myHref" href="#" emails="test#email.com">Link</a>
<br>
<input class="check-boxes" type="checkbox" value="email2#gmail.com">email2#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email3#gmail.com">email3#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email4#gmail.com">email4#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email5#gmail.com">email5#gmail.com<br>
<p id="emails"></p>
</body>
</html>

Detect text filled by barcode scanner(reader) javascript

The code checks barcodes using a barcode scanner.
Search_code is filled by a user (keyboard) , and insert_code is filled automatically by a barcode scanner.
Currently, code works if both inputs are introduced in barcode scanner values ​​which is not functional for me.
The code needs to run when:
search_code is entered manually ( keyboard ) and
insert_code is filled automatically by the barcode scanner
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value == insert_code.value) {
result.textContent = 'code ok';
result.className = "ok";
audio.play();
} else {
result.textContent = 'code is not ok';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
function clearField(input) {
input.value = "";
};
....
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value=""/><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
</div>
<div id="result"></div>
</div>
<script src="js/action_input.js"></script>
</body>
</html>
Thank you!
To prevent a textbox from being filled by a bar-code reader simply disable onpaste event .
$(document).ready(function(){
$('#search_code').bind("cut copy paste",function(e) {
e.preventDefault();
});
});

Unable to get an event interrupter for preventing form submission to work corrctly in a basic JavaScript and PHP tutorial

I am trying to learn JavaScript, PHP and some basic client-side form validations in trying to build this basic JavaScript tutorial that interacts with PHP and HTML. WHat I am trying to do is interrupt a form submission event, i.e. user forgets to enter a valid email format in the email submission input and clicks on the submit button which should then display an error message and not allow the form to be submitted. But I can't get this to work for me. What happens is that I am instead taken to the support_process.php page when that should not happen. Any help at all would be greatly appreciated.
Here is my index.html code for the form:
<div>
<form id="frmSupport" name="frmSupport" method="post" action="support_process.php">
<fieldset id="fastSupport">
<legend><strong>Fast Support</strong></legend>
<p>If you've already booked the Singing Rails Girls coach,</br> and have not gotten a confirmation number,</br> drop us a line and we'll respond within 24 hours.</p> </p>
<p>
<label for="email">Email:</label>
<input type="text" value="your email" name="name" id="email" tabindex="10" />
<p>
<span id="errorMsg"></span>
</p>
<input type="submit" value="Submit">
</p>
<p><b>Ed's "Blah Blah Blah" Tour Status</b></p>
<label for="tourStatus" class="inline">
<input type="radio" name="tour status" value="booked" id="tourStatus_0" tabindex="40" />Ed already toured here
</label>
<label for="tourConf" class="inline" >
<input type="radio" name="tour conf" value="paid" id= "tourStatus_1" tabindex="50" />Ed confirmed his tour date
</label>
</br>
</fieldset>
</form>
</div>
Comments Section
Comments:
<script src="myscript.js">
</script>
And here is my corresponding JavaScript file:
//alert("Hello, world!"); // this is a JavaScript alert button //
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro...");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
// Handling the form submit event
document.getElementById("frmSupport").onsubmit = function(){
//prevent a form from sumbitting if no email.
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers();
// This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White- Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var intervalHandle = setInterval(changeImage, 5000);
myImage.onclick = function() {
clearInterval(intervalHandle);
}
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
And here is my corresponding php file for the event interrupter (for refusing to allow the form to be submitted if user leaves email field blank or something):
<?php
//some php script can go here
echo "This is the support confirmation page...sorry, nothing fancy here!"
?>
<h1>Thank you, we will contact you shortly!</h1>
<a href="index.html" target="_blank" >Back</a>
<?php
// More php code can go here, and so forth and so on..
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_GET); */
error_log(message);
?>
Here's a problem:
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
In the first part of the if, you're trying to get a reference to the errorMsg element using a non-existent variable:
document.getElementById(errorMsg).innerHTML = "OOPS!";
In the second, you're accessing the element by its id properly:
document.getElementById("errorMsg").innerHTML = "";
You need to surround 'errorMsg' with single or double quotes.
You should definitely look into using a debugger to help you find problems like these. Chrome Developer Tools are a good place to start.

JQuery UI Diaglog to populate checkbox values to parent

I have a requirement that a user should select the checkbox values from a pop-up and click on submit on pop-up and the selected values should get displayed back to the parent page.
I was playing with some radio box values which I am able to push to the Parent window but struggling with checkbox values.
Here is what my pop-up looks like and my code is
<p>Please Select a language:</p>
<div id="myDialog" title="Select Language">
<br /><br />
<input type="checkbox" name="countryCheckbox[]" value="English" checked = "checked" /> English <br/>
<input type="checkbox" name="countryCheckbox[]" value="French" /> French <br/>
<input type="checkbox" name="countryCheckbox[]" value="Norwagian" /> Norwagian <br/>
<input type="checkbox" name="countryCheckbox[]" value="Swedish" /> Swedish <br/>
<input type="checkbox" name="countryCheckbox[]" value="Hindi" /> Hindi <br/>
<input type="checkbox" name="countryCheckbox[]" value="Chinese" /> Chinese <br/>
<br /><br />
<label for="yes">Yes!</label><input type="radio" id="yes" value="yes" name="question" checked="checked"><br>
<label for="no">No!</label> <input type="radio" id="no" value="no" name="question">
</div>
<p id="text">Selected Languages are: </p>
and my Jquery code that works for the selected radio button is as below
$(function(){
var execute = function(){
var answer;
$("input").each(function(){
(this.checked == true) ? answer = $(this).val() : null;
});
$("<p>").text("You selected " + answer).appendTo($("body"));
$("#myDialog").dialog("close");
}
var cancel = function() {
$("#myDialog").dialog("close");
}
var dialogOpts = {
buttons: {
"Submit": execute,
"Cancel": cancel
}
};
$("#myDialog").dialog(dialogOpts);
});
I'm trying to add the following JQuery code to display the selected checkbox values on the parent pages
$('#myDialog').submit(function(ev){
ev.preventDefault();
var arr = [];
$('input:checkbox:checked').each(function(){
arr.push($(this).val());
});
$(opener.document).contents().find("#text").text(arr.join(","));
self.close();
});
Please suggest as I'm still struggling to integrate the JQuery code of selected checkboxes to be displayed on the parent page.
you would need to iterate over each input and then store that in an array to append it to the body..
$(function () {
var execute = function () {
var answer = [];;
$("input").each(function () {
if (this.checked) answer.push(this.value);
});
for (var i = 0; i < answer.length ; i++)
$("<p>").text("You selected " + answer[i]).appendTo($("body"));
};
});
Check Fiddle
Code
$(function () {
var execute = function () {
var answer = [];;
$("input").each(function () {
if (this.checked) answer.push(this.value);
});
for (var i = 0; i < answer.length; i++)
$("<p>").text("You selected " + answer[i]).appendTo($("body"));
};
var cancel = function () {
$("#myDialog").dialog("close");
}
var dialogOpts = {
buttons: {
"Submit": execute,
"Cancel": cancel
}
};
$("#myDialog").dialog(dialogOpts);
});
EDIT
var cancel = function () {
$("#myDialog").dialog("close");
}
var saveAndCancel = functionI() {
execute();
cancel();
}
var dialogOpts = {
buttons: {
"Submit": saveAndCancel ,
"Cancel": cancel
}
};

Categories

Resources