On form submit all options why are all options selected? [duplicate] - javascript

This question already has answers here:
Variable assignment inside an 'if' condition in JavaScript
(6 answers)
Closed 6 months ago.
I am trying to create a mock smoothie ordering form with javascript and html checkboxes. When I submit the form all options are selected and I am not sure why.
<form name="smoothieForm" onsubmit="return false" action="#" method="get">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<p>Liquid/Dairy Ingredients (Check all that you would like)</p>
<input type='checkbox' id="yogurt">Yogurt
<input type='checkbox' id="milk">Milk
<input type='checkbox' id="oatmilk">Oat Milk
<input type='checkbox' id="soymilk">Soy Milk
<input type='checkbox' id="ice">Ice
<p>Fruit/Vegetable Ingredients (Check all that you would like)</p>
<input type='checkbox' id="spinach">Spinach
<input type='checkbox' id="strawberries">Strawberries
<input type='checkbox' id="avocado">Avocado
<input type='checkbox' id="blueberries">Blueberries
<input type='checkbox' id="mango">Mango
<input type='checkbox' id="bananas">Bananas
<p>Miscellaneous Ingredients (Check all that you would like)</p>
<input type='checkbox' id="chocolate">Chocolate
<input type='checkbox' id="proteinpowder">Protein Powder
<input type='checkbox' id="matcha">Matcha
<input type="submit" value="Submit" onclick="validateForm()">
</form>
<img/>
<p id="orderResults"></p>
function validateForm() {
let x = document.forms["smoothieForm"]["fname"].value;
let y = document.forms["smoothieForm"]["lname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
if (y == ""){
alert("Name must be filled out");
return false;
}
let name = x + y;
let ld = '';
if(document.getElementById("yogurt").checked = true){
ld += " yogurt ";
}
if(document.getElementById("milk").checked = true){
ld += " milk ";
}
if(document.getElementById("oatmilk").checked = true){
ld += " oatmilk ";
}
if(document.getElementById("soymilk").checked = true){
ld += " soymilk ";
}
if(document.getElementById("ice").checked = true){
ld += " ice ";
}
let fv = '';
if(document.getElementById("spinach").checked = true){
fv += " spinach ";
}
if(document.getElementById("strawberries").checked = true){
fv += " strawberries ";
}
if(document.getElementById("avocado").checked = true){
fv += " avocado ";
}
if(document.getElementById("bananas").checked = true){
fv += " bananas ";
}
if(document.getElementById("blueberries").checked = true){
fv += " blueberries ";
}
if(document.getElementById("mango").checked = true){
fv += " mango ";
}
let m = '';
if(document.getElementById("matcha").checked = true){
m += " matcha ";
}
if(document.getElementById("chocolate").checked = true){
m += " chocolate ";
}
if(document.getElementById("proteinpowder").checked = true){
m += " proteinpowder ";
}
s = 'Congrats ' + name + ', your order is submitted! You chose: ' + ld + 'for liquid/dairy ingredients, and ' + fv +
'for your fruits and vegetables as well as ' + m + 'for your miscellaneous ingredients, enjoy!';
printOrder(s);
}
function printOrder(s){
document.getElementById("orderResults").innerHTML= s;
const img = document.querySelector("img");
img.src = "img/smoothie.svg";
}
I know this code is pretty ugly but I would just like to be able to create that concatenated string and output to my p element, without it doing this
What it does when I submit

In validateForm(), all of your if statements are using single equals signs, which is for assignment. Switch them to == (for comparison) and you should get a result closer to what you're expecting.

Because you're using assignment statement =, not comparison statement == in your if conditions which will always going to give true
You should use ==
if(document.getElementById("yogurt").checked == true){
ld += " yogurt ";
}

Related

How can I find if a specific checkbox is checked?

I've looked at lots of posts but I couldn't find anything that works in my case. I need to display of a preview of the user's signature in their profile, with the options to not show their phone number and/or email address so I have a checkbox for each.
Here's my HTML for the checkboxes:
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showPhoneId" value="showPhone" class="checkbox style-0" checked="checked">
<span>Teléfono</span>
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showEmailId" value="showEmail" class="checkbox style-0" checked="checked">
<span>Dirección de e-mail</span>
</label>
</div>
and here is the jQuery:
var fname = $('#personalOptionsForm').find('[name="fname"]').val(),
lname = $('#personalOptionsForm').find('[name="lname"]').val(),
cellphone = $('#personalOptionsForm').find('[name="cellphone"]').val(),
email = $('#personalOptionsForm').find('[name="email"]').val(),
if ($('#showPhoneId').is(':checked') = true) {
showPhone = 1;
} else {
showPhone = 0;
},
// showPhone = (($('input[name="showInSignature[]"]')['showPhone'].checked = true) ? 1 : 0),
// showEmail = (($('input[name="showInSignature[]"]')['showEmail'].checked = true) ? 1 : 0),
str = "<strong>" + fname + " " + lname + "</strong><br /><br />" + ((showPhone = 1) ? 'Teléfono: ' + cellphone + '<br />' : '') + "E-mail: " + email + "",
html = $.parseHTML( str );
$('#signaturePreview').append(html);
If I comment out the IF (as I've commented out other tries I've made) and the ternary operator in the str var it works but NOTHING is displayed when trying to use a dynamic value (like the phone checkbox). There's only two methods there but I've tried many more. None of them work. Nothing is appended.
How can I do it? Thanks in advance!
showPhone = $('#showPhoneId').is(':checked');
surely that's all you need. It returns a boolean
$(document).ready(function() {
alert('Is Checked: ' + $('#showPhoneId')[0].checked);
console.log(typeof $('#showPhoneId')[0].checked);
console.log($('#showPhoneId')[0].checked === true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showPhoneId" value="showPhone" class="checkbox style-0" checked="checked">
<span>Teléfono</span>
</label>
</div>
In your code you are using assignment operator "=" which means
a = b (value of b is assigned to a),
in your case you are trying to assign true to $('#showPhoneId').is(':checked')
kindly"==" instead
var fname = $('#personalOptionsForm').find('[name="fname"]').val() ,
lname = $('#personalOptionsForm').find('[name="lname"]').val() ,
cellphone = $('#personalOptionsForm').find('[name="cellphone"]').val(),
email = $('#personalOptionsForm').find('[name="email"]').val(),
//dummy values
fname = 'abc', lname="dksjdn",
cellphone = "98989898", email = "abc#gmail.com";
if($('#showPhoneId').is(':checked') == true) {
showPhone = 1;
} else {
showPhone = 0;
};
// showPhone = (($('input[name="showInSignature[]"]').is(':checked') == true) ? 1 : 0),
// showEmail = (($('input[name="showInSignature[]"]').is(':checked') == true) ? 1 : 0),
str = "<strong>" + fname + " " + lname + "</strong><br /><br />" + ((showPhone == 1) ? 'Teléfono: ' + cellphone + '<br />' : '') + "E-mail: " + email + "",
html = $.parseHTML( str );
$('#signaturePreview').append(html);
please refer https://jsbin.com/rolodozode/1/edit?html,js,output

Loading data on the same form page after submitting

I have a tiny problem with this college assignment. When the user inputs their data, an account id number is created. I've worked on that and it works like it should. But here's the problem: after the user clicks the submit button and the account id number is created, what they entered needs to be displayed below it. The assignment says I need to create a function called displayNewAccount and put in into one of the other functions. I put in inside the createEventListeners function. The text needs to be displayed in a custom ID (account) on the HTML page. The data entered into the first name input (fnameinput) should display after "First Name" (fname) and the last name input (lnameinput) should display after "Last Name" (lname) and so on. If the displayNewAccount function has to be moved inside another function then that is totally fine. I've looked online and found several examples, but I couldn't get them to work for me. What am I doing wrong? Thanks for the help.
HTML
<article>
<h2>New Account Information</h2>
<form>
<fieldset id="deliveryinfo">
<label>First Name</label><input type="text" id="fnameinput" name="fname">
<label>Last Name</label><input type="text" id="lnameinput" name="lname">
<label>Street Address</label><input type="text" id="addrinput" name="address">
<label>City</label><input type="text" id="cityinput" name="city">
<label>State</label><input type="text" id="stateinput" name="state">
<label>Zip</label><input type="text" id="zipinput" name="zip">
<label>Account ID</label><input type="text" id="accountidbox" name="accountid">
<input type="button" id="submitBtn" value="Create Account">
</fieldset>
<!-- New section -->
<fieldset>
<div id="account">
<!-- Data is displayed in here. -->
</div>
</fieldset>
</form>
</article>
JavaScript
var newAccountObject = {};
var newAccountSubmission;
function createID() {
var fname = document.getElementById("fnameinput");
var lname = document.getElementById("lnameinput");
var zip = document.getElementById("zipinput");
var account = document.getElementById("accountidbox");
var fields = document.getElementsByTagName("input");
var acctid;
var firstInit;
var lastInit;
if (fname !== "" || lname !== "" || zip !== "") {
firstInit = fname.value.charAt(0).toUpperCase();
lastInit = lname.value.charAt(0).toUpperCase();
acctid = firstInit + lastInit + zip.value;
account.value = acctid;
newAccountObject = {};
for(var i = 0; i < fields.length - 1; i++) {
newAccountObject[fields[i].name] = fields[1].value;
}
}
}
function createString() {
newAccountSubmission = JSON.stringify(newAccountObject);
}
function createEventListeners() {
var fname = document.getElementById("fnameinput");
var lname = document.getElementById("lnameinput");
var zip = document.getElementById("zipinput");
if (fname.addEventListener) {
fname.addEventListener("change", createID, false);
lname.addEventListener("change", createID, false);
zip.addEventListener("change", createID, false);
}
else if (fname.attachEvent) {
fname.attachEvent("onchange", createID);
lname.attachEvent("onchange", createID);
zip.attachEvent("onchange", createID);
}
if (button.addEventListener) {
button.addEventListener("click", createString, false);
}
else if (button.attachEvent) {
button.attachEvent("onclick", createString);
}
// Displays an account summary section when the "Create Account" button is clicked.
function displayNewAccount() {
document.getElementById("account").innerHTML = "First Name: " + fname + "<br>" + "Last Name: " + lname + "<br>" + "Address: " + addrinput + "<br>" + "City: " + cityinput + "<br>" + "State: " + stateinput + "<br>" + "Zip: " + zipinput + "<br>" + "Account ID: " + accountidbox;
}
if (window.addEventListener) {
window.addEventListener("click", displayNewAccount, false);
}
else if (window.attachEvent) {
window.attachEvent("onclick", displayNewAccount);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}

How do I capture values (JavaScript Only) of each text box and display them?

I am building a form using JavaScript and HTML only (business need - no server access). I have a list of textboxes that I need the values from. The user has the option of either filling out 1 textbox, or as many as they need up to 35. I COULD create a function for each individual box
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
if (a != '' && b != '' && c != '') {
var abc = "this is a: " + a + "this is b: " + b + "and this is c:" + c;
}
and I could make a function for each scenario of each value:
if(a != '' && b != '' && c == '') {
var ab = "this is a: " + a + " and b: " + b + "but not c";
}
if(a != '' && b == '' && c != '') {
var ac = "this is a: " + a + " and c: " + c + "but not b";
}
if(a != '' && b == '' && c == '') {
var a-only = "this is a: " + a + " but not b or c";
}
if(a == '' && b != '' && c != '') {
var bc = "this is b: " + b + " and c: " + c + " but not a";
}
That's not even every scenario for just 3 variables, but I could potentially have up to 35 different variables that I need to make a function for each scenario which is a huge chunk of time and space and I think after about 10 of them, it will get too messy and hard to maintain later if I need let alone all 35.
I feel like there must be a far more efficient way of capturing the values and displaying them if they are not empty other than going through each possible scenario.
My textboxes are dynamically created by clicking an "Add More" button
JavaScript:
var max_fields = 35;
var x = 0;
$('#add').click(function(e) {
e.preventDefault();
if(x < max_fields){
x++;
var inps = $('#wrapper >div:last').data('count')+1 || 1;
$('#wrapper').append('<div class="date-time-list" data-count="'+inps+'"><input type="text" name="date_count' + inps + '" id="date_count'+inps+'" class="inp"/><input type="text" name="time_count' + inps + '" id="time_count'+inps+'" class="inp"/><a class=remove>Remove</a><br><br></div>');
}
});
$('#wrapper').on('click' , 'a.remove' ,function(){
var inps = $('#wrapper > div:last').data('count')-1 || 1;
x--;
$(this).closest('div').remove();
});
HTML:
<tr class="list" style="line-height:1em;">
<td>
Please fill in the dates and times
</td>
<td>
<strong>Dates</strong> <strong>Times</strong>
</td>
</tr>
<tr class="list" style="line-height:1em;">
<td>
</td>
<td>
<span id="wrapper">
</span>
</td>
</tr>
<tr class="list">
<td>
</td>
<td>
<button id="add">Add More</button>
</td>
</tr>
Please have a look at this little snippet: https://jsfiddle.net/0h52y0Ly/1/
$( document ).ready(function() {
$('button').click(function(){
var content = '';
var countOfTextareasFilled = 0;
$('textarea').each(function(){
if ($(this).val().length){
content += $(this).val() + '\n\n';
countOfTextareasFilled++;
}
});
alert(countOfTextareasFilled + ' text boxes have been filled. Contents are:\n\n' +content);
});
});
It shows a very generic approach to your task. You should be able to adapt it to your needs very easily.
EDIT:
I am fairly certain, that adapting a perfectly functioning generalized solution to your special use case, is something you should do yourself. But here it is:
https://jsfiddle.net/cb7ujmsw/
$('#evaluate').click(function(){
var content = '';
var data = [];
var dateField, timeField;
$('.date-time-list').each(function(){
dateField = $('#date_count' + $(this).data('count'));
timeField = $('#time_count' + $(this).data('count'));
if (dateField.val().length && timeField.val().length){
data.push({
date: dateField.val(),
time: timeField.val()
});
}
});
alert(data.length + ' complete datetimes. Data:\n\n' +JSON.stringify(data));
});
I added a button with the ID "evaluate". The rest is completely your code.
Assuming you have a way to select all relevant inputs (in this example all elements have the check-me class)
$(function(){
$('.do-the-check').on('click', function(e){
e.preventDefault();
var inputs = $('.check-me', this.form),
empty = inputs.filter(function(){return this.value === ''}),
nonempty = inputs.not(empty),
message = 'This is ';
if (nonempty.length){
message += nonempty.map(function(){return this.name + ':' + this.value}).get().join(' and ');
}
if (empty.length){
if (nonempty.length){
message += ' but ';
}
message += 'not ' + empty.map(function(){return this.name;}).get().join(' or ');
}
alert(message);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
a:<input name="a" class="check-me"><br/>
b:<input name="b" class="check-me"><br/>
c:<input name="c" class="check-me"><br/>
d:<input name="d" class="check-me"><br/>
e:<input name="e" class="check-me"><br/>
f:<input name="f" class="check-me"><br/>
g:<input name="g" class="check-me"><br/>
h:<input name="h" class="check-me"><br/>
i:<input name="i" class="check-me"><br/>
j:<input name="j" class="check-me"><br/>
<button class="do-the-check">check them</button>
</form>

Multiple input fields using JS

Got the following JS code:
<script language="javascript">
fields = 0;
pNR = 0;
err = 0;
function addInput() {
if (fields != 40) {
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
fields += 1;
pNR += 1;
} else {
if (err == 0) {
document.getElementById('text').innerHTML += "<br />Adaugati maxim 40 ingrediente.";
err = 1;
}
document.form.add.disabled = true;
}
}
</script>
and the following HTML:
<input name="name" style="color:#ffffff;" class="name required" type="button" onclick="addInput()" value="Add" />
<div id="text">
</div>
By default, there are no fields. When I press the Add button (fields are added two by two with different names), fill in the fields and click again the Add button, the filled fields are emptied. What did I do wrong?
You aren't simply adding new inputs.
You are:
converting the existing ones to HTML (the value attribute is unchanged, it will still have the default value, not the current value)
adding the HTML for the new inputs to it
generating new DOM elements from that HTML.
Don't use innerHTML. Use createElement, appendChild and friends.
This:
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
Becomes this:
var firstInput = document.createElement("input");
var secondInput = document.createElement("input");
firstInput.type = secondInput.type = "text";
firstInput.name = "first" + pNR;
secondInput.name = "second" + pNR;
var text = document.getElementById("text");
text.appendChild(firstInput);
text.appendChild(secondInput);
text.appendChild(document.createElement("br"));
And, for the else case:
var text = document.getElementById("text");
text.appendChild(document.createElement("br"))
text.appendChild(document.createTextNode("Adaugati maxim 40 ingrediente."));
Working example: http://jsbin.com/OqIWeMum/2/edit

If statements with radio buttons not assigning variables

I'm trying to learn about form building. I have form in which I would like to assign the value of certain variables to certain form fields, based on which radio button is selected. But my code is always defaulting to the first radio choice, no matter which one I select.
I've tried to chain 'if' conditions, if/else conditions and alter variable names, but it doesn't make a difference.
I've also found that the code doesn't work in JSfiddle (http://jsfiddle.net/GEZPU/1/), but I'm not sure why it says the function is not defined?.
HTML
Input 1
<select id="box0">
<option>Tampa</option>
<option>Phoenix</option>
</select>
<br>
<br>Input 2
<select id="box1">
<option>Bucs</option>
<option>Cards</option>
</select>
<br>
<br>If option radios
<br>
<br>
<input type="radio" id="box2" name="football" value="No Data">No Data
<br>
<br>
<input type="radio" id="box3" name="football" value="No Playoffs">No Playoffs
<br>Games to go?
<input id="box4" size="10">Superbowl location?
<input id="box5" size="10">
<br>
<br>
<input type="radio" id="box6" name="football" value="Yes Playoffs">Made Playoffs
<br>Superbowl location?
<input id="box7" size="10">
<p>
<input value="Write summary" onclick="writetext()" type="button">
<br>
<form>
<textarea rows="35" cols="45" placeholder="Template" id="output"></textarea>
</form>
<br>
</p>
Code
function writetext() {
var mytext = document.getElementById('output');
var captext = "";
// Checklist variables
var box_0 = $("#box0").val();
var box_1 = $("#box1").val();
captext += box_0 + "\n - " + box_1 + "\n ";
if ($('#box2').prop("checked ", true)) {
var box_margin = $("#box2").val();
captext += "\nMargins: \n - " + box_margin + "\n ";
}
if ($('#box3').prop("checked ", true)) {
var box_margin2 = $("#box3").val();
var box_margin_dist = $("#box4").val();
var box_margin_site = $("#box5").val();
captext += "\nMargins: \n - " + box_margin2 + "\n - Dist: " + box_margin_dist + "\n - margin " + box_margin_site + "\n ";
}
if ($('#box6').prop("checked ", true)) {
var box_margin3 = $("#box6 ").val();
var box_margin_site3 = $("#box7 ").val();
captext += "\nMargins: \n - " + box_margin3 + "\n - (Specify margin)" + box_margin_site3 + "\n ";
}
mytext.value = captext;
}
if ($('#box2').prop("checked ", true)) {
is always true.. I think you are trying to compare if it is set to true or false.
Supposed to be
if ($('#box2').prop("checked ")) {
It is always a good idea to avoid attaching events inline. Attach the events using javascript
Also you can simply use is(':checked') method to check if the radio is checked or not.
I observed that you are, using the same jQuery object in multiple places. It would be better to cache them in such instances as it will improve the performance.
And the same code can be refactored a bit ..
UPDATE
$('#write').click(write);
function write() {
var mytext = document.getElementById('output'),
captext = "",
// box elements
$box_0 = $('#box0'),
$box_1 = $('#box1'),
$box_2 = $('#box2'),
$box_3 = $('#box3'),
$box_4 = $('#box4'),
$box_5 = $('#box5'),
$box_6 = $('#box6'),
$box_7 = $('#box7'),
// Checklist variables
box_0 = $box_0.val();
box_1 = $box_1.val();
captext += box_0 + "\n - " + box_1 + "\n ";
// All the radios have the same name.
// So only 1 radio will be checked at any point of time
// This would give you the radio that is checked
var $radio = $('input[type=radio][name=football]:checked');
if ($radio.length) {
captext += "\nMargins: \n - " + $radio.val() + "\n ";
if ($radio.is($box_3)) {
captext += "\n - Dist: " + $box_4.val() + "\n - margin " + $box_5.val() + "\n ";
} else if ($radio.is($box_6)) {
captext += "\n - (Specify margin)" + $box_7.val() + "\n ";
}
}
mytext.value = captext;
}
Check Fiddle
If you take a look at http://api.jquery.com/prop/ you'll notice that .prop("checked") returns true or false while .prop("checked", true) assigned the value 'true' to the property "checked". Try switching those out and see what happens.

Categories