I have a poll for my mock website where I need to vote for one of three contestants. I need to store the vote in local storage and then after each additional vote, I need to update the vote in local storage and display it beside the contestants. My main problem is with updating the vote in local storage. I have to do it with only javaScript, HTML and CSS
<html>
<body>
<fieldset>
<legend> <h3>Vote For Your Favorite Chef! </h3></legend>
<form onsubmit="getChoice()" id="pollForm"> <!-- do js for the getCHoice-->
<input type="radio" id="Nominee1" name="Nominee" value="Reynold Poernomo" required/>
<label for="Nominee1"> Reynold Poernomo </label>
<span id="nom1" class="vote"></span>
<br/>
<input type="radio" id="Nominee1.1" name="Nominee" value="Christine Tania" required>
<label for="Nominee1.1"> Christine Tania </label>
<span id="nom2" class="vote"></span>
<br/>
<input type="radio" id="Nominee1.2" name="Nominee" value="Christina Tosi" required>
<label for="Nominee1.2"> Christina Tosi </label>
<span id="nom3" class="vote"></span> <br />
<br/>
<input type="submit">
</form>
<script src="js/localStorage.js"></script>
</fieldset>
</body>
</html>
<script>
function incrementPoll() {
let nominee1 = document.getElementById('Nominee1').value;
let nominee2 = document.getElementById('Nominee2').value;
let nominee3 = document.getElementById('Nominee3').value;
if (nominee1.checked == true) {
updatePoll("Nominee1");
} else if (nominee2.checked == true) {
updatePoll("Nominee2");
} else if (nominee3.checked == true) {
updatePoll("Nominee3");
}
}
function updatePoll(entry) {
let voteUpdate = parseInt(localStorage.getItem(entry),10) + 1;
return localStorage.setItem(entry, (Number(voteUpdate)).toString()); //how to convert to string
}
These two functions are supposed to check which button is being selected and updates the vote in local storage. But it doesn't actually work.
Here's a working version of your code. I hope this helps.
const nominee1 = document.getElementById('Nominee1');
const nominee2 = document.getElementById('Nominee2');
const nominee3 = document.getElementById('Nominee3');
function incrementPoll(e) {
e.preventDefault();
if (nominee1.checked == true) {
updatePoll("Nominee1");
} else if (nominee2.checked == true) {
updatePoll("Nominee2");
} else if (nominee3.checked == true) {
updatePoll("Nominee3");
}
}
function updatePoll(entry) {
const voteUpdate = (parseInt(localStorage.getItem(entry), 10) || 0) + 1;
localStorage.setItem(entry, voteUpdate);
document.querySelector(`#${entry.replace('Nominee', 'nom')}`).innerText = voteUpdate;
}
<fieldset>
<legend>
<h3>Vote For Your Favorite Chef! </h3>
</legend>
<form onsubmit="incrementPoll(event)" id="pollForm">
<input type="radio" id="Nominee1" name="Nominee" value="Reynold Poernomo" required/>
<label for="Nominee1"> Reynold Poernomo </label>
<span id="nom1" class="vote"></span>
<br/>
<input type="radio" id="Nominee2" name="Nominee" value="Christine Tania" required>
<label for="Nominee1.1"> Christine Tania </label>
<span id="nom2" class="vote"></span>
<br/>
<input type="radio" id="Nominee3" name="Nominee" value="Christina Tosi" required>
<label for="Nominee2"> Christina Tosi </label>
<span id="nom3" class="vote"></span> <br />
<br/>
<input type="submit">
</form>
</fieldset>
Since the snippet won't work because localStorage is not accessible in an SO snippet, here is a fiddle
Related
let opinions = [];
if (localStorage.myTreesComments) {
opinions = JSON.parse(localStorage.myTreesComments);
}
console.log(opinions);
const myFrmElm = document.getElementById("opnFrm");
myFrmElm.addEventListener("submit", processOpnFrmData);
function processOpnFrmData(event) {
const nopName = document.getElementById("menoapriezvisko").value.trim();
const nopEmail = document.getElementById("email").value.trim();
const nopUrl = document.getElementById("url").value.trim();
const nopComm = document.getElementById("komentar").value.trim();
const nopStar1 = document.getElementById("star-rating").value.trim();
const nopStar2 = document.getElementById("star-rating2").value.trim();
const nopScale = document.getElementById("scale-rating").value.trim();
const nopWillReturn = document.getElementById("willReturnElm").checked;
if (nopName == "" || nopEmail == "" || nopUrl == "" || nopComm == "") {
window.alert("Prosím, zadajte všetky údaje.");
return;
}
const newOpinion = {
name: nopName,
email: nopEmail,
url: nopUrl,
comment: nopComm,
gdpr: nopWillReturn,
created: new Date()
};
console.log("Nový názor návštevníka:\n " + JSON.stringify(newOpinion));
opinions.push(newOpinion);
localStorage.myTreesComments = JSON.stringify(opinions);
//4. Notify the user
window.alert("Tvoj názor bol uložený! Pre viac info nahliadni do konzole.");
console.log("Nový názor bol pridaný!");
console.log(opinions);
//5. Reset the form
myFrmElm.reset();
}
<form id="opnFrm">
<label for="menoapriezvisko">Meno a priezvisko</label>
<input type="text" id="menoapriezvisko" name="menoapriezvisko">
<label for="email">Kontaktný email</label> <input type="email" id="email">
<label>1. Celková spokojnosť s dizajnom a funkcionalitou stránky ?</label><br>
<span class="star-rating">
<input type="radio" name="rating1" value="1"><i></i>
........................
<input type="radio" name="rating1" value="5"><i></i>
</span>
<div class="clear"></div>
<hr class="survey-hr">
<label>2. Celková spokojnosť s obsahom.</label><br>
<span class="star-rating2">
<input type="radio" name="rating2" value="1"><i></i>
..........................
<input type="radio" name="rating2" value="5"><i></i>
</span>
<div class="clear"></div>
<hr class="survey-hr">
<label style="color: red;"><b>3. Celkové hodnotenie stránky (1-10)</b></label>
<span class="scale-rating">
<label value="1">
<input type="radio" name="rating" >
<label style="width:100%;"></label>
</label>
<label value="2">
<input type="radio" name="rating" >
<label style="width:100%;"></label>
</label>
..................
<label value="10">
<input type="radio" name="rating" value="10">
<label style="width:100%;"></label>
</label>
</span>
<div class="clear"></div>
<input style="background:#43a7d5;color:#fff;padding:12px;border:0" type="submit" value="Odoslať">
<button type="submit">Odošli</button>
<input style="background:#43a2d1;color:#fff;padding:12px;border:0" type="reset" value="Resetuj">
</form>
</div>
</article>
I need to write values from 3 spans of radio buttons to my JS script into const Opinions.
In first 2 spans I have star rating from 1-5 and in the third span I have points (1-10).. I need to read these values and write them into my script. Please if u can help me i would be really pleased. It is hard for me.
I am using jQuery and Javascript.
Thanks for any help.
i want to get all of this input values to my budget app
but i have problem to get values of the radio button because it says its undefined. i create global function to get by radio button value. but the others is in javascript module.
https://jsfiddle.net/8k3gw7ty/
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
Actually there was no default value for your val variable. Since val will only get value when you click on the checkbox (according to your code).
Also you were returning val which isn't necessary. I've also removed the budgetController.
Hope this'll help.
let val = 'inc'; // default value
function getButtonValue() {
var type = document.getElementsByName("type");
if (type[0].checked) {
val = type[0].value
} else if (type[1].checked) {
val = type[1].value
}
}
const domController = (function() {
return {
getInput: function() {
return {
type: val,
description: document.querySelector(".input_description").value || 0,
value: parseFloat(document.querySelector(".input_value").value) || 0
}
}
}
})();
const controller = (function( UI) {
var ctrlAddItem = function() {
var input = UI.getInput();
console.log(input);
}
document.querySelector(".addbtn").addEventListener("click", ctrlAddItem)
document.addEventListener("keypress", function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
})( domController);
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
<button><i class="fas fa-check addbtn">Save</i></button>
I currently have been working on this code and I can't seem to figure it out. I am planning to make it so that if the radio button is pressed that shipping is not free, that an input field pops up to specifying what the addition cost will be using DOM. I am also trying to figure out how to add text to describe the input field, and to validate the input field.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
c++;
alert("Added Text Box");
}
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id = "tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked /> Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;"/> No
<p class="boldParagraph" id = "emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br><br>
<button>Submit</button>
</form>
</body>
</html>
Create a label element and populate text using innerHTML. and then append to DOM.
Example Snippet:
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : ";
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
c++;
alert("Added Text Box");
}
}
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button>Submit</button>
</form>
OR
You can keep the text box hidden and show it when user clicks no. Also, apply validations only when no is selected for shipment radio button.
I suggest use jQuery, see the snippet below:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
var radioButtons = $("[name=tip3]");
radioButtons.on("change", function() {
if ($("[name=tip3]:checked").val() == "3") {
$("#shipmentDetail").hide();
} else {
$("#shipmentDetail").show();
}
})
$("#submit").on("click", function() {
var flag = true;
if ($("[name=tip3]:checked").val() == "4") {
if ($("#shipmentDetail").val() == "") {
flag = false;
alert("enter some value");
}
}
//other validations here
if (flag) {
$("#form").submit()
}
})
#shipmentDetail {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="#" method="post">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" />No
<label id="shipmentDetail" for="price">Shipment Cost:
<input id="price" type="text" value="" />
</label>
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button id="submit">Submit</button>
</form>
replace
alert("Added Text Box");
with:
var additional_fees = prompt("Type in");
x.setAttribute("value", additional_fees)
I want to limit how many checkbox clicked. When it reaches to the limit I want to trigger an action. Let's say max limit is 3 and min limit is 1. Here's my html.
<div class="ingredients">
<span class="border-bottom"></span>
<div class="row cf">
<label tabindex="1" class="mnf-checkbox" for="tuzCheck">
<span class="ck"></span>
<input id="tuzCheck" type="checkbox"
name="information" value="1" />
<span class="name">Tuz</span>
</label>
<label tabindex="2" class="mnf-checkbox" for="karnibaharCheck">
<span class="ck"></span>
<input id="karnibaharCheck" type="checkbox"
name="information" value="2" />
<span class="name">Karnıbahar</span>
</label>
<label tabindex="3" class="mnf-checkbox" for="biberCheck">
<span class="ck"></span>
<input id="biberCheck" type="checkbox"
name="information" value="3" />
<span class="name">Biber</span>
</label>
<label tabindex="4" class="mnf-checkbox" for="sosisCheck">
<span class="ck"></span>
<input id="sosisCheck" type="checkbox"
name="information" value="4" />
<span class="name">Sosis</span>
</label>
<label tabindex="5" class="mnf-checkbox" for="prasaCheck">
<span class="ck"></span>
<input id="prasaCheck" type="checkbox"
name="information" value="5" />
<span class="name">Prasa</span>
</label>
</div>
</div>
I tried to use this code but that doesn't help me.
var maxCheckedCount = 3;
jQuery('input[type=checkbox]').click(function () {
var n = jQuery('input:checked').length;
if (n >= maxCheckedCount) {
$(this).prop('checked', false);
$(".counter").text("hakkın kalmadı :(").css("color", "#cd1212");
}
});
What I want to do is: when it reaches its limit I want to trigger an action and the user can't continue to check. I'm beginner so please don't judge me :)
Try this one...
http://jsfiddle.net/ZpqQ2/3/
var max = 3;
jQuery('input[type=checkbox]').click(function () {
var n = jQuery('input:checked').length;
if (n > max) {
// here your code
$(this).prop('checked', false);
alert('Minimum of 3');
}
});
try the Fiddle
jQuery('input[type=checkbox]').click(function() {
var n = jQuery('input[type=checkbox]:checked').length;
if (n >= 1 && n <= 3) {
// here your code
}
});
var countChecked = function () {
var n = $("input:checked").length;
alert("n>>>" + n);
$("div").text(n + (n === 1 ? " is" : " are") + " checked!");
if(n == 2){
$("input:checkbox:not(:checked)").attr("disabled", true);
} else {
$("input:checkbox:not(:checked)").attr("disabled", false);
}
};
countChecked();
$("input[type=checkbox]").on("click", countChecked);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="newsletter" class="newsletter" value="Hourly">
<input type="checkbox" name="newsletter" class="newsletter" value="Daily">
<input type="checkbox" name="newsletter" class="newsletter" value="Weekly">
<input type="checkbox" name="newsletter" class="newsletter" value="Monthly" >
<input type="checkbox" name="newsletter" class="newsletter" value="Yearly">
</p>
The problem is I still contunie to check after an alert. That doesn't restrict me to check.
Am trying to validate the date on a form so that user cannot select a date in the past, or that checkout date is greater than checkin date
<form action="form2email.php" method="post" name="form" target="_blank" onSubmit="return validate(form);">
<fieldset id="user-1">
<h2>
<img src="images/booking-enquiry.png" width="160" height="20" />
</h2>
<label for="name">Name:</label>
<input name="name" type="text" />
<label for="email" class="required">Email:</label>
<input type="text" name="email" size="8" id="email" />
</fieldset>
<fieldset id="user-2">
<h2> </h2>
<label for="Phone" class="required">Phone:</label>
<input type="text" name="Telephone_Number" id="Phone" />
<label for="Accommodation Type" class="required">Accommodation Type:</label>
<select id="room_type" name="Accommodation Type">
<option value="Villa">Villa</option>
<option value="1 Bed Apartment">1 Bed Apartment</option>
<option value="2 Bed Apartment">2 Bed Apartment</option>
</select>
</fieldset>
<fieldset id="user-3">
<h2> </h2>
<label for="Check-in-Date" class="required">Check-in Date:</label>
<script>
DateInput('checkindate', true, 'DD-MON-YYYY')
</script>
<label for="Check-out-Date" class="required">Check-out Date:</label>
<script>
DateInput('checkoutdate', true, 'DD-MON-YYYY')
</script>
<label>
<div style="padding-top:10px;font-size:14px;color:white;">
<p>Total Charges: <span id="tot_charges">1995.00</span> THB
</p>
<p class="VAT"><span> Prices exclude VAT # 7%</span>
</p>
</div>
</label>
</fieldset>
<fieldset id="user-4">
<h2> </h2>
<label for="Comments" class="required">Comments :</label>
<textarea name="Comments"></textarea>
<div>
<label style="padding:0;">Please read our cancellation policy
</label>
<input type="checkbox" name="checkbox" id="checkbox" value="I agree to cancellation policy">
<label for="checkbox" id="agree" name="agree">I agree to cancellation policy</label>
</div>
<input type="submit" value="Submit" />
</fieldset>
</form>
<SCRIPT LANGUAGE="JavaScript">
function validate() {
var frm = document.forms["form"];
if (frm.checkbox.checked == false) {
alert("Please Agree To Our Cancellation Policy.");
return false;
} else return true;
}
</SCRIPT>
<script type="text/javascript">
var frmvalidator = new Validator("form");
frmvalidator.addValidation("Email", "maxlen=100");
frmvalidator.addValidation("Email", "req");
frmvalidator.addValidation("Email", "email");
frmvalidator.addValidation("Phone", "req");
frmvalidator.addValidation("Phone", "maxlen=100");
frmvalidator.addValidation("Phone", "numeric");
frmvalidator.setAddnlValidationFunction(validate);
</script>
Was trying to integrate something like this in :
function validateTheDate() {
var dateOK = false;
var Today = new Date();
if (Response_Requested_By_Object.picked.date < Today)
alert('Cannot select a date in the past.');
else if (Response_Requested_By_Object.picked.yearValue > 2020)
alert('Cannot select dates beyond 2020.');
else
dateOK = true;
return dateOK;
}
But not quite sure how to do it with existing validation there ?!?
This is how the validateDate function should look like:
function validateDate(){
var dateOK = false;
var today = new Date();
var startDt = new Date(document.getElementById("checkin").value).getTime();
var endDt = new Date(document.getElementById("checkout").value).getTime();
if (startDt < today || endDt < today)
alert('Cannot select a date in the past.');
else if (startDt > 2020 || endDt > 2020)
alert('Cannot select dates beyond 2020.');
else if(startDt > endDt){
alert ('Checkout date is greater than Checkin date.');
dateOK = true;
}
}
to add this custom function to you validator, just need to:
frmvalidator.setAddnlValidationFunction(validateDate);
Note: I'm sure there is a lot of (Javascript) Jquery plugins very good for validate forms and dates (using alert is not cool).