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
Related
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 ";
}
I need to add checkbox dynamically by entering the label name.
Here I can add checkbox, but problem is if same label(case sensitive) is already present it should not allow user to add. Please help on this. Thanks in advance.
HTML
<input type="button" value="add" onClick="add()" />
<ul id="container" style="list-style-type:none;">
</ul>
Script
var i=0;
function add() {
var label = prompt("Please enter label name", "");
if (label != null || label != "") {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
Jsfiddle
Store the labels in an array and check whether the new label is present in that array or not, then proceed inserting the new element.
var i = 0;
var labels = [];
function add() {
var label = prompt("Please enter label name", "");
if (label != null || label != "") {
if (labels.indexOf(label) == -1) {
labels.push(label); i++;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">' + labels[labels.length - 1] + '</label>';
document.getElementById('container').appendChild(node);
} else {
alert("labels should be unique!")
}
}
}
DEMO
You can try something like this:
var i=0;
function add() {
var label = prompt("Please enter label name", "");
var exists = document.evaluate('//label[text()="' + label + '"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, exists).snapshotItem(0);
if (exists) {
return;
}
if (label != null || label != "") {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
You can use data attribute and querySelector to check for the existance.
var i=0;
function add() {
var label = prompt("Please enter label name", "");
var labels = ;
if ((label != null || label != "") && !document.querySelector('label[data-value="'+label+'"]')) {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '" data-value="'+title+'">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
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);
}
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>
I've been struggling with this for around an hour now and rewrote it about three different times and I can't for the life of me figure out what the issue is, regardless of what is entered, everything besides for the name field will return a value, however the name will just return undefined. I've gone over this so many times, I've copy+pasted+modified the working ones, there's not a single typo that I can find... What is going on here?
Item Name: <input type="text" id="item_name" placeholder="Enter a price..."/> </br>
Item Price: <input type="text" id="item_price" placeholder="Enter a price..."/> </br>
Item Description: <input type="text" id="item_description" placeholder="Enter a description..."/> </br>
Item Image(link): <input type="text" id="item_image" placeholder="Enter a image link..."/> </br>
rsid: <input type="text" id="rs_item_id" placeholder="Enter a item id..."/> </br>
rsam: <input type="text" id="rs_item_amount" placeholder="Enter a item amount..."/> </br>
<button id="update">Update item</button>
<script>
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
var button = document.getElementById("update");
button.addEventListener("click", function() {
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
</script>
The problem is that because you make them all global variables the name one clashes with the window.name property.
Either using a different variable name, or creating a closure will work
Put name, price, desc, img, rsid, rsam inside event handler.
var button = document.getElementById("update");
button.addEventListener("click", function() {
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
Demo: http://jsbin.com/fivos/1/edit?html,output