please anyone can help me I am stuck in radio buttons.
when user click on submit button under the radio buttons they should be redirected into new window like target="_blank"
please help me if there is any solution available.
then I change window.location.href
two window.open the code is not working properly
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
input[type=radio] {
-webkit-appearance: radio;
-O-appearance: radio;
-moz-appearance: radio;
opacity:1;
}
#header .bottom-header.blog h1 {
font-size: 64px;
color: red
}
input[type=radio]:hover + label {
border: solid 1px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=radio]:checked + label {
border: solid 2px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=text] {
font-weight:bold;
}
input[type=text]:hover {
}
input[type=email]:hover {
}
<form name="radioExampleForm" method="get" action="" onsubmit="return false;">
<p> <label for="number0"><input type="radio" value="http://www.google.com" name="number" id="number0"> Zero</label></br>
<label for="number1"><input type="radio" value="http://www.ebay.com" name="number" id="number1"> One</label></br>
<label for="number2"><input type="radio" value="http://www.gamestop.com" name="number" id="number2"> Two</label></br>
</p>
<input type="button" onclick="window.location.href = (getCheckedValue(document.forms['radioExampleForm'].elements['number']));" value="Buy Now">
</form>
You should use window.open(url, '_blank') which will open the url in new tab. Again I would say opening in new tab will get certainly get struck by a popup blocker. I would recommend you using an anchor tag with target="_blank" in place of button (and change a tag's href in onchange of radio button) which will not get blocked by a popup blocker
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
input[type=radio] {
-webkit-appearance: radio;
-O-appearance: radio;
-moz-appearance: radio;
opacity:1;
}
#header .bottom-header.blog h1 {
font-size: 64px;
color: red
}
input[type=radio]:hover + label {
border: solid 1px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=radio]:checked + label {
border: solid 2px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=text] {
font-weight:bold;
}
input[type=text]:hover {
}
input[type=email]:hover {
}
<form name="radioExampleForm" method="get" action="" onsubmit="return false;">
<p> <label for="number0"><input type="radio" value="http://www.google.com" name="number" id="number0"> Zero</label></br>
<label for="number1"><input type="radio" value="http://www.ebay.com" name="number" id="number1"> One</label></br>
<label for="number2"><input type="radio" value="http://www.gamestop.com" name="number" id="number2"> Two</label></br>
</p>
<input type="button" onclick="window.open(getCheckedValue(document.forms['radioExampleForm'].elements['number']), '_blank');" value="Buy Now">
</form>
Use the below script to do your task
$("input[type='button']").click(function(){
var numbers = document.getElementsByName('number');
var num_value;
for(var i = 0; i < numbers.length; i++){
if(numbers[i].checked){
num_value = numbers[i].value;
// alert(num_value);
window.open(num_value, '_blank');
}
}
});
Related
I'm trying to hide mailingaddress box and label, and also hide comments box and label. They will only show up when I click on the radio button "mail" (the first choice), and when I switch to another button/choice, those labels and fields will be hidden again. Same for comments - when I click on "I accepted" of Terms of Services - the comments box and label will show up, if I uncheck it, the box and the label disappear. I successfully hide them but I cannot make them appear again when I click on the mail button, neither can I make the comments box and label appear when I click on "I accept" of Terms of Services. Where did I go wrong?
var $ = function(id) { return document.getElementById(id); };
var processEntries = function() {
var isValid = true;
// get values for user entries
var email = $("email_address").value;
var phone = $("phone").value;
var country = $("country").value;
var terms = $("terms").checked; //return true or false indicates whether a check box is checked or not
//remove validity messages if there is any
$("email_address").nextElementSibling.textContent = "";
$("phone").nextElementSibling.textContent = "";
$("country").nextElementSibling.textContent = "";
$("terms").nextElementSibling.textContent = "";
// check user entries for validity
if (email === "") {
$("email_address").nextElementSibling.textContent = "This field is required.";
isValid = false;
}
if (phone === "") {
$("phone").nextElementSibling.textContent = "This field is required.";
isValid = false;
}
if (country === "") {
$("country").nextElementSibling.textContent = "Please select a country.";
isValid = false;
}
if (terms === false) {
$("terms").nextElementSibling.textContent = "This box must be checked.";
isValid = false;
}
if(isValid)
{
$("registration_form").submit(); //submit registration form
}
};
var resetForm = function() {
$("registration_form").reset();
$("email_address").nextElementSibling.textContent = "*";
$("phone").nextElementSibling.textContent = "*";
$("country").nextElementSibling.textContent = "*";
$("terms").nextElementSibling.textContent = "*";
$("email_address").focus();
};
$("register").onclick = processEntries;
$("reset_form").onclick = resetForm;
//step 1: hide mailingaddress box and label, hide comments box and label
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("mailingaddress").style.display = "none";
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
//step 2: define event handler function and add event listener to hide or show mailing address box and label when radio buttons are clicked.
//show mailing addess box and label only when mail button is clicked, when other buttons are clicked, hide mailing address box and label
document.getElementById("mail").addEventListener("click", displayMailOption);
function displayMailOption() {
if (documenet.getElementById("mail").checked){
document.getElementsByTagName("label")[4].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
//step 3: define event handler functionn and add event listener to hide or show comment box and label when check box is clicked.
//show comment box and label only when check box is checked. when check box is unchecked, hide comment box and label
document.getElementById("comments").addEventListener("click", displayCommentOption);
function displayCommentOption() {
if (documenet.getElementById("comments").checked){
document.getElementsByTagName("label")[6].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
html { background-image: url("ginkgo.jpg");}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 730px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
h2 {
font-size: 120%;
margin-bottom: .25em;
}
label {
float: left;
width: 9em;
}
input, select , textarea{
width: 20em;
margin-left: 1em;
margin-bottom: 1em;
}
input[type="checkbox"],[type="radio"] {
width: 1em;
}
#registration_form span {
color: red;
font-size: 80%;
}
.hide {display: none;}
input[type="button"] {
background-color: #000;
border-radius: 5px;
color: #fff;
font-size: 1.2em;
width: 100px;
margin-right: 1.4em;}
input[type="button"]:hover {
background-color: #666;
cursor: pointer;
text-shadow: 2px 2px 2px #000;
box-shadow: inset 0 2px 2px #000;}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Account Registration</title>
<link rel="stylesheet" type="text/css" href="register.css">
</head>
<body>
<main>
<h1>Register for an Account</h1>
<form action="register_account.html" method="get"
name="registration_form" id="registration_form">
<label for="email_address">E-Mail:</label>
<input type="text" name="email_address" id="email_address">
<span>*</span><br>
<label for="phone">Mobile Phone:</label>
<input type="text" name="phone" id="phone">
<span>*</span><br>
<label for="country">Country:</label>
<select name="country" id="country">
<option value="">Select an option</option>
<option>USA</option>
<option>Canada</option>
<option>Mexico</option>
</select>
<span>*</span><br>
<label>Contact me by:</label>
<input type="radio" name="contact" id="mail" value="mail">Mail
<input type="radio" name="contact" id="email" value="email">Email
<input type="radio" name="contact" id="mphone" value="mobilephone">Mobile Phone
<input type="radio" name="contact" id="none" value="none">Don't contact me
<br>
<label for="mailingaddress">Your Mailing Address:</label>
<textarea id="mailingaddress"></textarea><br>
<label>Terms of Service:</label>
<input type="checkbox" name="terms" id="terms" value="yes">I accept
<span>*</span><br>
<label for="comments">Comments:</label>
<textarea id="comments" cols='20' rows='10' ></textarea><br>
<label> </label>
<input type="button" id="register" value="Register">
<input type="button" id="reset_form" value="Reset">
</form>
</main>
<script src="register.js"> </script>
</body>
</html>
You don't have event listeners for other radio inputs, so no code will run.
Add these:
document.getElementById("email").addEventListener("click", displayMailOption);
document.getElementById("mphone").addEventListener("click", displayMailOption);
document.getElementById("none").addEventListener("click", displayMailOption);
Now on every radio input change, your displayMailOption function will run.
The displayMailOption function should look like this, after fixing the typo and selecting the correct element:
function displayMailOption() {
if (document.getElementById("mail").checked) {
document.getElementsByTagName("label")[4].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("mailingaddress").style.display = "none";
}
}
Fix the comment listener ID:
document.getElementById("terms").addEventListener("click", displayCommentOption);
The displayCommentOption function should look like this:
function displayCommentOption() {
if (document.getElementById("terms").checked) {
document.getElementsByTagName("label")[6].style.display = "block";
document.getElementById("comments").style.display = "block";
} else {
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
Actually you don't need JavaScript to achieve that. You can do it in pure CSS. But to answer your question first, the problem is that you attach the click event the label and the function is called only when input is clicked. So if "email", "phone" or other labels are clicked the function is not called and therefore the elements are not hidden.
Here is an example of how to do it using only CSS:
var $ = function(id) {
return document.getElementById(id);
};
var processEntries = function() {
var isValid = true;
// get values for user entries
var email = $("email_address").value;
var phone = $("phone").value;
var country = $("country").value;
var terms = $("terms").checked; //return true or false indicates whether a check box is checked or not
//remove validity messages if there is any
$("email_address").nextElementSibling.textContent = "";
$("phone").nextElementSibling.textContent = "";
$("country").nextElementSibling.textContent = "";
$("terms").nextElementSibling.textContent = "";
// check user entries for validity
if (email === "") {
$("email_address").nextElementSibling.textContent = "This field is required.";
isValid = false;
}
if (phone === "") {
$("phone").nextElementSibling.textContent = "This field is required.";
isValid = false;
}
if (country === "") {
$("country").nextElementSibling.textContent = "Please select a country.";
isValid = false;
}
if (terms === false) {
$("terms").nextElementSibling.textContent = "This box must be checked.";
isValid = false;
}
if (isValid) {
$("registration_form").submit(); //submit registration form
}
};
var resetForm = function() {
$("registration_form").reset();
$("email_address").nextElementSibling.textContent = "*";
$("phone").nextElementSibling.textContent = "*";
$("country").nextElementSibling.textContent = "*";
$("terms").nextElementSibling.textContent = "*";
$("email_address").focus();
};
$("register").onclick = processEntries;
$("reset_form").onclick = resetForm;
//step 1: hide mailingaddress box and label, hide comments box and label
/*
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("mailingaddress").style.display = "none";
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
*/
//step 2: define event handler function and add event listener to hide or show mailing address box and label when radio buttons are clicked.
//show mailing addess box and label only when mail button is clicked, when other buttons are clicked, hide mailing address box and label
//document.getElementById("mail").addEventListener("click", displayMailOption);
/*
function displayMailOption() {
if (document.getElementById("mail").checked) {
document.getElementsByTagName("label")[4].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
//step 3: define event handler functionn and add event listener to hide or show comment box and label when check box is clicked.
//show comment box and label only when check box is checked. when check box is unchecked, hide comment box and label
document.getElementById("comments").addEventListener("click", displayCommentOption);
function displayCommentOption() {
if (document.getElementById("comments").checked) {
document.getElementsByTagName("label")[6].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
*/
html {
background-image: url("ginkgo.jpg");
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 730px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
h2 {
font-size: 120%;
margin-bottom: .25em;
}
label {
float: left;
width: 9em;
}
input,
select,
textarea {
width: 20em;
margin-left: 1em;
margin-bottom: 1em;
}
input[type="checkbox"],
[type="radio"] {
width: 1em;
}
#registration_form span {
color: red;
font-size: 80%;
}
.hide {
display: none;
}
input[type="button"] {
background-color: #000;
border-radius: 5px;
color: #fff;
font-size: 1.2em;
width: 100px;
margin-right: 1.4em;
}
input[type="button"]:hover {
background-color: #666;
cursor: pointer;
text-shadow: 2px 2px 2px #000;
box-shadow: inset 0 2px 2px #000;
}
/* Hide elements on load */
#mailingaddress,
#mailadress-label,
#comments-label,
#comments {
display: none;
}
/* Show elements when #mail is checked */
#mail:checked~#mailingaddress,
#mail:checked~#mailadress-label {
display: block;
}
/* Show comments when #terms is checked */
#terms:checked~#comments-label,
#terms:checked~#comments {
display: block;
}
<main>
<h1>Register for an Account</h1>
<form action="register_account.html" method="get" name="registration_form" id="registration_form">
<label for="email_address">E-Mail:</label>
<input type="text" name="email_address" id="email_address">
<span>*</span><br>
<label for="phone">Mobile Phone:</label>
<input type="text" name="phone" id="phone">
<span>*</span><br>
<label for="country">Country:</label>
<select name="country" id="country">
<option value="">Select an option</option>
<option>USA</option>
<option>Canada</option>
<option>Mexico</option>
</select>
<span>*</span><br>
<label>Contact me by:</label>
<input type="radio" name="contact" id="mail" value="mail">Mail
<input type="radio" name="contact" id="email" value="email">Email
<input type="radio" name="contact" id="mphone" value="mobilephone">Mobile Phone
<input type="radio" name="contact" id="none" value="none">Don't contact me
<br>
<label for="mailingaddress" id='mailadress-label'>Your Mailing Address:</label>
<textarea id="mailingaddress"></textarea><br>
<label>Terms of Service:</label>
<input type="checkbox" name="terms" id="terms" value="yes">I accept
<span>*</span><br>
<label for="comments" id='comments-label'>Comments:</label>
<textarea id="comments" cols='20' rows='10'></textarea><br>
<label> </label>
<input type="button" id="register" value="Register">
<input type="button" id="reset_form" value="Reset">
</form>
</main>
jQuery('input[type=radio]').change(function(){
if (document.getElementById("mail").checked){
document.getElementsByTagName("label")[4].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("mailingaddress").style.display = "none";
}
})
document.getElementById("terms").addEventListener("click", displayCommentOption);
function displayCommentOption() {
if (document.getElementById("terms").checked){
document.getElementsByTagName("label")[6].style.display = "block";
document.getElementById("comments").style.display = "block";
} else {
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
Im creating a floating label , i manage to make a floating label on textbox but
in my dropdown it doesn't work. hope you can help me.
/** GLOBAL OBJECT **/
var $ = {
addClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = classes.indexOf(name);
if (cIndex === -1) {
classes.push(name);
}
elem.className = classes.join(' ');
return this;
}, // END addClass
removeClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = undefined;
function recursive() {
// use a recursive function to remove all instances
// of the class name
cIndex = classes.indexOf(name);
if (cIndex >= 0) {
classes.splice(cIndex, 1);
recursive();
}
}
recursive();
elem.className = classes.join(' ');
return this;
}, // END removeClass
hasClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = classes.indexOf(name);
if (cIndex >= 0) {
return true;
} else {
return false;
}
}, // END hasClass
selectCreate: function(select, label) {
var _this = this;
id = '_' + select.id,
input = document.createElement('input'),
div = document.createElement('div'),
ul = document.createElement('ul'),
val = {
value: select.value,
text: select.options[select.selectedIndex].text
};
select.style.display = 'none';
ul.id = 'ul' + id;
ul.className = 'ddown-list';
ul.setAttribute('aria-live', 'polite');
input.setAttribute('type', 'text');
input.setAttribute('aria-autocomplete', 'list');
input.setAttribute('aria-haspopup', 'true');
input.setAttribute('aria-owns', ul.id);
input.className = 'dynamic-dropdown';
input.id = id;
if (select.getAttribute('data-required') === 'true') {
input.setAttribute('required', 'true');
}
label.setAttribute('for', id);
div.className = 'selectRegion';
div.appendChild(label);
div.appendChild(input);
div.appendChild(ul);
select.parentNode.insertBefore(div, select);
input.value = val.text;
if (input.value !== '') {
this.addClass(label, 'active');
} else {
this.addClass(label, 'inactive');
}
input.addEventListener('focus', function() {
_this.addClass(label, 'active')
.addClass(label, 'transition')
.removeClass(label, 'inactive');
if (this.setSelectionRange) {
this.setSelectionRange(0, this.value.length);
}
populateList(this, select, document.getElementById('ul' + this.id), -1, true);
}); // END focus
input.addEventListener('blur', function() {
var input = this;
setTimeout(function() {
if (input.value === '') {
_this.addClass(label, 'inactive')
.addClass(label, 'transition')
.removeClass(label, 'active');
} else {
var list = getList(input.value, select, false);
select.value = list.value[0];
input.value = list.text[0];
}
document.getElementById('ul' + input.id).innerHTML = '';
}, 250);
}); // END blur
input.addEventListener('keyup', function(e) {
var list = document.getElementById('ul' + this.id).getElementsByTagName('li'),
index = -1,
kC = e.keyCode;
for (var i = 0, x = list.length; i < x; i++) {
if (_this.hasClass(list[i], 'active')) {
index = i;
break;
}
}
if (kC !== 9 && kC !== 16) { // SHIFT && TAB
if (kC === 13) { // ENTER
var list = getList(this.value, select, false);
select.value = list.value[index];
this.value = list.text[index];
document.getElementById('ul' + this.id).innerHTML = '';
} else {
switch (kC) {
case 38: // ARROW UP
index--;
if (index < 0) {
index = 0;
}
break;
case 40: // ARROW DOWN
index++;
if (index >= list.length) {
index = list.length - 1;
}
break;
default:
index = -1;
break;
}
populateList(this, select, document.getElementById('ul' + this.id), index, false);
}
}
}); // END keyup
function populateList(input, select, target, index, focus) {
var list = getList(input.value, select, focus),
counter = 0,
output;
if (focus) {
index = select.selectedIndex - 1;
}
target.innerHTML = '';
for (var i = 0, x = list.value.length; i < x; i++) {
output = document.createElement('li');
if (counter === index) {
output.className = 'active';
}
output.appendChild(document.createTextNode(list.text[i]));
output.addEventListener('click', function() {
console.log('test');
input.value = this.innerHTML;
});
target.appendChild(output);
counter++;
}
if (index >= 0) {
var lis = target.getElementsByTagName('li'),
sTop = 0;
for (var i = 0, x = lis.length; i < x; i++) {
if (i >= index) {
break;
}
sTop += lis[i].clientHeight;
}
target.scrollTop = sTop;
}
} // END populateList
function getList(val, list, focus) {
var value = [],
text = [],
vLength = val.length;
if (focus) {
vLength = 0;
val = '';
}
for (var i = 0, x = list.length; i < x; i++) {
if (list[i].text !== '' &&
(list[i].text.toUpperCase().substring(0, vLength) === val.toUpperCase() ||
list[i].value.toUpperCase().substring(0, vLength) === val.toUpperCase())) {
value.push(list[i].value);
text.push(list[i].text);
}
}
return {
value: value,
text: text
};
} // END function getList
}, // END selectCreate()
}; // END $
window.onload = function() {
var labels = document.getElementsByTagName('label'),
id = '',
label = undefined,
input = undefined,
type = undefined;
for (var i = 0, x = labels.length; i < x; i++) {
label = labels[i];
id = label.getAttribute('for') || '';
input = document.getElementById(id);
if (input) {
type = input.getAttribute('type') || input.tagName;
type = type.toLowerCase();
if (input && (type === 'select')) {
$.selectCreate(input, label);
} // END if( input && select )
}
} // END for( labels )
}();
var demo = function() {
setTimeout(function() {
document.getElementById('_s').focus();
setTimeout(function() {
document.getElementById('_s').blur();
}, 750);
}, 500);
}();
body {
background-color: #F7F7F7;
font-family: Arial;
padding-top: 10%;
}
input,
label,
select {
width: 280px;
padding: 10px;
font-size: 16px;
}
input {
border: solid 1px #CCCCCC;
border: none;
overflow: visible;
outline: none;
background-color: transparent;
border-bottom: solid 1px #999;
}
label {
position: absolute;
}
label.active {
color: #3784BB;
margin-top: -20px;
font-size: 12px;
}
label.inactive {
color: #999999;
}
li.active {
background-color: rgba( 255, 0, 0, 0.1);
}
.transition {
transition: all linear 0.1s;
}
.input {
width: 300px;
margin: auto;
}
.input:first-child {
margin-bottom: 5%
}
.selectRegion {
width: 100%;
}
.selectRegion ul {
margin: 0;
padding: 0;
position: absolute;
width: 300px;
max-height: 200px;
overflow: auto;
box-shadow: 0 2px 3px rgba( 0, 0, 0, 0.1);
background-color: #FFFFFF;
z-index: 2;
}
.selectRegion ul li {
padding: 10px;
}
.selectRegion ul li:hover {
cursor: pointer;
}
.inputbox {
position: relative;
background: none;
margin-right: 50px;
}
.inputbox input {
width: 120%;
padding: 10px 0;
font-size: 19px;
color: #21a1e;
margin-bottom: 50px;
overflow: visible;
outline: none;
background-color: transparent;
border: none;
border-bottom: solid 1px #999;
margin-left: -10px;
margin-top: -15px;
}
.inputbox label {
display: block;
position: absolute;
top: 0;
left: 0;
padding: 10px 0;
font-size: 16px;
color: #999;
pointer-events: none;
transition: top 0.7s ease, opacity 0.7s ease;
border-radius: .25rem;
margin-left: -10px;
margin-top: -10px;
}
.inputbox input:focus+label,
.inputbox input:valid+label {
top: -18px;
left: 0;
color: #4285f4;
font-size: 12px;
cursor: pointer;
}
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-sm-5">
<button type="button" class="button2 " data-toggle="modal" data-target="#exampleModal1">Login</button>
</div>
<div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg " role="document">
<div class="modal-content">
<div class="modal-header ">
<h5 class="modal-title" id="exampleModalLabel" style=" color: #404E67;">Form</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-row ">
<div class="inputbox">
<input type="text" required>
<label>First Name </label>
</div>
<div class="inputbox">
<input type="text" required>
<label>Last Name</label>
</div>
</div>
<div class="form-row">
<div class="input">
<label for="s">Sample 1:</label>
<select id="s">
<option value=""></option>
<option value="1">Assignment</option>
<option value="2">Reading</option>
</select>
</div>
</div>
<div class="clear"></div>
<div class="input">
<label for="state">Sample 2</label>
<select id="state">
<option value=""></option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
</div>
</form>
</div>
</div>
</body>
</html>
here is my current output:
As you can see on my output the two dropdown is not working any idea how ca i make it a floating label like at my textbox?
I want to display a table on click submit only if text box is not null
Demo: https://jsfiddle.net/21bbc4wm/
When i click submit button it returns no table, pls can someone help me out of this
<input type="text" list="user" id="note" name="Username"
placeholder="User ID*" autocomplete="off" required />
<div id= "container1" style="display:none;">
<p style="text-align:center; font-size:160%;">Search Result</p>
<table id="demo">
<tr><th>User ID</th>
<th>Date</th><tr>
</table>
<td><button style="background-color: #4CAF50;" id = "buttonSubmit"
type="submit" value="Submit" onclick ='check(); return
false'>Submit</button></td>
Javascript:
function check()
{
if(document.getElementById("note").value == null ||
document.getElementById("note").value == "")
{
alert("You must mention User ID for the result!!!");
document.getElementById("note").focus();
return false
var x = document.getElementById("container1");
if (x.style.display = "none") {
x.style.display = "block";
} else {
x.style.display = "true";
}
}
document.addEventListener("click", function(e){
var table = document.getElementById("demo");
var content = document.getElementById("container1");
var val = document.getElementById("note");
if(e.target.id === "buttonSubmit") {
if(val.value === null || val.value === "") {
alert("You must mention User ID for the result!!!");
content.classList.remove("active");
val.focus();
}
else {
var date = new Date();
/* remove this line for stacking */ table.innerHTML = '<tr><th>User ID</th><th>Date</th><tr>';
table.innerHTML += '<tr><td>' + val.value + '</th><td>'+ date.toDateString() +'</th><tr>';
val.value = "";
content.classList.remove("active");
content.classList.add("active");
}
}
if(e.target.id === "buttonReset") {
table.innerHTML = '<tr><th>User ID</th><th>Date</th><tr>';
val.value = "";
content.classList.remove("active");
}
});
input {
font-size: 1em;
}
#container1 {
display: none;
}
#container1.active {
display: block;
}
#result {
text-align: center;
font-size: 160%;
}
#buttonSubmit {
background-color: #4CAF50;
padding: 3px;
border: 1px solid black;
display: inline-block;
font-size: 1em;
cursor: pointer;
}
#buttonReset {
background-color: #4CAF50;
padding: 3px;
border: 1px solid black;
display: inline-block;
font-size: 1em;
cursor: pointer;
}
<input type="text" list="user" id="note" name="Username"
placeholder="User ID*" autocomplete="off" required>
<div id="container1">
<p id="result">Search Result</p>
<table id="demo">
<tr><th>User ID</th>
<th>Date</th><tr>
</table>
</div>
<a id="buttonSubmit">Submit</a>
<a id="buttonReset">Reset</a>
I'm working on an assignment that needs to, upon the click of a span element's text in an input div, output the same text in an output div. That part I've done successfully, but to the left of each span element within the input div is a checkbox that needs to also be checked upon the click of said span element.
I am not allowed to target each individual checkbox with its own unique ID because I will be adding in newer checkboxes and span elements later with the press of a button and prompt. This is an assignment on event delegation.
I will then need to be able to uncheck the checkbox and remove the appended output, but first things first, I cannot figure out how to target the checkboxes. The only thing I can think of is to somehow say that whatever index number of said span element was clicked would be the index number of said checkbox is clicked, but I'm unsure if that is the best method as well as how to go about doing that.
Also, this assignment should not have any JQuery involved. My next project is actually to redo this assignment in JQuery. Any help would be appreciated!
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Document Object Model Exercise</title>
<link rel="stylesheet" href="canvas_stylesheet.css">
</head>
<body>
<div id="input">
<form>
<input class="checkbox" type="checkbox"><span class="values">Apple</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Mango</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Grape</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Strawberry</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Cherry</span>
</form>
</div>
<div id="output"></div>
CSS:
#input {
width: 250px;
height: 300px;
float: left;
padding: 20px 0 30px 15px;
border-style: solid;
border-color: black;
border-width: 1px;
}
.values {
display: inline;
}
/*
#input form input {
padding: 20px 20px 20px 20px;
}
*/
#output {
width: 225px;
height: 326px;
float: left;
border-top: 1px solid black;
border-right: 1px solid black;
border-bottom: 1px solid black;
padding: 4px 20px 20px;
}
JS:
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
if (e.target.nodeName === "SPAN") {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
}
});
Just surround your checkboxes elements with label, like I did here.
Ps: plese never write a br element like this </br>, its <br> with no slash at all
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
if (e.target.nodeName === "SPAN") {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
}
});
#input {
width: 250px;
height: 300px;
float: left;
padding: 20px 0 30px 15px;
border-style: solid;
border-color: black;
border-width: 1px;
}
.values {
display: inline;
}
/*
#input form input {
padding: 20px 20px 20px 20px;
}
*/
#output {
width: 225px;
height: 326px;
float: left;
border-top: 1px solid black;
border-right: 1px solid black;
border-bottom: 1px solid black;
padding: 4px 20px 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Canvas Document Object Model Exercise</title>
<link rel="stylesheet" href="canvas_stylesheet.css">
</head>
<body>
<div id="input">
<form>
<label>
<input class="checkbox" type="checkbox"><span class="values">Apple</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Mango</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Grape</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Strawberry</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Cherry</span>
</label>
</form>
</div>
<div id="output"></div>
</body>
</html>
I realized the answer was to use .previousSibling and .nextSibling after posting the question, so I went ahead and finished all the code for the input/output part of the assignment. Then, I realized someone else mentioned .previousSibling in response to the first answer attempt. Thanks everyone!
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
//Click Input Text - Box Checks and Output Text Appears
if (e.target.nodeName === "SPAN") {
if (e.target.previousSibling.checked === false) {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
e.target.previousSibling.checked = true;
return;
}
}
//Click Input Text - Box Unchecks and Output Text Disappears
if (e.target.nodeName === "SPAN") {
if (e.target.previousSibling.checked === true) {
for (i = 0; i < document.getElementsByClassName("outputItem").length; i++) {
if (e.target.innerHTML === document.getElementsByClassName("outputItem")[i].innerHTML) {
document.getElementsByClassName("outputItem")[i].remove();
e.target.previousSibling.checked = false;
return;
}
}
}
}
//Check Box - Output Text Appears
if (e.target.type === "checkbox") {
if (e.target.checked === true) {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.nextSibling.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
return;
}
}
//Uncheck Box - Output Text Disappears
if (e.target.type === "checkbox") {
if (e.target.checked === false) {
for (i = 0; i < document.getElementsByClassName("outputItem").length; i++) {
if (e.target.nextSibling.innerHTML === document.getElementsByClassName("outputItem")[i].innerHTML) {
document.getElementsByClassName("outputItem")[i].remove();
return;
}
}
}
}
});
I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.
Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.
In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.
Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});