Javascript, toggle radio button images with the same name - javascript

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');
}
});

Related

Adding values to placeholder using checkbox

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>

How to be simpler in this JavaScript?

I am trying to make a Js to search & filter items in JSON
so I use many radio in the "form" , the result will be [X,X,X,X,X,X]
I will set 50tags x 3(choose), I can feel my function will be large.
What ways can I change my function to be simpler?
function myFunction() {
var elements1 = document.getElementsByName("chair"),
elements2 = document.getElementsByName("car"),
elements3 = document.getElementsByName("house"),
elements4 = document.getElementsByName("tree"),
elements5 = document.getElementsByName("flower"),
elements6 = document.getElementsByName("grass");
var i;
for (var a = "", i = elements1.length; i--;) {
if (elements1[i].checked) {
var a = elements1[i].value;
break;
}
};
for (var b = "", i = elements2.length; i--;) {
if (elements2[i].checked) {
var b = elements2[i].value;
break;
}
};
for (var c = "", i = elements3.length; i--;) {
if (elements3[i].checked) {
var c = elements3[i].value;
break;
}
};
for (var d = "", i = elements4.length; i--;) {
if (elements4[i].checked) {
var d = elements4[i].value;
break;
}
};
for (var e = "", i = elements5.length; i--;) {
if (elements5[i].checked) {
var e = elements5[i].value;
break;
}
};
for (var f = "", i = elements6.length; i--;) {
if (elements6[i].checked) {
var f = elements6[i].value;
break;
}
};
var o2 = document.getElementById("output2");
o2.value = "[" + a + "," + b + "," + c + "," + d + "," + e + "," + f + "]";
o2.innerHTML = o2.value;
}
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter" onclick="myFunction()" /> </div>
</form>
<div id="output2"></div>
Give the form an id, and you can refer to it as an object.
function myFunction() {
var form = document.getElementById("myForm");
var parts = [
form.chair.value,
form.car.value,
form.house.value,
form.tree.value,
form.flower.value,
form.grass.value
];
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
And this is an even simpler solution using a FormData object. It supports an arbitrary number of named form fields without having to actually name them in the function:
function myFunction() {
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
var parts = Array.from(formData.values());
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
Use document.querySelector() to directly select the value of the checked radio button based on element names.
function myFunction() {
var chair = document.querySelector('input[name="chair"]:checked').value;
var car = document.querySelector('input[name="car"]:checked').value;
var house = document.querySelector('input[name="house"]:checked').value;
var tree = document.querySelector('input[name="tree"]:checked').value;
var flower = document.querySelector('input[name="flower"]:checked').value;
var grass = document.querySelector('input[name="grass"]:checked').value;
var o2 = document.getElementById("output2");
o2.value = "[" + chair + "," + car + "," + house + "," + tree + "," + flower + "," + grass + "]";
o2.innerHTML = o2.value;
}
Use arrays!
function myFunction() {
var elem_ids = [ "chair", "car", "house", "tree", "flower", "grass"];
var elems = elem_ids.map(id => document.getElementById(id));
var elems_check_values = elems.map(el => {
// el is kind of an array so
for(var i = 0; i < el.length; ++i)
if(el[i].checked)
return el[i].value;
return undefined;
}).filter(value => value == undefined) // to filter undefined values;
var output = "[" + elems_check_values.join(",") + "]";
var o2 = document.getElementById("output2");
o2.innerHTML = output
}
Your issue can be generalized to: how can I aggregate values for all fields in a given form?
The solution is a function that can be merely as long as 5 lines, and work for any amount of inputs with any type. The DOM model for <form> elements provides named keys (eg, myform.inputName) which each have a value property. For radio buttons, eg myform.tree.value will automatically provide the value of the selected radio button.
With this knowledge, you can create a function with a simple signature that takes a form HTMLElement, and an array of field names for the values that you need, like below: (hit the search button for results, and feel free to change the radio buttons).
function getFormValues(form, fields) {
var result = [];
for (var i = 0; i < fields.length; i++) {
result.push(form[fields[i]].value);
}
return result;
}
document.getElementById('filter').addEventListener('click', function(e) {
var o2 = document.getElementById("output2");
o2.innerHTML = getFormValues(document.forms[0], ['chair','car','house','tree','flower','grass']);
});
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter"/> </div>
</form>
<div id="output2"></div>
The thing you need to do is break the code up into reusable chunks. So make a method to get the value. That will reduce a lot of code. After than, you should look at a way to reduce how many elements you need to list. Finally, find an easy way to fetch all the values.
So below is code that does this. It uses a helper method to get the elements, find the value. Than it uses an array to know what element groups to look for. And finally it uses map to iterate over the list so you do not have to code multiple function calls.
function getSelected (radioBtnGroup) {
// get the elements for the radio button group
var elms = document.getElementsByName(radioBtnGroup)
// loop over them
for(var i=0; i<elms.length; i++) {
// if checked, return value and exit loop
if (elms[i].checked) {
return elms[i].value
}
}
// if nothing is selected, return undefined
return undefined
}
// list the groups you want to get the values for
var groups = ['rb1', 'rb2', 'rb3', 'rb4']
// call when you want to get the values
function getValues () {
// use map to get the values of the rabio button groups.
// map passes the index value as the first argument.
// code is map(function(k){return getSelected(k)})
var results = groups.map(getSelected)
//displat the results
console.log(results);
}
document.querySelector('#btn').addEventListener('click', getValues);
<form>
<fieldset>
<legend>Item 1</legend>
<label><input type="radio" name="rb1" value="1-1"> One</label>
<label><input type="radio" name="rb1" value="1-2"> Two</label>
<label><input type="radio" name="rb1" value="1-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 2</legend>
<label><input type="radio" name="rb2" value="2-1"> One</label>
<label><input type="radio" name="rb2" value="2-2"> Two</label>
<label><input type="radio" name="rb2" value="2-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 3</legend>
<label><input type="radio" name="rb3" value="3-1"> One</label>
<label><input type="radio" name="rb3" value="3-2"> Two</label>
<label><input type="radio" name="rb3" value="3-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 4</legend>
<label><input type="radio" name="rb4" value="4-1"> One</label>
<label><input type="radio" name="rb4" value="4-2"> Two</label>
<label><input type="radio" name="rb4" value="4-3"> Three</label>
</fieldset>
<button type="button" id="btn">Get Results</button>
</form>
Personally I would not store the values in an array, I would use an object with key value pairs.
var results = groups.reduce(function (obj, name) {
obj[name] = getSelected(name)
return obj
}, {});

How can I get a variable image URL?

So I got a project here with a couple of radiobuttons. The plan is to be able to select a base, a lining, color and a shading technique. The blue box to the right serves the purpose of giving the customer a live overview of example outcome of the selected parts. I want to place an image there, with a variable URL.
My plan would be to do something like: "https://www.example.com/images/calculator/base+line+color+shading.png"
Where base is gotten from the base radio input, and could be for example "fullbody"Where line is gotten from the line radio input, and could be for example "clean"Where color is gotten from the color radio input, and could be for example "colored"Where shading is gotten from the shading radio input, and could be for example "ccel"This would leave us with a variable url of "https://www.example.com/images/calculator/fullbody+clean+colored+ccel.png"
At the same time, I don't want them to have to select all of the inputs to get an overview, if they only select "fullbody", the variable URL should become "https://www.example.com/images/calculator/fullbody.png"
The artist I'm doing this for is rapidly increasing the product base and style choices, and I will be updating it over time, so a solution that is expandable with more options over time would be amazing.
As always, thank you for taking your time to read over, any answers or tips/tricks/hints or pointing in directions is greatly appreciated! Enjoy the weekend folks! <3
small overview of my project layout
data-position="1" is for base group
data-position="2" is for line group
data-position="3" is for color group
data-position="4" is for shade group
..
..
data-position="k" will be for kth value group and so on...
See working example here https://jsfiddle.net/y2khfjwp/40/
<div style="width: 50%; float: Left;">
<h2>
Base
</h2>
<input type="radio" name="base" class="main-inputs" data-position="1" value="fullbody" onchange="makeImage(this)"/>Full Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="halfbody" onchange="makeImage(this)"/>Half Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="xyzbody" onchange="makeImage(this)"/>xyz Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="abcbody" onchange="makeImage(this)"/>abc body<br>
<hr>
<h2>
Line
</h2>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean" onchange="makeImage(this)"/>Clean<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean2" onchange="makeImage(this)"/>Clean2<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean3" onchange="makeImage(this)"/>Clean3<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean4" onchange="makeImage(this)"/>Clean4<br>
<hr>
<h2>
Color
</h2>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored" onchange="makeImage(this)"/>Colored<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored2" onchange="makeImage(this)"/>Colored2<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored3" onchange="makeImage(this)"/>Colored3<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored4" onchange="makeImage(this)"/>Colored4<br>
<hr>
<h2>
Shade
</h2>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel" onchange="makeImage(this)"/>Ccel<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel2" onchange="makeImage(this)"/>Ccel2<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel3" onchange="makeImage(this)"/>Ccel3<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel4" onchange="makeImage(this)"/>Ccel4<br>
</div>
<div style="width: 50%; float: Right;">
OutPut: <img id="final-output-src" src="Please select Options" /><br><span id="final-output">Please select Options</span>
</div>
<script>
var path = [];
function makeImage(element)
{
var imagePath = "";
path[element.getAttribute('data-position')] = element.value;
imagePath = finalImagePath();
document.getElementById("final-output-src").src = imagePath;
document.getElementById("final-output").innerHTML = imagePath;
};
function finalImagePath() {
var imageSrc = "https://www.example.com/images/calculator/";
var selections = "";
for(var i=1 ; i<=path.length ; i++) {
if(typeof path[i] != 'undefined' && path[i] != '') {
if(selections == "") {
selections = selections + path[i];
} else {
selections = selections + "+" + path[i];
}
}
}
if(selections != "") {
selections = selections + ".png";
imageSrc = imageSrc + selections;
}
return imageSrc;
}
</script>
Okay here is a solution to generate the image url:
const partials = document.querySelectorAll('#partials input');
const fullBody = document.getElementById('fullbody');
const baseUrl = 'some-root-url.com/';
const fileType = '.png';
let imageUrl = baseUrl + 'some-default-url' + fileType;
// Add Event Listeners
fullBody.addEventListener('change', function(){
let checked = document.querySelectorAll('#partials input:checked');
// deselect each partial
for(let i = 0; i < checked.length; i++){
checked[i].checked = false;
}
// Set the imageUrl var to the fullbody
imageUrl = baseUrl + this.value + fileType;
// see the imageUrl!
console.log(imageUrl);
});
for(let i = 0; i < partials.length; i++){
partials[i].addEventListener('change', function(){
// uncheck fullBody if checked
fullBody.checked = false;
// init the imageUrl
imageUrl = baseUrl;
// loop through each checked option and add the value to the imageUrl
let checked = document.querySelectorAll('#partials input:checked');
for(let i = 0; i < checked.length; i++){
imageUrl += checked[i].value;
}
// add the file type
imageUrl += fileType;
// see the imageUrl!
console.log(imageUrl)
});
}
And here's the corresponding HTML
<div id="partials">
<label for="base">Base</label><input name="base" type="checkbox" value="base" /><br />
<label for="line">Line</label><input name="line" type="checkbox" value="line" /><br />
<label for="color">Color</label><input name="color" type="checkbox" value="color" /><br />
<label for="Shading">Shading</label><input name="shading" type="checkbox" value="shading" />
</div>
<label for="fullbody">Full Body</label><input name="fullbody" id="fullbody" type="checkbox" value="fullbody" />
And a JSFiddle to demo
One tip for you as well, you want to use checkboxes not radio, as radio are designed for single choices not multiselect.
Hope that helps!

Change input type, from radio button to checkbox, jquery

First of this is my very first jQuery script if you have any suggestions don’t be shy.
I'm trying to do the following. I have 3 columns of radio buttons. With a checkbox above. When I check one of those checkboxes the column changes from radio button to checkboxes and there can only be changed one row at the time. My script is doing all that, but I have one problem. When I change the type, all inputs get the same attribute of the first input. I think I should have some sort of loop but I have absolutely no idea how to do this.
So, my question: how can I change my script so that just the type change and not the other attributes?
https://jsfiddle.net/bjc3a9y7/1/
$('input[name="switch"]').change(function() {
var checked = $(this).is(':checked');
$('input[name="switch"]').prop('checked',false);
var brandType = $('input[name="brand"]').prop("type");
var fuelType = $('input[name="fuel"]').prop("type");
var bodyType = $('input[name="body"]').prop("type");
if (brandType == 'checkbox') {
var oldInput = $('input[name="brand"]');
$('input[name="brand"]').replaceWith(
$('<input type="radio" />').
attr("value", oldInput.attr("value")).
attr("name", oldInput.attr("name")).
attr("id", oldInput.attr("id"))
)
} else if (fuelType == 'checkbox') {
var oldInput = $('input[name="fuel"]');
$('input[name="fuel"]').replaceWith(
$('<input type="radio" />').
attr("value", oldInput.attr("value")).
attr("name", oldInput.attr("name")).
attr("id", oldInput.attr("id"))
)
} else if (bodyType == 'checkbox') {
var oldInput = $('input[name="body"]');
$('input[name="body"]').replaceWith(
$('<input type="radio" />').
attr("value", oldInput.attr("value")).
attr("name", oldInput.attr("name")).
attr("id", oldInput.attr("id"))
)
};
if(checked) {
$(this).prop('checked',true);
var id = $(this).attr("id");
var oldInput = $('input[name="' + id + '"]');
$('input[name="' + id + '"]').replaceWith(
$('<input type="checkbox" />').
attr("value", oldInput.attr("value")).
attr("name", oldInput.attr("name")).
attr("id", oldInput.attr("id"))
)
};
});
#container {
display: flex;
flex-direction: row;
}
.filter {
width: 150px;
display: flex;
flex-direction: column;
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<div id='container'>
<div class='filter'>
<header>
Brand <input type='checkbox' id='brand' name='switch' class='switch'>
</header>
<div id='brand'>
<div class='filter-item'>
<span><input type='radio' id='mercedes' name='brand' value='mercedes'></span>
<label for='mercedes'><span></span>Mercedes-benz</label>
</div>
<div class='filter-item'>
<input type='radio' id='bmw' name='brand' class='brand' value='bmw'>
<label for='bmw'><span></span>BMW</label>
</div>
<div class='filter-item'>
<input type='radio' id='audi' name='brand' class='brand' value='audi'>
<label for='audi'><span></span>Audi</label>
</div>
<div class='filter-item'>
<input type='radio' id='ford' name='brand' class='brand' value='ford'>
<label for='ford'><span></span>Ford</label>
</div>
<div class='filter-item'>
<input type='radio' id='dodge' name='brand' class='brand' value='dodge'>
<label for='dodge'><span></span>Dodge</label>
</div>
</div>
</div>
<div class='filter'>
<header>
Fuel <input type='checkbox' id='fuel' name='switch' class='switch'>
</header>
<div class='filter-item'>
<input type='radio' id='diesel' name='fuel' class='fuel' value='diesel'>
<label for='diesel'><span></span>Diesel</label>
</div>
<div class='filter-item'>
<input type='radio' id='gasoline' name='fuel' class='fuel' value='gasoline'>
<label for='gasoline'><span></span>Gasoline</label>
</div>
<div class='filter-item'>
<input type='radio' id='electric' name='fuel' class='fuel' value='electric'>
<label for='electric'><span></span>Electric</label>
</div>
<div class='filter-item'>
<input type='radio' id='other' name='fuel' class='fuel' value='other'>
<label for='other'><span></span>Other</label>
</div>
</div>
<div class='filter'>
<header>
Body <input type='checkbox' id='body' name='switch' class='switch'>
</header>
<div class='filter-item'>
<input type='radio' id='convertible' name='body' class='body' value='convertible'>
<label for='convertible'><span></span>Convertible</label>
</div>
<div class='filter-item'>
<input type='radio' id='coupe' name='body' class='body' value='coupe'>
<label for='coupe'><span></span>Coupe</label>
</div>
<div class='filter-item'>
<input type='radio' id='sedan' name='body' class='body' value='sedan'>
<label for='sedan'><span></span>Sedan</label>
</div>
<div class='filter-item'>
<input type='radio' id='station' name='body' class='body' value='station'>
<label for='station'><span></span>Station wagon</label>
</div>
</div>
</div>
Well I didn't stop trying and finally I got it to work with .each() loops. I added a checkbox selection limitation of 2 as well. I'm new to JQuery so maybe the code isn't as clean as I would like, but it seems to work perfectly.
https://jsfiddle.net/bjc3a9y7/2/
$('input[name="switch"]').change(function() {
var checked = $(this).is(':checked');
$('input[name="switch"]').prop('checked',false);
var arr = ["brand", "fuel", "body"];
$.each( arr, function( i, val ) {
var type = $('input[name="' + val + '"]').prop("type");
if (type == 'checkbox') {
$('input[name="' + val + '"]').each(function(index, value){
var oldInput = $(value);
if(index == 0){
$(value).replaceWith(
$('<input type="radio" />').
prop("value", oldInput.prop("value")).
prop("name", oldInput.prop("name")).
prop("id", oldInput.prop("id")).
prop('checked',true)
)
} else {
$(value).replaceWith(
$('<input type="radio" />').
prop("value", oldInput.prop("value")).
prop("name", oldInput.prop("name")).
prop("id", oldInput.prop("id"))
)
}
});
};
});
if(checked) {
$(this).prop('checked',true);
var id = $(this).prop("id");
$('input[name="' + id + '"]').each(function(index, value){
var oldInput = $(value);
var checked2 = $(value).is(':checked');
if(checked2) {
$(value).replaceWith(
$('<input type="checkbox" />').
prop("value", oldInput.prop("value")).
prop("name", oldInput.prop("name")).
prop("id", oldInput.prop("id")).
prop('checked',true)
)
}else{
$(value).replaceWith(
$('<input type="checkbox" />').
prop("value", oldInput.prop("value")).
prop("name", oldInput.prop("name")).
prop("id", oldInput.prop("id"))
)
}
});
// limit selection checkboxes
$('input[name="' + id + '"]').change(function(){
var max= 2;
if( $('input[name="' + id + '"]:checked').length == max ){
$('input[name="' + id + '"]').prop('disabled', 'disabled');
$('input[name="' + id + '"]:checked').removeProp('disabled');
}else{
$('input[name="' + id + '"]').removeProp('disabled');
}
});
}
});

jQuery: Verify If one of multiple required checkboxes is/are checked

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() + " | ");
});

Categories

Resources