Basically I have 4 checkbox elements in my form and a text field up top. The text field has a placeholder with a product name — product price format. Each checkbox has a product name and product price as well, and I want to use javascript to change the placeholder value once a checkbox is checked. The issue is that the product price should be a SUM of default placeholder base price and the product price of the checkbox that was checked. The first part of the placeholder should change from product name to product name + product name.
So far I have only been able to use javascript to change the value of the placeholder entirely, which would work if I had only one checkbox, but I have 4 so it doesn't.
In a perfect world the placeholder should display Basic Package + Video + Picture + Tour + Emergency — €30 when all checkboxes are checked, and Basic Package + Picture + Tour — €20 when only Option2 and Option3 are checked. And so on, and so on.
Here is a simplified code of what I am trying to achieve (note: only Video works in my code):
$('.Option1').on('change', function(e) {
if ($(this).is(':checked') === true) {
$('.PriceInput').attr('placeholder', 'Basic Package + Video — €15');
} else $('.PriceInput').attr('placeholder', 'Basic Package — €10');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact-basic" method="post" action="mailer-basic.php">
<div class="field">
<input class="form-control PriceInput" type="text" name="basicpackage" id="basicpackage" placeholder="Basic Package — €10" disabled />
</div>
<div class="field">
<input class="Option1" type="checkbox" id="videobasic" name="optiesbasic[]" value="Video">
<label for="videobasic">Video — €5</label>
</div>
<div class="field">
<input class="Option2" type="checkbox" id="picturebasic" name="optiesbasic[]" value="Picture">
<label for="picturebasic">Picture — €5</label>
</div>
<div class="field">
<input class="Option3" type="checkbox" id="tourbasic" name="optiesbasic[]" value="Tour">
<label for="tourbasic">Tour — €5</label>
</div>
<div class="field">
<input class="Option4" type="checkbox" id="emergencybasic" name="optiesbasic[]" value="Emergency">
<label for="emergencybasic">Emergency — €5</label>
</div>
I've removed the number from each class="Option"
then you can do something like this:
$('.Option').on('change', function(e) {
var s = "";
var p = 10;
$('.Option').each(function() {
if ($(this).is(':checked') === true) {
s += " + " + $(this).val();
var tempP = +$(this).next().text().split('€')[1];
p = p + tempP;
}
});
$('.PriceInput').attr('placeholder', 'Basic Package' + s + ' — €' + p);
});
Demo
$('.Option').on('change', function(e) {
var s = "";
var p = 10;
$('.Option').each(function() {
if ($(this).is(':checked') === true) {
s += " + " + $(this).val();
var tempP = +$(this).next().text().split('€')[1];
p = p + tempP;
}
});
$('.PriceInput').attr('placeholder', 'Basic Package' + s + ' — €' + p);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact-basic" method="post" action="mailer-basic.php">
<div class="field">
<input class="form-control PriceInput" type="text" name="basicpackage" id="basicpackage" placeholder="Basic Package — €10" disabled />
</div>
<div class="field">
<input class="Option" type="checkbox" id="videobasic" name="optiesbasic[]" value="Video">
<label for="videobasic">Video — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="picturebasic" name="optiesbasic[]" value="Picture">
<label for="picturebasic">Picture — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="tourbasic" name="optiesbasic[]" value="Tour">
<label for="tourbasic">Tour — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="emergencybasic" name="optiesbasic[]" value="Emergency">
<label for="emergencybasic">Emergency — €5</label>
</div>
Related
Why does my Priority checkbox return 'on' as a result after selecting either the 'Important' or 'Unimportant' checkbox? Why does it not return either 'Important' or 'Unimportant'?
Also, why does my Category radio selection only return the correct selection the first time I input and click the add button - on every subsequent attempt, the return is blank for Category. All the other input options work correctly.
var $addButton = $(".btn-primary");
var $removeButton = $(".btn-danger");
var $todoList = $(".uncomplete");
var $doneList = $(".completed");
//Take Text Input and Add <li> to To Do List
$addButton.on("click", function(){
//Creating object Variables
var $sort = $(".sort").val();
var $newTask = $(".newTask").val();
var $taskDescr = $(".taskDescr").val();
var $taskDate = $(".taskDate").val();
// var $category= $(".category").val();
var $category= $("input[type='radio'][name='category']:checked").val();
//var $importance = $("input[type='checkbox'][name='importance']:checked").val();
var $importance = $('<input type="checkbox" name="importance"/>').val();
var $newTaskString = $sort + ", " + $taskDescr + ", " + $newTask + ", " + $taskDate + ", " + $category + ", " + $importance + " ";
var $todoList = $(".uncompleted");
//call append method on $todoList
$todoList.append("<li>" + $newTaskString + "<button><span> Done</span></button><button><span> Remove</span></button></li>").addClass("todo");
//add styles to button added to DOM by append
var $span = $(".todo button span");
var $button = $(".todo button");
$button.addClass("btn btn-success");
$span.addClass("glyphicon glyphicon-ok");
$("input").val("");
})
//When Success button Clicked, remove task from to do list and append to completed tasks
var $doneButton = $(".btn-success");
$(".uncompleted").on("click", ".btn-success", function(){
var $completedTask = $( this ).parent("li").text();
$(this).parent("li").remove();
$doneList.append("<li>" + $completedTask + "<button><span> Remove</span></button></li>").addClass("done");
$(".done button").addClass("btn btn-danger");
$(".done button span").addClass("glyphicon glyphicon-remove");
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="list-wrap" contenteditable="false">
<div class="list-inner-wrap">
<h2 class="title">ToDo List</h2>
<h3 class="title">Add Task</h2>
<label for="sort">Sort Order:</label><input type="text" class="sort" name="sort" id="sort" value="" placeholder="A,B,C,etc.">
<br>
<label for="task-name">Task Name:</label><input type="text" class="newTask" name="task-name" id="task-name" value="" placeholder="My task...">
<br>
<label for="task-descr">Task Descr:</label><input type="text" class="taskDescr" name="task-descr" id="task-descr" value="" placeholder="Buy milk...">
<!--<h4>Date</h4>-->
<br>
<label for="task-date">Start Date:</label><input type="text" class="taskDate" name="task-date" id="task-date" value="" placeholder="dd/mm/yyyy">
<br>
<form method="POST" action="..." name="radiodemo" id="radiodemo" onsubmit="getCategory();">
<label for="category"> Category:</label>
<input type="radio" id="grocery" name="category" value="Grocery" class="category" checked="checked">
<label for="grocery">Grocery</label>
<input type="radio" id="work" name="category" value="Work" class="category">
<label for="work">Work</label>
<input type="radio" id="chores" name="category" value="Chores" class="category">
<label for="chores">Chores</label>
<input type="radio" id="finance" name="category" value="Finance" class="category">
<label for="finance">Finance</label>
<br>
</form>
<label for="importance">Priority:</label>    Important<input type="checkbox" class="importance" name="important" id="important" value="Important">
<label for="importance"></label>Unimportant<input type="checkbox" class="importance" name="unimportant" id="unimportant" value="Unimportant">
<br>
<button class="btn btn-primary">
<span class="glyphicon glyphicon-plus"> Add</span>
</button>
<br>
<h3 class="title">To Do</h2>
<h6><i>Click task item to edit or modify</i></h6>
<ul class="uncompleted" id="id01"><!--contenteditable="true"-->
<li>Need to be completed task
<button class="btn btn-success"><span class="glyphicon glyphicon-ok"> Done</span>
</button>
<button class="btn btn-danger"><span class="glyphicon glyphicon-remove"> Remove</span>
</button>
<br>
</li>
</ul>
So I am validating a form - The validation works fine but if the user was to get something wrong it would .after a <p></p> error message. But if the user were to click the button more than once it will keep printing out that .after error message!
I have tried everything - This includes putting a boolean expression in the if statement and once the .after error message prints it will make that expression falseso the if statement won't run again. This did not work for me.
I also can't get the values to print out once the validation is all done!?
To try and fix this I have wrapped tried to wrap the validation in an if statement that tests to see if the validation is true and then at the bottom of the if statement after the validation I make that boolean value turn to false and then I have an else statement which prints out the values for each input...This won't work for me!
jQuery:
// JavaScript Document
$(document).ready(function() {
//Submit the form for validation
$('#submit').click(function ()
{
//Get the values from input fields:
$name = $('#txtName').val();
$age = $('#numAge').val();
//Sex:
$sex = $('sex').val();
//Email:
$email = $('#txtEmail').val();
$confirmEmail = $('#txtConfirmEmail').val();
//Checkbox
$("input[name='interest']:checked").each(function() {
$gender += "" + $(this).val() + ", ";
});
//Fish varieties:
$varieties = $('#txtVariety').val();
//Put checkbox values into an Array
var values = $('input:[name="interest[]"]:checked').map(function () {
return this.value;
}).get();
//printDetails is the id to print out to.
for(var i=0; i<values.length;i++){
alert(values[i]);
}
//Start Validation
if($name.length < 5){
$('#txtName').focus();
$('#txtName').val("");
$('#txtName').after("<p id='after1' style='color:red;'><strong>Enter a name greater than 5 letters!</strong></p>");
return false;
}
else{
$('p').remove('#after1');
$name = $('#txtName').val();
}
if($age.length > 105 || $age.length < 1){
$('#numAge').focus();
$('#numAge').val("");
$('#numAge').after("<p id='after2' style='color:red;'><strong>Enter an Age less than 106 and greater than 0!</strong></p>");
return false;
}
else{
$('p').remove('#after2');
}
function isValidEmailAddress($email) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
// alert( pattern.test(emailAddress) );
return pattern.test($email);
};
if(!isValidEmailAddress($email)){
$('#txtEmail').focus();
$('#txtEmail').after("<p id='after3' style='color:red;'><strong>Enter a valid email - <span style='color:#0078ab;'>"+ $email +"</span> - Is not valid</strong></p>");
$('#txtEmail').val("");
return false;
}
else{
$('p').remove('#after3');
//Now check if the email is successfully confirmed
if($email != $confirmEmail){
$('#txtConfirmEmail').focus();
$('#txtConfirmEmail').after("<p id='after4' style='color:red;'><strong>Your email - <span style='color:#0078ab;'>"+ $confirmEmail +"</span> - Does not match!</strong></p>");
$('#txtConfirmEmail').val("");
return false;
}
else{
$('p').remove('#after4');
}
}
//Check if there is atleast 1 checkbox checked
if($('input[type=checkbox:checked').length < 1) {
$('#checkboxError').html('<p id="after5" style="color:red;" id="after5">Please check atleast one checkbox</p>');
return false;
}
else{
//This should remove the above error message!
$('p').remove('#after5');
}
//These won't work?
document.getElementById("printDetails").innerHTML = $name + $age + $gender + $sex + $varieties + $email;
$("#printDetails").html("<div>" + $name + $age + $gender + $sex + $varieties + $email + " </div");
}); //END OF ONCLICK
}); //End of document.ready
Html
<div data-role="page" id="page2">
<div data-role="header">
<h1>Register jQuery</h1>
</div>
<div data-role="content">
<!-- Name, Age -->
<div data-role="fieldcontain">
<label for="txtName">Name:</label>
<input type="text" name="txtName" id="txtName" value="" />
</div>
<div data-role="fieldcontain">
<label for="numAge">Age:</label>
<input type="number" name="numAge" id="numAge" value="" />
</div>
<!-- Sex, Default value = Male-->
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Sex</legend>
<input type="radio" name="sex" id="sex_male" value="" />
<label for="sex_male">Male</label>
<input type="radio" name="sex" id="sex_female" value="" checked='checked' />
<label for="sex_female">Female</label>
</fieldset>
</div>
<!-- Emails -->
<div data-role="fieldcontain">
<label for="txtEmail">e-mail:</label>
<input type="email" name="txtEmail" id="txtEmail" value="" />
</div>
<div data-role="fieldcontain">
<label for="txtConfirmEmail">Confirm e-mail:</label>
<input type="email" name="txtConfirmEmail" id="txtConfirmEmail" value="" />
</div>
<!-- Interest In checkboxes -->
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>I am interested in the following</legend>
<input type="checkbox" name="interest[]" value='Comet' id="interest_0" class="custom" value="" />
<label for="interest_0">Comet</label>
<input type="checkbox" name="interest[]" value='Common Goldfish' id="interest_1" class="custom" value="" />
<label for="interest_1">Common Goldfish</label>
<input type="checkbox" name="interest[]" id="interest_2" class="custom" value="Black Moor" />
<label for="interest_2">Black Moor</label>
<input type="checkbox" name="interest[]" value='Celestial Eye' id="interest_3" class="custom" value="" />
<label for="interest_3">Celestial Eye</label>
<input type="checkbox" name="interest[]" value='Fantail' id="interest_4" class="custom" value="" />
<label for="interest_4">Fantail</label>
<input type="checkbox" name="interest[]" value='Lionchu' id="interest_5" class="custom" value="" />
<label for="interest_5">Lionchu</label>
<input type="checkbox" name="interest[]" value='Other' id="interest_6" class="custom" value="" />
<label for="interest_6">Other</label>
</fieldset>
</div>
<div data-role="fieldcontain" class='display'>
<label for="txtVariety">Fish Varieties:</label>
<textarea cols="40" rows="8" name="txtVariety" id="txtVariety"></textarea>
</div>
<p id='checkboxError'></p>
<!-- Text Area - Fish Varieties -->
<!-- Drop down select menu - How did u hear about us -->
<div data-role="fieldcontain">
<label for="selectmenu" class="select">How did you hear about us?:</label>
<select name="selectmenu" id="selectmenu">
<option value="Internet">Internet</option>
<option value="Email">Email</option>
<option value="Friend">Friend</option>
<option value="Billboard">Billboard</option>
<option value="Other">Other</option>
</select>
</div>
<!-- Register & Start again buttons -->
<input type="submit" id='submit' value="Register"/>
<input type="submit" id='resetForm' value="Start Again" />
<!-- Print out the details -->
<div id='printDetails'></div>
I Have a feeling this code should work - Hopefully someone sees the problem i',
Ok so after going through your fiddle and I think I got it working with bare minimum code changes.
The main thing was setting up the boolean isValid at the beginning of the submit button event to true and setting to false when it fails a validation test. Then only displaying your output when the form is valid.
Demo
Also, some jQuery selectors were incorrect and I think there is some confusion between gender and sex. They are the same thing, just different words.
There are still is lots of room for improvement but this looks like a homework assignment so I can tell you maybe still learning.
I have found out how to fix one of the issues - The issue I fixed is the duplication of the .after error messages. To fix this I just added $('p').remove('#after5'); inside each if statement before the if statement actually prints the .after error message out.
if($('input[type=checkbox:checked').length < 1) {
$('p').remove('#after5');
$('#checkboxError').html('<p id="after5" style="color:red;" id="after5">Please check atleast one checkbox</p>');
return false;
}
else{
//This should remove the above error message!
$('p').remove('#after5');
}
I am still having problems printing out the data when all the validation is correct!
I have a form where I have replaced the radio buttons with images, and when the images are clicked, they show a darker form of the image to show that it is active, but, I can't quite figure out how to get the darker image to go back to the standard one when I click on a different radio button image. Here is what I've got so far.
$("[name=make]").on({
"click": function() {
var val = $(this).attr('value');
console.log("Value: " + val);
var imgName = "#" + val + "-icon";
$(imgName).attr('src', '/images/make-icons/' + val + '-hover.png');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input id="ford" class="dis-none" type="radio" name="make" value="ford">
<img class="make-icons" src="/images/make-icons/ford.png" id="ford-icon">
</label>
<label>
<input id="chevrolet" class="dis-none" type="radio" name="make" value="chevrolet">
<img class="make-icons" src="/images/make-icons/chevrolet.png" id="chevrolet-icon">
</label>
<label>
<input id="gmc" class="dis-none" type="radio" name="make" value="gmc">
<img class="make-icons" src="/images/make-icons/gmc.png" id="gmc-icon">
</label>
<label>
<input id="dodge" class="dis-none" type="radio" name="make" value="dodge">
<img class="make-icons" src="/images/make-icons/dodge.png" id="dodge-icon">
</label>
<label>
<input id="toyota" class="dis-none" type="radio" name="make" value="toyota">
<img class="make-icons" src="/images/make-icons/toyota.png" id="toyota-icon">
</label>
<label>
<input id="nissan" class="dis-none" type="radio" name="make" value="nissan">
<img class="make-icons" src="/images/make-icons/nissan.png" id="nissan-icon">
</label>
check for the state of the radio
$("[name=make]").on({
"change": function() {
var suffix = '';
if ($(this).is(':checked')) {
suffix = '-hover';
}
var val = $(this).attr('value');
console.log("Value: " + val);
var imgName = "#" + val + "-icon";
$(imgName).attr('src', '/images/make-icons/' + val + suffix + '.png');
}
});
I'm trying to view the value selected in a radio button. The form is:
<form onsubmit="return false;">
<fieldset>
<h3>Textos</h3>
<label>Nombre:</label>
<input type="text" name="nombre"/>
<label>Apellido:</label>
<input type="text" name="apellido" />
<label>Contraseña:</label>
<input type="password" name="contrasena" />
<div class="limpia"></div>
</fieldset>
<fieldset>
<h3>Gustos musicales:</h3>
<label>POP <input type="checkbox" name="pop" value="POP" class="gmusicales"
/></label>
<label>ROCK <input type="checkbox" name="rock" value="ROCK" class="gmusicales"
/></label>
<label>HIP-HOP <input type="checkbox" name="hiphop" value="HIP-HOP"
class="gmusicales"
/></label>
<label>METAL <input type="checkbox" name="metal" value="METAL" class="gmusicales"
/></label>
<div class="limpia"></div>
</fieldset>
<fieldset>
<h3>Sistema operativo</h3>
<label>Windows <input type="radio" name="SO" value="Windows" class="soperativo"/>
</label>
<label>Linux <input type="radio" name="SO" value="Linux" class="soperativo"/>
</label>
<label>Mac <input type="radio" name="SO" value="Mac" class="soperativo"/></label>
<div class="limpia"></div>
</fieldset>
<fieldset>
<input type="reset" value="Borrar"/>
<input type="submit" onclick=muestra() value="Probar" />
<div class="limpia"></div>
</fieldset>
</form>
The problem is in my JavaScript code:
var nom;
var ape;
var con;
var gustos = document.getElementsByClassName("gmusicales");
var sistema = document.getElementById("soperativo");
var resultado;
var i;
var h2 = document.createElement("h2");
function muestra()
{
nom = document.forms[0].elements.nombre.value;
ape = document.forms[0].apellido.value;
con = document.forms[0].contrasena.value;
resultado = nom + " " + ape + " " + con;
for(i=0; i<=gustos.length; i++)
{
if (gustos[i].checked)
{
resultado = resultado + " " + gustos[i].value;
alert(resultado);
}
}
for(i=0; i<=sistema.length; i++)
{
if (sistema[i].checked)
{
resultado = resultado + " " + sistema[i].value;
alert(resultado);
}
}
document.body.appendChild(h2);
document.h2.appenChild(resultado);
}
What I want is to view the values of sistema operativo fieldset. You can choose only one. When I select it, I don't view anything. When I select the other one, that is a checkbox, I can view the values.
I want to create an h2 html tag and to print the values.
How can I do it?
At first you write:
var sistema = document.getElementById("soperativo");
That would give you a single element (uno solo), if there was any.
But in your code, I can see that you have elements with the class soperativo, not an id soperativo.
Use this instead of the line above:
var sistema = document.getElementsByClassName("soperativo");
I know that it's a pure Javascript question.. but how you didn't specified in the question that you want the solution in pure Javascript, here is my solution in jQuery:
$(document).ready(function(){
$('input[type=submit]').click(function(){
$('#resultado').val($('.soperativo:checked').val());
return false;
});
});
http://jsfiddle.net/h9GJa/
More more easy, don't you think?
I have a form with multiple groups of checkboxes (among other things). Some of these groups are mandatory fields (At least one checkbox needs to be checked within that group).
I am able to tell if a group has a checkbox checked, but I failed to make them mandatory. Also I am need to get one long string with the values of the selected checkbox(es). I would need to have a string where if the user checks, say the first 3 checkboxes from group1, the string to be:
"zero | 1 val | 2 val"
The code is a simplified version of my original. Here is the jFiddle: http://jsfiddle.net/QyY2P/1/
Also, for your convenience I am also including the code here:
jQuery:
function countChecked() {
//Group 1
var n = $("#group1 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group1 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection1").text(txt);
alert($(this).val() + " | ");
});
//Group 2
var n = $("#group2 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group2 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection3").text(txt);
alert($(this).val() + " | ");
});
}
countChecked();
$(":checkbox").click(countChecked);
HTML:
<form>
<div id="group1">
<p> *Please select a box (Mandatory)</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="1 val" />
<input type="checkbox" name="ckb_unit[]" value="2 val" />
<input type="checkbox" name="ckb_unit[]" value="3 val" />
<input type="checkbox" name="ckb_unit[]" value="4 val" />
</div>
<div id="group2">
<p>Please select a box</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="A" />
<input type="checkbox" name="ckb_unit[]" value="B" />
<input type="checkbox" name="ckb_unit[]" value="C" />
<input type="checkbox" name="ckb_unit[]" value="D" />
</div>
<div id="group3">
<p>*Please select a box (Mandatory)</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="1 A" />
<input type="checkbox" name="ckb_unit[]" value="2 B" />
<input type="checkbox" name="ckb_unit[]" value="3 C" />
<input type="checkbox" name="ckb_unit[]" value="4 D" />
</div>
</form>
<!-- For debugging purposes -->
<br/>
<div id="count"></div>
<div id="selection1"></div>
<div id="selection3"></div>
PS. I am a beginner, perhaps you noticed it by my not so elegant coding >_<
You can make it mandatory by checking if n is 0 when the user hits submit and then attracting the user's attention towards it somehow (appending an error message, for example). I'm talking about this n:
var n = $("#group1 input:checked").length;
Looking at JSFiddle, it seems you didn't declare txt as a variable, so this works for me:
//Group 1
var txt = ""; // initialise txt with an empty string, so you can append to it later
var n = $("#group1 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group1 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection1").text(txt);
alert($(this).val() + " | ");
});